@rr0/ufoathome 0.204.0 → 0.204.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-scene/rr0-scene.mjs +215 -215
- package/dist-embed-sighting/{CaseReportExport-CUy_3oyV.js → CaseReportExport-DQ4bO4eb.js} +1 -1
- package/dist-embed-sighting/SightingMessages_en-Bih7ljAQ.js +1 -0
- package/dist-embed-sighting/SightingMessages_es-CHrrXx-N.js +1 -0
- package/dist-embed-sighting/SightingMessages_fr-B2NUAkiz.js +1 -0
- package/dist-embed-sighting/SightingMessages_it-OGLqMUWg.js +1 -0
- package/dist-embed-sighting/rr0-sighting.mjs +233 -229
- package/dist-embed-sighting-editor/{CaseElement-CC4gimF1.js → CaseElement-zFqMRzIe.js} +2 -2
- package/dist-embed-sighting-editor/{CaseReportExport-DmvvH_GH.js → CaseReportExport-C7dPT0eH.js} +1 -1
- package/{dist-embed-ufoathome/SightingEditorMessages_en-V_dJYjNb.js → dist-embed-sighting-editor/SightingEditorMessages_en-CS2iXwDm.js} +1 -1
- package/{dist-embed-ufoathome/SightingEditorMessages_es-DauDuhPa.js → dist-embed-sighting-editor/SightingEditorMessages_es-C8Vw_4b_.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_fr-zxTvQa2I.js → SightingEditorMessages_fr-AYgrnKFD.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_it-vvaao68O.js → SightingEditorMessages_it-DZyzwScx.js} +1 -1
- package/dist-embed-sighting-editor/{SightingElement-BpYuBmJB.js → SightingElement-Bf654S_I.js} +5 -5
- package/dist-embed-sighting-editor/{SightingLabels_en-dOsFjVRL.js → SightingLabels_en-trAaLk8Q.js} +1 -1
- package/{dist-embed-ufoathome/SightingLabels_es-CKlP2BDO.js → dist-embed-sighting-editor/SightingLabels_es-Geji-Hhz.js} +1 -1
- package/dist-embed-sighting-editor/{SightingLabels_fr-Cpkcf5_9.js → SightingLabels_fr-BVnntoiD.js} +1 -1
- package/{dist-embed-ufoathome/SightingLabels_it-3127rMXm.js → dist-embed-sighting-editor/SightingLabels_it-B9FWbLXW.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_en-Drcr3k4V.js → SightingMessages_en-D90vDTQ7.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_es-BcaWM7Oy.js → SightingMessages_es-D8laK6OY.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_fr-7IYuW095.js → SightingMessages_fr-Gq3IMFTE.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_it-BhDmZn6p.js → SightingMessages_it-BXDxv-lE.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +245 -241
- package/dist-embed-ufoathome/{AdsbLolArchiveProvider-Ck345V92.js → AdsbLolArchiveProvider-JK7ddZzC.js} +1 -1
- package/dist-embed-ufoathome/{Aurora-CMORgA2p.js → Aurora-UBzKnuxt.js} +1 -1
- package/dist-embed-ufoathome/{AuroraEditor-CDZgVOlI.js → AuroraEditor-B0Q9h5C6.js} +1 -1
- package/dist-embed-ufoathome/{AuroraSimulation-DqfSBul6.js → AuroraSimulation-Cj8dyvm4.js} +1 -1
- package/dist-embed-ufoathome/{BallesterGuaspAssessor-DUNQZ9e8.js → BallesterGuaspAssessor-DZ5guaNx.js} +1 -1
- package/dist-embed-ufoathome/{BalloonEditor-Cx3fRab8.js → BalloonEditor-BBAtMeVM.js} +1 -1
- package/dist-embed-ufoathome/{BeamEditor-gxTjO6Pr.js → BeamEditor-Dgo8WSF9.js} +1 -1
- package/dist-embed-ufoathome/{BeamSystem-C8jjTJtB.js → BeamSystem-BbSsBbZk.js} +1 -1
- package/dist-embed-ufoathome/{BodyEditor-DGaBo74A.js → BodyEditor-Cav_-OeQ.js} +1 -1
- package/dist-embed-ufoathome/{CaseEditorElement-BOp207Tr.js → CaseEditorElement-CK82yjEn.js} +6 -6
- package/dist-embed-ufoathome/{CaseElement-BGO5UZLP.js → CaseElement-Bm6xPD0e.js} +3 -3
- package/dist-embed-ufoathome/{CaseReportExport-6DFaJzfO.js → CaseReportExport-D_I2ml6F.js} +3 -3
- package/dist-embed-ufoathome/{ColumnResize-DnX89ynB.js → ColumnResize-DksRZriL.js} +4 -4
- package/dist-embed-ufoathome/{ControlPasses-CeExr5X1.js → ControlPasses-BpLNDq5G.js} +1 -1
- package/dist-embed-ufoathome/{CoverageAssessor-BbqRqh0C.js → CoverageAssessor-UyH_dVvr.js} +1 -1
- package/dist-embed-ufoathome/{Flightradar24Provider-MzQcuUHn.js → Flightradar24Provider-XASYwL-N.js} +1 -1
- package/dist-embed-ufoathome/{GLTFLoader-CPUffC65.js → GLTFLoader-s3EU9qS0.js} +1 -1
- package/dist-embed-ufoathome/{GeoJsonExport-D7QhWNRC.js → GeoJsonExport-BCtJzQ9B.js} +1 -1
- package/dist-embed-ufoathome/{GeographicFigures-BvEeCtxr.js → GeographicFigures-DINsiWL0.js} +1 -1
- package/dist-embed-ufoathome/{HynekAssessor-BwjRkQWT.js → HynekAssessor-D5zxfJ44.js} +1 -1
- package/dist-embed-ufoathome/{InterviewEditorElement-CVCOicLD.js → InterviewEditorElement-CQNMEirl.js} +1 -1
- package/dist-embed-ufoathome/{InterviewElement-ZI42DKRx.js → InterviewElement-BouR8Xii.js} +1 -1
- package/dist-embed-ufoathome/{KmlExport-BX0nxAaA.js → KmlExport-C8zEY6ew.js} +1 -1
- package/dist-embed-ufoathome/{LanternEditor-BROUv-vx.js → LanternEditor-DEeA3Kf_.js} +1 -1
- package/dist-embed-ufoathome/{LaserBeam-ChD9aV-N.js → LaserBeam-CDTsYUwS.js} +1 -1
- package/dist-embed-ufoathome/{LaunchEditor-CM2Wcjv2.js → LaunchEditor-C91_y6bJ.js} +1 -1
- package/dist-embed-ufoathome/{LaunchPlume-DeVRe05u.js → LaunchPlume-Je5cyuGE.js} +1 -1
- package/dist-embed-ufoathome/{LaunchSimulation-RROdYccW.js → LaunchSimulation-BsCQGsdb.js} +1 -1
- package/dist-embed-ufoathome/{ModelSource-nXZ6eIH5.js → ModelSource-7jnvikmB.js} +1 -1
- package/dist-embed-ufoathome/{ModelThumbnails-CRSm49vm.js → ModelThumbnails-DhEg69n0.js} +1 -1
- package/dist-embed-ufoathome/{ModelViewer-BQsl_Nfn.js → ModelViewer-BQJyyY66.js} +1 -1
- package/dist-embed-ufoathome/{ModulesPanelElement-BvzY1GUF.js → ModulesPanelElement-Ct9DMG0-.js} +1 -1
- package/dist-embed-ufoathome/{NearestApproach-DbUpe1iw.js → NearestApproach-BFKGUqFb.js} +1 -1
- package/dist-embed-ufoathome/{PoherAssessor-Dmro58tC.js → PoherAssessor-Cmw5u2Nv.js} +1 -1
- package/dist-embed-ufoathome/{PoherSelfCheck-pcYj_hQ1.js → PoherSelfCheck-BjmenygA.js} +1 -1
- package/dist-embed-ufoathome/{ReentryEditor-Di0KzYeZ.js → ReentryEditor-x_C9chQN.js} +1 -1
- package/dist-embed-ufoathome/{ReentrySimulation-HhdlSVkR.js → ReentrySimulation-D0XIfeyt.js} +1 -1
- package/dist-embed-ufoathome/{ReferenceSystem-B30-UBHY.js → ReferenceSystem-Cv556rkv.js} +1 -1
- package/dist-embed-ufoathome/{ScenarioReadings-EAUAsx9t.js → ScenarioReadings-YJ8iIjyw.js} +1 -1
- package/dist-embed-ufoathome/{ScenarioSweep-jTxLjnaW.js → ScenarioSweep-DTqJSF5a.js} +1 -1
- package/dist-embed-ufoathome/{SearchlightEditor-B6_BW8FD.js → SearchlightEditor-Dy-gMDUN.js} +1 -1
- package/dist-embed-ufoathome/{SearchlightSystem-D_DTpDNC.js → SearchlightSystem-C-qAMIFS.js} +1 -1
- package/dist-embed-ufoathome/{ShareDialogElement-C0oFh0X4.js → ShareDialogElement-DMDY7Hlo.js} +17 -13
- package/dist-embed-ufoathome/Sighting-C1yj2-s5.js +1 -0
- package/{dist-embed-sighting-editor/SightingEditorMessages_en-V_dJYjNb.js → dist-embed-ufoathome/SightingEditorMessages_en-CS2iXwDm.js} +1 -1
- package/{dist-embed-sighting-editor/SightingEditorMessages_es-DauDuhPa.js → dist-embed-ufoathome/SightingEditorMessages_es-C8Vw_4b_.js} +1 -1
- package/dist-embed-ufoathome/{SightingEditorMessages_fr-zxTvQa2I.js → SightingEditorMessages_fr-AYgrnKFD.js} +1 -1
- package/dist-embed-ufoathome/{SightingEditorMessages_it-vvaao68O.js → SightingEditorMessages_it-DZyzwScx.js} +1 -1
- package/dist-embed-ufoathome/{SightingElement-DzxTvvLN.js → SightingElement-DZlh5u4N.js} +5 -5
- package/dist-embed-ufoathome/{SightingLabels_en-dOsFjVRL.js → SightingLabels_en-trAaLk8Q.js} +1 -1
- package/{dist-embed-sighting-editor/SightingLabels_es-CKlP2BDO.js → dist-embed-ufoathome/SightingLabels_es-Geji-Hhz.js} +1 -1
- package/dist-embed-ufoathome/{SightingLabels_fr-Cpkcf5_9.js → SightingLabels_fr-BVnntoiD.js} +1 -1
- package/{dist-embed-sighting-editor/SightingLabels_it-3127rMXm.js → dist-embed-ufoathome/SightingLabels_it-B9FWbLXW.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_en-Drcr3k4V.js → SightingMessages_en-D90vDTQ7.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_es-BcaWM7Oy.js → SightingMessages_es-D8laK6OY.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_fr-7IYuW095.js → SightingMessages_fr-Gq3IMFTE.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_it-BhDmZn6p.js → SightingMessages_it-BXDxv-lE.js} +1 -1
- package/dist-embed-ufoathome/{TraceSystem-CiBRo1aU.js → TraceSystem-DYmjmB9_.js} +1 -1
- package/dist-embed-ufoathome/{VideoButton-BseBKx2r.js → VideoButton-CvAmQpx0.js} +1 -1
- package/dist-embed-ufoathome/rr0-ufoathome.mjs +3 -3
- package/dist-embed-ufoathome/{surroundingsSources-BSh42KUu.js → surroundingsSources-DtoCfflQ.js} +1 -1
- package/dist-embed-ufoathome/{trafficRuntime-BMTtwn7o.js → trafficRuntime-CyYep5Cc.js} +1 -1
- package/package.json +1 -1
- package/dist-embed-sighting/SightingMessages_en-DKFVZnDu.js +0 -1
- package/dist-embed-sighting/SightingMessages_es-DYQlWvm0.js +0 -1
- package/dist-embed-sighting/SightingMessages_fr-BygVDDY9.js +0 -1
- package/dist-embed-sighting/SightingMessages_it-BI7GnXPz.js +0 -1
- package/dist-embed-ufoathome/Sighting-BX_CmDY2.js +0 -1
package/dist-embed-ufoathome/{ShareDialogElement-C0oFh0X4.js → ShareDialogElement-DMDY7Hlo.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./VideoButton-
|
|
2
|
-
import{F as ku,P as as,S as Nr,H as pn,s as pr,U as gr,B as kp,_ as H,a as Uf,J as Lp,M as Sn,g as ke,j as Oc,t as Lh,q as Tn,d as Np,K as Cp}from"./rr0-ufoathome.mjs";import{A as he,c as pt,I as je,H as Nh,T as Gf,l as Bf,O as od,W as rd,n as cd,p as ai,k as oo,f as Vf,s as Wf,o as _p,b as Qa,r as Kf,F as Wo,h as zp,q as Fp,a as Hp,t as Yf,u as Ko}from"./Sighting-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./VideoButton-CvAmQpx0.js","./rr0-ufoathome.mjs","./Sighting-C1yj2-s5.js","./VisualAids-DI-hEL46.js","./three.module-CbaHqYFq.js","./SaidPosition-OJEYhVKN.js","./GeoProjection-DvqDbRIx.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./xyzImageryRaster-Dhxs0B26.js","./Obstacles-v9SkfBD7.js","./PoherSelfCheck-BjmenygA.js","./PoherMatrix-C2fcLqDH.js","./CoverageAssessor-UyH_dVvr.js","./HynekAssessor-D5zxfJ44.js","./NearestApproach-BFKGUqFb.js","./BallesterGuaspAssessor-DZ5guaNx.js","./Account-C4jhsVtN.js","./PoherAssessor-Cmw5u2Nv.js","./RoadMarkings-DKUNImjj.js","./BeamSystem-BbSsBbZk.js","./LaserBeam-CDTsYUwS.js","./BeamEditor-Dgo8WSF9.js","./SkyEventEditorStyle-CvY_AhbI.js","./ParameterForm-XbqxCLRn.js","./TimelineTracks-Daaqw9ly.js","./LaunchSimulation-BsCQGsdb.js","./LaunchPlume-Je5cyuGE.js","./LaunchEditor-C91_y6bJ.js","./ReentrySimulation-D0XIfeyt.js","./ReentryEditor-x_C9chQN.js","./ReentryArchive-CeXHrU7L.js","./AuroraSimulation-Cj8dyvm4.js","./Aurora-UBzKnuxt.js","./AuroraEditor-B0Q9h5C6.js","./SearchlightSystem-C-qAMIFS.js","./SearchlightEditor-Dy-gMDUN.js","./GLTFLoader-s3EU9qS0.js","./WaterSystem-BNxlYNtW.js","./RailwaySystem-KlBj8mLP.js","./TraceSystem-DYmjmB9_.js","./ContrailSystem-D2AR5Zgy.js","./ContrailGrowth-DwHS8If9.js","./HeadlightSystem-D5-78PFB.js","./ControlPasses-BpLNDq5G.js","./ReferenceSystem-Cv556rkv.js","./ReferenceTimeline-2kBldQeG.js","./PictureFetch-C3wgf1ZV.js","./AdsbLolArchiveProvider-JK7ddZzC.js","./Flightradar24Provider-XASYwL-N.js","./trafficRuntime-CyYep5Cc.js","./upperAirSources-BU0pD84c.js","./ModuleSession-Dac4fD0X.js","./GenerativeKit-BmhvjjzB.js","./browser-CltifEM0.js","./VideoExport-B8ZhHNnd.js","./GenerativeKitMessages-BwG7cWZX.js","./ShareCodeEditor-DyEYu_9d.js","./index-C8cdeM8E.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{F as ku,P as as,S as Nr,H as pn,s as pr,U as gr,B as kp,_ as H,a as Uf,J as Lp,M as Sn,g as ke,j as Oc,t as Lh,q as Tn,d as Np,K as Cp}from"./rr0-ufoathome.mjs";import{A as he,c as pt,I as je,H as Nh,T as Gf,l as Bf,O as od,W as rd,n as cd,p as ai,k as oo,f as Vf,s as Wf,o as _p,b as Qa,r as Kf,F as Wo,h as zp,q as Fp,a as Hp,t as Yf,u as Ko}from"./Sighting-C1yj2-s5.js";import{V as D,Q as Oa,E as $f,C as q,S as Lt,B as Ai,a as Ge,D as Up,R as Nl,L as Xt,b as Br,M as B,c as ri,d as Zi,H as oe,e as Ws,A as rs,f as Xe,g as Fo,O as Ho,h as Xf,N as qf,i as Pa,j as ht,k as hd,l as Gp,Z as gn,m as js,n as Ji,o as ro,P as hi,W as ye,p as Ns,q as ld,r as Vs,F as Mr,s as yi,t as jf,u as Uc,v as Bp,w as le,x as Ot,y as Qn,z as Uo,G as ci,I as Ft,J as Us,K as $s,T as tn,U as Cl,X as Zf,Y as ud,_ as dd,$ as Go,a0 as qe,a1 as os,a2 as Oe,a3 as _l,a4 as Xs,a5 as fd,a6 as Vp,a7 as Wp,a8 as ee,a9 as vh,aa as Gc,ab as yh,ac as Jf,ad as Qf,ae as un,af as Pc,ag as Kp,ah as to,ai as kc,aj as Yp,ak as $p,al as Xp,am as qp,an as jp,ao as tm,ap as Zp,aq as bn,ar as eo,as as em,at as sm,au as md,av as zl,aw as Jp,ax as Qp,ay as tg,az as eg,aA as sg}from"./three.module-CbaHqYFq.js";import{S as pd,I as ig,a as ur,P as ng}from"./SaidPosition-OJEYhVKN.js";import{l as Fl,i as im,e as nm,r as wi,c as Bo,h as am,a as Bc,D as Vc,f as ag,F as og,g as rg,j as Lu,k as om,m as cg,b as hg,n as lg,H as Hl,p as gd,q as Md}from"./Decor-Dn-cvniW.js";import{g as ot,l as Ks}from"./GeoProjection-DvqDbRIx.js";import{R as vd}from"./RecordingIssue-BlWT8Xsu.js";import{f as rm,a as cm,A as hm}from"./xyzImageryRaster-Dhxs0B26.js";import{O as yd}from"./Obstacles-v9SkfBD7.js";/**
|
|
3
3
|
@preserve
|
|
4
4
|
|
|
5
5
|
Astronomy library for JavaScript (browser and Node.js).
|
|
@@ -1565,11 +1565,11 @@ canvas[data-cursor="rotate"] {
|
|
|
1565
1565
|
white-space: nowrap;
|
|
1566
1566
|
}
|
|
1567
1567
|
`;class ko{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const s of t.observerTrack.allKeyframes){const{lat:i,lng:n,headingDeg:a}=s.pose;i===void 0||n===void 0||e.push({t:s.t,lat:i,lng:n,headingDeg:a})}if(e.length===0){const s=t.event.place?.[0];if(!s)return;e.push({t:0,lat:s.lat,lng:s.lng})}return new ko(e)}static TRAVEL_M=50;get travels(){return this.spanM>ko.TRAVEL_M}get moved(){return this.spanM>ko.STATIONARY_M}get spanM(){const t=this.box,e=(t.south+t.north)/2,s=(t.west+t.east)/2;return Math.max(Math.abs(ot(e,t.east,e,t.west).x),Math.abs(ot(t.north,s,t.south,s).z))}get center(){const t=this.box;return{lat:(t.south+t.north)/2,lng:(t.west+t.east)/2}}boundsAround(t,e){const{lat:s,lng:i}=this.center,n=Math.max(this.spanM*(1+e),t)/2;return{north:Ks(0,-n,s,i).lat,south:Ks(0,n,s,i).lat,east:Ks(n,0,s,i).lng,west:Ks(-n,0,s,i).lng}}get box(){const t=this.points.map(s=>s.lat),e=this.points.map(s=>s.lng);return{south:Math.min(...t),north:Math.max(...t),west:Math.min(...e),east:Math.max(...e)}}}class Qs{constructor(t,e){this.rotationPassed=t,this.scale=e}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(t,e=0){const s=t.instrumentAt(e);if(s.mounted)return;const i=t.event.tags?.includes("paralysis")||(t.exposureAt(e)??0)>Qs.HAND_HELD_S,n=t.sway??(i?0:1);if(n>0)return new Qs(Math.max(1-(s.stabilization??0),Qs.GAZE_DRIFT_SHARE),n)}offsetAt(t){const e=t/1e3,s=this.scale,i=(l,d)=>Math.sin(2*Math.PI*l*e+d),[n,a,o,r,c,h]=Qs.HZ;return{eastM:s*Qs.SWAY_M*(.7*i(n,.3)+.3*i(r,1.9)),northM:s*Qs.SWAY_M*(.6*i(o,2.2)+.4*i(c,.8)),upM:s*Qs.BREATH_M*i(a,0),yawDeg:s*this.rotationPassed*Qs.DRIFT_YAW_DEG*(.6*i(h,1.1)+.4*i(r,2.7)),pitchDeg:s*this.rotationPassed*Qs.DRIFT_PITCH_DEG*(.5*i(a,1.6)+.5*i(o,.4)),rollDeg:s*this.rotationPassed*Qs.DRIFT_ROLL_DEG*i(n,2.9)}}}class Bt{constructor(t,e){this.stretches=t,this.rotationPassed=e}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(t,e=0){const s=ko.of(t);if(!s||s.points.length<2)return;const i=[];let n=0;for(let a=1;a<s.points.length;a++){const o=s.points[a-1],r=s.points[a],c=(r.t-o.t)/1e3;if(c<=0)continue;const h=ot(r.lat,r.lng,o.lat,o.lng),l=h.x,d=-h.z,f=Math.hypot(l,d),m=f/c,p=Bt.stepHzFor(m);i.push({startMs:o.t,endMs:r.t,speedMPerS:m,eastUnit:f>0?l/f:0,northUnit:f>0?d/f:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*c}for(let a=0;a<i.length;a++){const o=i[a-1],r=i[a+1];i[a].rampsIn=o===void 0||o.stepHz===0,i[a].rampsOut=r===void 0||r.stepHz===0}if(i.some(a=>a.stepHz>0))return new Bt(i,1-(t.instrumentAt(e).stabilization??0))}static bodyAt(t,e,s=!1){const i=Bt.of(t,e)?.offsetAt(e)??Bt.STILL;return s?i:Bt.add(i,Qs.of(t,e)?.offsetAt(e))}static stepHzFor(t){return t<Bt.SLOWEST_WALK_M_PER_S||t>Bt.FASTEST_WALK_M_PER_S?0:Bt.REFERENCE_STEP_HZ*Math.pow(t/Bt.REFERENCE_SPEED_M_PER_S,Bt.CADENCE_EXPONENT)}offsetAt(t){return Bt.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const s=e.speedMPerS/Bt.REFERENCE_SPEED_M_PER_S,i=(o,r,c,h)=>{if(o<0||o>Bt.JOLT_LASTS_MS)return;const l=o/1e3,d=Math.exp(-l/Bt.JOLT_DECAY_S)*Math.sin(2*Math.PI*Bt.JOLT_HZ*l),f=h*r*s*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*c*s*d*this.rotationPassed,yawDeg:0}},n=e.rampsOut?i(t-e.endMs,Bt.STOP_LURCH_M,Bt.STOP_PITCH_DEG,1):void 0;if(n)return n;const a=e.rampsIn?i(t-e.startMs,Bt.START_LURCH_M,Bt.START_PITCH_DEG,-1):void 0;if(a)return a}}static add(t,e){return e?{eastM:t.eastM+e.eastM,northM:t.northM+e.northM,upM:t.upM+e.upM,rollDeg:t.rollDeg+e.rollDeg,pitchDeg:t.pitchDeg+e.pitchDeg,yawDeg:t.yawDeg+e.yawDeg}:t}cycleAt(t){const e=this.stretches.find(r=>t>=r.startMs&&t<=r.endMs);if(!e||e.stepHz===0)return Bt.STILL;const s=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,i=2*Math.PI*s,n=this.amplitudeAt(e,t),a=Bt.SWAY_M*n*Math.cos(i/2),o=n*this.rotationPassed*e.speedMPerS/Bt.REFERENCE_SPEED_M_PER_S;return{eastM:a*e.northUnit,northM:-a*e.eastUnit,upM:Bt.RISE_M_PER_M_PER_S*e.speedMPerS*n*Math.cos(i),rollDeg:Bt.HEAD_ROLL_DEG*o*Math.cos(i/2),pitchDeg:-1.25*o*Math.cos(i),yawDeg:Bt.HEAD_YAW_DEG*o*Math.cos(i/2)}}amplitudeAt(t,e){const s=1e3/t.stepHz,i=Math.min(s,(t.endMs-t.startMs)/2);if(i<=0)return 1;const n=e-t.startMs,a=t.endMs-e,o=Math.min(t.rampsIn?n/i:1,t.rampsOut?a/i:1,1);return(1-Math.cos(Math.PI*Math.max(o,0)))/2}}class z1{constructor(t,e){this.timeline=t,this.onFrame=e}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const t=()=>{if(this.state!=="playing")return;const e=performance.now();if(this.currentT+=(e-this.lastWallTime)*this.playbackRate,this.lastWallTime=e,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(t){this.currentT=Math.max(0,Math.min(t,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(t){const e=new Map;for(const s of this.timeline.sourceIds){const i=this.timeline.getInterpolatedShapeAt(t,s);i&&e.set(s,i)}this.onFrame(t,e)}}const Hm=["nw","n","ne","e","se","s","sw","w"],F1=24,uo=8,H1=3,U1=8;function mr(u,t,e){const s=u.x-t.x,i=u.y-t.y,n=Math.cos(e),a=Math.sin(e);return{x:t.x+s*n-i*a,y:t.y+s*a+i*n}}function ca(u){return{x:u.x+u.width/2,y:u.y+u.height/2}}const G1={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class Es{static handlePointsFor(t){const{x:e,y:s,width:i,height:n}=t.bounds,a={nw:{x:e,y:s},n:{x:e+i/2,y:s},ne:{x:e+i,y:s},e:{x:e+i,y:s+n/2},se:{x:e+i,y:s+n},s:{x:e+i/2,y:s+n},sw:{x:e,y:s+n},w:{x:e,y:s+n/2},rotate:{x:e+i/2,y:s-F1}},o=ca(t.bounds),r={};for(const c of Object.keys(a))r[c]=mr(a[c],o,t.angle);return r}static hitTestHandle(t,e,s=8,i=[...Hm,"rotate"]){const n=Es.handlePointsFor(t);for(const a of i)if(Math.hypot(e.x-n[a].x,e.y-n[a].y)<=s)return a}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(t,e){const i=((Es.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,n=["ew","nwse","ns","nesw"];return n[Math.round(i)%n.length]}static resizeBounds(t,e,s,i){const n=ca(t),a=mr(i,n,-e),{x:o,y:r,width:c,height:h}=t,l=G1[s];let d=o,f=r,m=o+c,p=r+h;return l.left&&(d=Math.min(a.x,m-uo)),l.right&&(m=Math.max(a.x,d+uo)),l.top&&(f=Math.min(a.y,p-uo)),l.bottom&&(p=Math.max(a.y,f+uo)),{x:d,y:f,width:m-d,height:p-f}}static resizeShape(t,e,s){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:i,height:n}=t.bounds,a=Es.resizeBounds(t.bounds,t.angle,e,s);if(t.kind==="oval")return{...t,bounds:a};const o=i===0?1:a.width/i,r=n===0?1:a.height/n;return{...t,bounds:a,points:t.points.map(c=>({x:c.x*o,y:c.y*r}))}}static rotateShape(t,e){const s=ca(t.bounds),i=Math.atan2(e.y-s.y,e.x-s.x)+Math.PI/2;return{...t,angle:i}}static groupBoundsFor(t){const e=Math.min(...t.map(a=>a.x)),s=Math.min(...t.map(a=>a.y)),i=Math.max(...t.map(a=>a.x+a.width)),n=Math.max(...t.map(a=>a.y+a.height));return{x:e,y:s,width:i-e,height:n-s}}static vertexPointsFor(t){const e=ca(t.bounds);return t.points.map(s=>mr({x:t.bounds.x+s.x,y:t.bounds.y+s.y},e,t.angle))}static hitTestVertex(t,e,s=U1){const i=Es.vertexPointsFor(t);let n,a=s;return i.forEach((o,r)=>{const c=Math.hypot(e.x-o.x,e.y-o.y);c<=a&&(a=c,n=r)}),n}static toLocalPoint(t,e){const s=ca(t.bounds),i=mr(e,s,-t.angle);return{x:i.x-t.bounds.x,y:i.y-t.bounds.y}}static moveVertex(t,e,s){const i=t.points.map((l,d)=>d===e?Es.toLocalPoint(t,s):l),n=Math.min(...i.map(l=>l.x)),a=Math.min(...i.map(l=>l.y)),o=Math.max(...i.map(l=>l.x)),r=Math.max(...i.map(l=>l.y)),c={x:t.bounds.x+n,y:t.bounds.y+a,width:o-n,height:r-a},h=i.map(l=>({x:l.x-n,y:l.y-a}));return{...t,bounds:c,points:h}}static insertVertexNear(t,e){const s=Es.toLocalPoint(t,e),{points:i}=t;let n=i.length-1,a=1/0;for(let r=0;r<i.length;r++){const c=i[r],h=i[(r+1)%i.length],l=Es.distanceToSegment(s,c,h);l<a&&(a=l,n=r)}const o=[...i.slice(0,n+1),s,...i.slice(n+1)];return{...t,points:o}}static distanceToSegment(t,e,s){const i=s.x-e.x,n=s.y-e.y,a=i*i+n*n,o=a===0?0:Math.max(0,Math.min(1,((t.x-e.x)*i+(t.y-e.y)*n)/a)),r=e.x+o*i,c=e.y+o*n;return Math.hypot(t.x-r,t.y-c)}static deleteVertex(t,e){return t.points.length<=H1?t:{...t,points:t.points.filter((s,i)=>i!==e)}}}class Xw{constructor(t){this.members=t}bounds(){return Es.groupBoundsFor(this.members.map(t=>t.shape.bounds))}scaleTo(t){const e=this.bounds(),s=e.width===0?1:t.width/e.width,i=e.height===0?1:t.height/e.height;return this.members.map(({sourceId:n,shape:a})=>{const o=Math.max(a.bounds.width*s,uo),r=Math.max(a.bounds.height*i,uo),c=t.x+(a.bounds.x-e.x)*s,h=t.y+(a.bounds.y-e.y)*i,l={x:c,y:h,width:o,height:r};return a.kind==="oval"?{sourceId:n,shape:{...a,bounds:l}}:{sourceId:n,shape:{...a,bounds:l,points:a.points.map(d=>({x:d.x*s,y:d.y*i}))}}})}resize(t,e){return this.scaleTo(Es.resizeBounds(this.bounds(),0,t,e))}rotate(t,e){const s=ca(this.bounds()),i=a=>Math.atan2(a.y-s.y,a.x-s.x),n=i(t)-i(e);return this.members.map(({sourceId:a,shape:o})=>{const r=ca(o.bounds),c=mr(r,s,n),h={x:c.x-o.bounds.width/2,y:c.y-o.bounds.height/2,width:o.bounds.width,height:o.bounds.height};return{sourceId:a,shape:{...o,bounds:h,angle:o.angle+n}}})}}const nu=6,Qr=nu/2,Nd=20,Cd=24,_d=9,zd=6,Fd=7,Hd=6,Si=4;class Vo{constructor(t){this.ctx=t}starPoints=0;roll=0;clear(t,e){this.ctx.clearRect(0,0,t,e)}static paintExtent(t){const{x:e,y:s,width:i,height:n}=t.bounds,a=e+i/2,o=s+n/2,r=t.angle%(2*Math.PI)!==0,c=Math.hypot(i,n)/2,h=r?c:i/2,l=r?c:n/2,d=Math.max(i,n)/2,f=t.brightness??0,m=f>0?Math.max(d*(1+_d*f),Hd*f)-d:0,p=f>0?d*(1+Fd*f)-d:0,g=3*Cd*(t.blur??0)+1.5*Nd*t.haloScale,M=Math.max(m,p,0)+g+2;return{x:a-h-M,y:o-l-M,width:2*(h+M),height:2*(l+M)}}paintInto(t,e,s,i=!1){this.ctx.save(),this.ctx.scale(s,s),this.ctx.translate(-e.x,-e.y);const n=t.selected?{...t,selected:!1}:t;i?this.paintGhost(n,1.5):this.paintShape(n),this.ctx.restore()}paintShape(t){this.ctx.save(),this.ctx.globalAlpha=1-t.transparency;const e=t.blur??0;e>0&&(this.ctx.filter=`blur(${(Cd*e).toFixed(2)}px)`);const s=t.brightness??0;s>0&&this.paintDazzle(t,s),t.haloScale>0&&this.paintHalo(t),this.paintBase(t),this.ctx.restore(),t.selected&&this.paintSelectionHandles(t)}setStarPoints(t){this.starPoints=Math.max(0,Math.floor(t))}setRoll(t){this.roll=t}paintDazzle(t,e){const{x:s,y:i,width:n,height:a}=t.bounds,o=s+n/2,r=i+a/2,c=Math.max(n,a)/2,h=Math.max(c*(1+_d*e),Hd*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const l=this.ctx.createRadialGradient(o,r,0,o,r,h);for(let d=0;d<=zd;d++){const f=d/zd,m=1/(1+24*f*f);this.ctx.globalAlpha=1,l.addColorStop(f,this.withAlpha(t.color,m*e*.55))}if(this.ctx.fillStyle=l,this.ctx.beginPath(),this.ctx.arc(o,r,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=c*(1+Fd*e);this.ctx.lineWidth=Math.max(1,c*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const m=f/this.starPoints*Math.PI*2+this.roll,p=o+Math.cos(m)*d,g=r+Math.sin(m)*d,M=this.ctx.createLinearGradient(o,r,p,g);M.addColorStop(0,this.withAlpha(t.color,e*.55)),M.addColorStop(.35,this.withAlpha(t.color,e*.22)),M.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=M,this.ctx.beginPath(),this.ctx.moveTo(o,r),this.ctx.lineTo(p,g),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const s=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!s)return t.color;const i=Number.parseInt(s[1],16),n=a=>Math.round(a+(255-a)*e);return`rgb(${n(i>>16&255)}, ${n(i>>8&255)}, ${n(i&255)})`}withAlpha(t,e){const s=Math.max(0,Math.min(1,e)),i=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!i)return t;const n=Number.parseInt(i[1],16);return`rgba(${n>>16&255}, ${n>>8&255}, ${n&255}, ${s.toFixed(3)})`}paintBase(t){this.ctx.fillStyle=this.dazzledFill(t,t.brightness??0),this.tracePath(t),this.ctx.fill()}paintGhost(t,e){this.ctx.save(),this.tracePath(t),this.ctx.setLineDash([e*3,e*2]),this.ctx.lineWidth=e,this.ctx.strokeStyle=t.color,this.ctx.stroke(),this.ctx.restore()}tracePath(t){if(this.ctx.beginPath(),t.kind==="oval"){const{x:e,y:s,width:i,height:n}=t.bounds,a=i/2,o=n/2;this.ctx.ellipse(e+a,s+o,a,o,t.angle,0,2*Math.PI)}else{const{x:e,y:s,width:i,height:n}=t.bounds;this.ctx.save(),this.ctx.translate(e+i/2,s+n/2),this.ctx.rotate(t.angle),this.ctx.translate(-i/2,-n/2),t.points.forEach((a,o)=>{o===0?this.ctx.moveTo(a.x,a.y):this.ctx.lineTo(a.x,a.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=Nd*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(Es.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of Es.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Si,Si,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(Es.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,s){const i=this.ctx;if(i.save(),t&&t.length===4){i.strokeStyle="#39f",i.lineWidth=1.5,i.setLineDash([6,4]),i.beginPath(),i.moveTo(t[0].x,t[0].y);for(const n of t.slice(1))i.lineTo(n.x,n.y);i.closePath(),i.stroke(),i.setLineDash([])}for(const n of e){const a=Vo.landmarkColour(n.residualDeg),o=n.selected?3:2;n.selected&&(i.strokeStyle="#fff",i.lineWidth=o+3,i.beginPath(),i.ellipse(n.picture.x,n.picture.y,Si+2,Si+2,0,0,2*Math.PI),i.stroke()),n.scene&&(i.strokeStyle=a,i.lineWidth=1,i.beginPath(),i.moveTo(n.picture.x,n.picture.y),i.lineTo(n.scene.x,n.scene.y),i.stroke(),i.fillStyle=a,i.beginPath(),i.ellipse(n.scene.x,n.scene.y,Si,Si,0,0,2*Math.PI),i.fill()),i.strokeStyle=a,i.lineWidth=o,i.beginPath(),i.ellipse(n.picture.x,n.picture.y,Si+2,Si+2,0,0,2*Math.PI),i.stroke(),this.paintLabel(n.label,n.picture.x+Si+5,n.picture.y-Si-2,a)}s&&this.paintLabel(s,8,8,"#fff",13),i.restore()}paintGhosts(t,e,s){const i=this.ctx;i.save();const n=(r,c,h,l=[])=>{i.setLineDash(l),i.lineWidth=h+2,i.strokeStyle="rgba(0, 0, 0, 0.6)",r(),i.lineWidth=h,i.strokeStyle=c,r(),i.setLineDash([])},a=(r,c)=>()=>{i.beginPath(),i.arc(r.x,r.y,c,0,2*Math.PI),i.stroke()},o=(r,c,h)=>()=>{const[l,d]=h?[c,c]:[c,0];i.beginPath(),i.moveTo(r.x-l,r.y-d),i.lineTo(r.x+l,r.y+d),i.moveTo(r.x+d,r.y-l),i.lineTo(r.x-d,r.y+l),i.stroke()};for(const r of t)n(()=>{i.beginPath(),i.moveTo(r.ghost.x,r.ghost.y),i.lineTo(r.light.x,r.light.y),i.stroke()},"rgba(255, 255, 255, 0.85)",1,[4,4]),n(a(r.light,7),"#ffffff",1.5),n(a(r.ghost,Math.max(9,r.ghostRadius)),"#ffd23f",2);e&&n(o(e,8,!1),"#ffd23f",2),s&&n(o(s,5,!0),"rgba(255, 255, 255, 0.7)",1),i.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,s,i,n=11){const a=this.ctx;a.save(),a.font=`${n}px system-ui, sans-serif`,a.textBaseline="top";const o=a.measureText(t).width;a.fillStyle="rgba(0, 0, 0, 0.6)",a.fillRect(e-3,s-2,o+6,n+4),a.fillStyle=i,a.fillText(t,e,s),a.restore()}paintGroupHandles(t){this.paintHandleFrame(Es.handlePointsFor({bounds:t,angle:0}),{includeRotate:!0})}paintOutline(t){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(t.nw.x,t.nw.y),this.ctx.lineTo(t.ne.x,t.ne.y),this.ctx.lineTo(t.se.x,t.se.y),this.ctx.lineTo(t.sw.x,t.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(t,{includeRotate:e}){this.paintOutline(t),this.ctx.fillStyle="lightgray";for(const s of Hm){const i=t[s];this.ctx.fillRect(i.x-Qr,i.y-Qr,nu,nu)}e&&(this.ctx.beginPath(),this.ctx.moveTo(t.n.x,t.n.y),this.ctx.lineTo(t.rotate.x,t.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(t.rotate.x,t.rotate.y,Qr+1,Qr+1,0,0,2*Math.PI),this.ctx.fill())}}class qs{static sessionDeclared=!1;static isLive(t){return t!==void 0&&typeof AudioContext<"u"&&t instanceof AudioContext}static unlock(t){if(qs.declarePlayback(),t.state!=="running")try{Promise.resolve(t.resume()).catch(()=>{});const e=t.createBufferSource();e.buffer=t.createBuffer(1,1,22050),e.connect(t.destination),e.start(0)}catch{}}static declarePlayback(){if(!(qs.sessionDeclared||typeof navigator>"u")){qs.sessionDeclared=!0;try{const t=navigator.audioSession;t&&(t.type="playback")}catch{}}}}const Ud=.05,Gd=.08,Bd=2,Vd=3,B1=14,V1=.02;class Wd{context;constructor(t){this.context=t}voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}qs.isLive(this.context)&&qs.unlock(this.context)}setSound(t){if(this.requested=t,!this.context)return;const e=this.keyFor(t);if(!e){this.silence();return}if(this.voice?.key!==e){this.stopVoice();const s=++this.voiceToken;e.startsWith("src:")?this.buildRecordedVoice(t.src,e,s):this.voice=this.buildSynthesizedVoice(t,e)}this.applyTo(this.voice,t)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),qs.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const s=this.context;if(!t||!s)return;const i=s.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,i,Ud);for(const{param:n,ratio:a}of t.pitch)n.setTargetAtTime(Math.min(e.pitchHz*a,s.sampleRate/2-1),i,Ud)}buildSynthesizedVoice(t,e){const s=this.context;if(s)switch(t.kind){case"hum":return this.buildHum(s,e);case"whistle":return this.buildWhistle(s,e);case"rumble":return this.buildRumble(s,e);case"crackle":return this.buildCrackle(s,e);default:return}}buildHum(t,e){const s=t.createOscillator();s.type="sawtooth";const i=t.createOscillator();i.type="sawtooth";const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=1;const a=t.createGain();return a.gain.value=0,s.connect(n),i.connect(n),n.connect(a).connect(this.output(t)),s.start(),i.start(),{key:e,nodes:[n,a],sources:[s,i],volumeParam:a.gain,gainScale:.16,pitch:[{param:s.frequency,ratio:1},{param:i.frequency,ratio:1.006},{param:n.frequency,ratio:6}]}}buildWhistle(t,e){const s=t.createOscillator();s.type="sine";const i=t.createOscillator();i.type="sine",i.frequency.value=5;const n=t.createGain(),a=t.createGain();return a.gain.value=0,i.connect(n).connect(s.frequency),s.connect(a).connect(this.output(t)),s.start(),i.start(),{key:e,nodes:[n,a],sources:[s,i],volumeParam:a.gain,gainScale:.22,pitch:[{param:s.frequency,ratio:1},{param:n.gain,ratio:.012}]}}buildRumble(t,e){const s=t.createBufferSource();s.buffer=this.brownNoise(t),s.loop=!0;const i=t.createBiquadFilter();i.type="lowpass",i.Q.value=.8;const n=t.createGain();return n.gain.value=0,s.connect(i).connect(n).connect(this.output(t)),s.start(),{key:e,nodes:[i,n],sources:[s],volumeParam:n.gain,gainScale:1.4,pitch:[{param:i.frequency,ratio:1}]}}buildCrackle(t,e){const s=t.createBufferSource();s.buffer=this.whiteNoise(t),s.loop=!0;const i=t.createBiquadFilter();i.type="bandpass",i.Q.value=1.2;const n=t.createGain();n.gain.value=0;const a=t.createBufferSource();a.buffer=this.crackleEnvelope(t),a.loop=!0;const o=t.createGain();return o.gain.value=0,a.connect(o).connect(n.gain),s.connect(i).connect(n).connect(this.output(t)),s.start(),a.start(),{key:e,nodes:[i,n,o],sources:[s,a],volumeParam:o.gain,gainScale:.9,pitch:[{param:i.frequency,ratio:4}]}}async buildRecordedVoice(t,e,s){const i=this.context;if(!i)return;let n;try{n=await this.getBuffer(t)}catch(r){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",r);return}if(s!==this.voiceToken||!this.context)return;const a=i.createBufferSource();a.buffer=n,a.loop=!0;const o=i.createGain();o.gain.value=0,a.connect(o).connect(this.output(i)),a.start(),this.voice={key:e,nodes:[o],sources:[a],volumeParam:o.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(t){const e=this.context;if(!e)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let s=this.buffers.get(t);return s||(s=fetch(t).then(i=>{if(!i.ok)throw new Error(`Audio fetch failed (${i.status}): ${t}`);return i.arrayBuffer()}).then(i=>e.decodeAudioData(i)),this.buffers.set(t,s)),s}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*Bd),t.sampleRate),s=e.getChannelData(0);for(let i=0;i<s.length;i++)s[i]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*Bd),t.sampleRate),s=e.getChannelData(0);let i=0,n=0;for(let a=0;a<s.length;a++)i=(i+.02*(Math.random()*2-1))/1.02,s[a]=i,n=Math.max(n,Math.abs(i));if(n>0)for(let a=0;a<s.length;a++)s[a]/=n;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*Vd),t.sampleRate),s=e.getChannelData(0),i=Math.max(1,Math.floor(V1*t.sampleRate)),n=Math.round(Vd*B1);for(let a=0;a<n;a++){const o=Math.floor(Math.random()*s.length),r=.4+Math.random()*.6;for(let c=0;c<i&&o+c<s.length;c++)s[o+c]=Math.max(s[o+c],r*(1-c/i))}this.crackleBuffer=e}return this.crackleBuffer}stopVoice(){const t=this.voice,e=this.context;if(this.voice=void 0,!t||!e)return;const s=e.currentTime;t.volumeParam.cancelScheduledValues(s),t.volumeParam.setTargetAtTime(0,s,Gd/3);const i=s+Gd;for(const n of t.sources){n.onended=()=>{n.disconnect();for(const a of t.nodes)a.disconnect()};try{n.stop(i)}catch{n.disconnect();for(const a of t.nodes)a.disconnect()}}}}class Q{static svg(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor"/></svg>`}static outline(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=Q.outline(Q.BOOKMARK);static MILESTONES_ON=Q.solid(Q.BOOKMARK);static PICTURES_OFF=Q.outline(`${Q.PICTURE}${Q.PICTURE_HILLS}`);static PICTURES_ON=Q.solid(`${Q.PICTURE}${Q.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=Q.outline(`${Q.TRACE_LINE}${Q.TRACE_MARK}`);static TRACES_ON=Q.solid(`${Q.TRACE_LINE}${Q.TRACE_MARK}`);static MAP_OFF=Q.outline(`${Q.PIN}${Q.PIN_HOLE}`);static MAP_ON=Q.solid(`${Q.PIN}${Q.PIN_HOLE}`);static SHARE=Q.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static VIDEO=Q.outline("M3.5 7h11a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1zM15.5 10.5l5-3v9l-5-3z");static FOLDED=Q.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Q.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Q.svg("M7.4 5v14l11-7z");static PAUSE=Q.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Q.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=Q.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=Q.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Q.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}class ti{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,s,i){if(!ti.isObject(t)){i.push({kind:"wrong-type",path:s||"(the file)",expected:"object",found:ti.typeOf(t)});return}for(const[n,a]of Object.entries(t)){const o=s?`${s}.${n}`:n,r=e[n];r?this.field(a,r,o,i):i.push({kind:"unknown-key",path:o})}}field(t,e,s,i){if(ti.isStated(t)){this.range(t.range,`${s}.range`,i),this.field(t.value,e,s,i);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&i.push({kind:"not-in-list",path:s,expected:(e.values??[]).map(n=>`"${n}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,s,i):ti.isObject(t)||i.push({kind:"wrong-type",path:s,expected:"object",found:ti.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((n,a)=>{const o=ti.isStated(n)?n.value:n;this.object(o,e.fields,`${s}.${a}`,i)}):i.push({kind:"wrong-type",path:s,expected:"array",found:ti.typeOf(t)});return;default:typeof t!==e.type?i.push({kind:"wrong-type",path:s,expected:e.type,found:ti.typeOf(t)}):typeof t=="number"&&(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&i.push({kind:"out-of-range",path:s,expected:`${e.minimum??"−∞"}–${e.maximum??"∞"}`,found:String(t)})}}range(t,e,s){if(t===void 0||typeof t=="string")return;const i=n=>n===null||typeof n=="number"&&Number.isFinite(n);!Array.isArray(t)||t.length!==2||!t.every(i)||t[0]===null&&t[1]===null?s.push({kind:"wrong-type",path:e,expected:"[least, greatest], null for an open side, or an EDTF interval",found:JSON.stringify(t)}):t[0]!==null&&t[1]!==null&&t[0]>t[1]&&s.push({kind:"out-of-range",path:e,expected:"least ≤ greatest",found:JSON.stringify(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 ti.isObject(t)&&"value"in t&&Object.keys(t).every(e=>ti.STATED_KEYS.has(e))}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class ls{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const s=Number.isFinite(e)?Math.max(0,e):0,i=Math.max(0,t-s*1e3),n=Math.max(0,t-i);return{fromMs:i,toMs:t,ms:n,seconds:n/1e3}}static instants(t,e,s,i,n){if(!(i>0))return 1;const a=n>0?ls.travelDegOver(t,e,s,s+i*1e3)/n/ls.PIXELS_PER_INSTANT:0,o=ls.flashesOver(t,i)*ls.INSTANTS_PER_FLASH,r=Math.ceil(Math.max(a,o));return r<2?1:Math.min(ls.MAX_INSTANTS,r)}static travelDegOver(t,e,s,i){let n=0;for(const a of t){if(!a.track||a.track.length<2)continue;const o=ls.directionAt(a,e,s),r=ls.directionAt(a,e,i),c=Math.min(1,Math.max(-1,o.x*r.x+o.y*r.y+o.z*r.z));n=Math.max(n,Math.acos(c)*180/Math.PI)}return n}static flashesOver(t,e){let s=0;for(const i of t)for(const n of i.lights??[])n.pattern.kind==="flash"&&(s=Math.max(s,n.pattern.perMinute));return s/60*e}static directionAt(t,e,s){const i=wi(t,s),n=i.eastM,a=i.altitudeM-e,o=i.northM,r=Math.hypot(n,a,o);return r===0?{x:0,y:1,z:0}:{x:n/r,y:a/r,z:o/r}}static bodyInstants(t,e,s,i,n){if(!(i>s)||!(n>0))return 1;let a=0;for(const r of t){const c=ls.bodyAt(r,s),h=ls.bodyAt(r,i);if(!c||!h)continue;const l={x:c.eastM,y:c.upM-e,z:c.northM},d={x:h.eastM,y:h.upM-e,z:h.northM},f=Math.hypot(l.x,l.y,l.z),m=Math.hypot(d.x,d.y,d.z);if(f===0||m===0)continue;const p=Math.min(1,Math.max(-1,(l.x*d.x+l.y*d.y+l.z*d.z)/f/m));let g=Math.acos(p)*180/Math.PI,M=0;for(const v of Object.keys(h.motions))M=Math.max(M,Math.abs(h.motions[v]-(c.motions[v]??h.motions[v])));M>0&&(g+=M*2*(h.halfWidthM/Math.max(m,.001))*180/Math.PI),a=Math.max(a,g)}const o=Math.ceil(a/n/ls.PIXELS_PER_INSTANT);return o<2?1:Math.min(ls.MAX_INSTANTS,o)}static bodyAt(t,e){const s=t.track;if(s.length===0||e<s[0].t||e>s[s.length-1].t)return;let i=0,n=s.length-1;for(;n-i>1;){const d=i+n>>1;s[d].t<=e?i=d:n=d}const a=s[i],o=s[n];if(a.eastM===void 0||a.northM===void 0||o.eastM===void 0||o.northM===void 0)return;const r=o.t>a.t?(e-a.t)/(o.t-a.t):0,c=(d,f)=>d+(f-d)*r,h={};for(const d of Object.keys(o.motions??{})){const f=a.motions?.[d],m=o.motions[d];h[d]=f===void 0?m:c(f,m)}const l=s.find(d=>d.sizeM)?.sizeM?.widthM??1;return{eastM:c(a.eastM,o.eastM),northM:c(a.northM,o.northM),upM:c(a.altitudeM??0,o.altitudeM??0),halfWidthM:l/2,motions:h}}}const W1="#2ec4ff";class ha{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 s,i=1/0;for(const n of this.targets){const a=Math.hypot(n.x-t,n.y-e);a>n.radius||a>i||(s=n,i=a)}return s}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,s){const i=rm(t,s,e);return{x:i.x*this.width,y:i.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const s=t.imagery;if(!s)return;const i=this.toCanvas(t.bounds,s.bounds.north,s.bounds.west),n=this.toCanvas(t.bounds,s.bounds.south,s.bounds.east);e.drawImage(s.source,i.x,i.y,n.x-i.x,n.y-i.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 s of t.decor){const i=this.toCanvas(t.bounds,s.lat,s.lng);if(s.label&&this.targets.push({kind:"decor",label:s.label,lat:s.lat,lng:s.lng,x:i.x,y:i.y,radius:7}),e.beginPath(),e.rect(i.x-3.5,i.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(),s.headingDeg===void 0)continue;const n=(s.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+Math.cos(n)*10,i.y+Math.sin(n)*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,s=t.path.points.map(i=>this.toCanvas(t.bounds,i.lat,i.lng));e.beginPath(),e.moveTo(s[0].x,s[0].y);for(const i of s.slice(1))e.lineTo(i.x,i.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 s of t.traces??[]){const i=s.points.map(a=>this.toCanvas(t.bounds,a.lat,a.lng));if(i.length===0)continue;const n=s.color??W1;if(s.kind==="point")e.beginPath(),e.moveTo(i[0].x,i[0].y-6),e.lineTo(i[0].x+6,i[0].y),e.lineTo(i[0].x,i[0].y+6),e.lineTo(i[0].x-6,i[0].y),e.closePath(),e.fillStyle=n,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const a of i.slice(1))e.lineTo(a.x,a.y);s.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=n,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(s.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let a=i[0];if(s.kind==="line"&&t.position){const o=this.toCanvas(t.bounds,t.position.lat,t.position.lng);a=i.reduce((r,c)=>Math.hypot(c.x-o.x,c.y-o.y)>Math.hypot(r.x-o.x,r.y-o.y)?c:r)}this.paintOutlinedText(s.label,a.x+9,a.y-9)}}}paintCone(t,e){const{headingDeg:s,coneHalfAngleDeg:i}=t;if(s===void 0||i===void 0)return;const{ctx:n}=this,a=this.toCanvas(t.bounds,e.lat,e.lng),o=Math.hypot(this.width,this.height),r=(s-90)*Math.PI/180,c=i*Math.PI/180;n.save(),n.beginPath(),n.moveTo(a.x,a.y),n.arc(a.x,a.y,o,r-c,r+c),n.closePath();const h=n.createRadialGradient(a.x,a.y,0,a.x,a.y,o);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),n.fillStyle=h,n.fill(),n.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const s of[...t.markers].sort((i,n)=>Number(i.current)-Number(n.current))){const i=this.toCanvas(t.bounds,s.lat,s.lng);this.targets.push({kind:"milestone",label:s.note?`${s.label} — ${s.note}`:s.label,lat:s.lat,lng:s.lng,t:s.t,x:i.x,y:i.y,radius:ha.MARKER_RADIUS_PX}),e.beginPath(),e.arc(i.x,i.y,ha.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=s.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=s.current?"#1d2321":"#fff",e.fillText(s.label,i.x,i.y)}}paintObserver(t,e){const{ctx:s}=this,i=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:i.x,y:i.y,radius:8});const n=t.markers.some(a=>{if(!a.current)return!1;const o=ot(a.lat,a.lng,e.lat,e.lng);return Math.hypot(o.x,o.z)<=ha.ON_MARKER_M});s.beginPath(),s.arc(i.x,i.y,n?ha.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),n||(s.fillStyle="#ff5a3c",s.fill()),s.lineWidth=4,s.strokeStyle="rgba(0, 0, 0, 0.5)",s.stroke(),s.lineWidth=n?3:2.5,s.strokeStyle=n?"#ff5a3c":"#fff",s.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,s=16;t.beginPath(),t.moveTo(e,s-9),t.lineTo(e-4.5,s+5),t.lineTo(e,s+2),t.lineTo(e+4.5,s+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,s+6),t.fillText("N",e,s+6)}paintFooter(t,e){const{ctx:s}=this;s.font="9px sans-serif",s.textBaseline="bottom";const i=e?this.wrap(e,this.width-20):[];let n=this.height-4;s.textAlign="right";for(const f of i.slice().reverse())this.paintOutlinedText(f,this.width-6,n),n-=11;const a=(t.south+t.north)/2,r=Math.abs(ot(a,t.east,a,t.west).x)/this.width,c=ha.SCALE_STEPS_M.find(f=>f/r<=this.width/3);if(c===void 0)return;const h=c/r,l=8,d=n-3;s.lineWidth=3,s.strokeStyle="rgba(0, 0, 0, 0.6)",s.beginPath(),s.moveTo(l,d),s.lineTo(l+h,d),s.stroke(),s.lineWidth=1.5,s.strokeStyle="rgba(255, 255, 255, 0.95)",s.stroke(),s.textAlign="left",this.paintOutlinedText(c>=1e3?`${c/1e3} km`:`${c} m`,l,d-3)}paintOutlinedText(t,e,s){const{ctx:i}=this;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.75)",i.strokeText(t,e,s),i.fillStyle="#fff",i.fillText(t,e,s)}wrap(t,e){const s=[];let i="";for(const n of t.split(" ")){const a=i?`${i} ${n}`:n;i&&this.ctx.measureText(a).width>e?(s.push(i),i=n):i=a}return i&&s.push(i),s}}class Yt{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 Yt.including(t.boundsAround(Yt.MIN_SPAN_M,Yt.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,s){const i=Math.min(Yt.MAX_ZOOM,Math.max(Yt.MIN_ZOOM,this.zoom*s)),n=this.centerX+(t-.5)/this.zoom,a=this.centerY+(e-.5)/this.zoom;this.centerX=n-(t-.5)/i,this.centerY=a-(e-.5)/i,this.zoom=i}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const s=this.boundsWithin(t),i=Yt.mercatorY01(e.north),n=Yt.mercatorY01(e.south),a=Yt.mercatorY01(s.north),o=Yt.mercatorY01(s.south);this.zoom=(e.east-e.west)/(s.east-s.west),this.centerX=((s.west+s.east)/2-e.west)/(e.east-e.west),this.centerY=((a+o)/2-i)/(n-i)}keepInView(t,e,s){if(!this.changed)return!1;const i=this.boundsWithin(t),n=Yt.mercatorY01(i.north),a=Yt.mercatorY01(i.south),o=(e.lng-i.west)/(i.east-i.west),r=(Yt.mercatorY01(e.lat)-n)/(a-n);return o>=s&&o<=1-s&&r>=s&&r<=1-s?!1:(this.panBy(.5-o,.5-r),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,s=Yt.mercatorY01(t.north),i=Yt.mercatorY01(t.south),n=t.east-t.west;return{west:t.west+(this.centerX-e)*n,east:t.west+(this.centerX+e)*n,north:Yt.latitudeAt(s+(this.centerY-e)*(i-s)),south:Yt.latitudeAt(s+(this.centerY+e)*(i-s))}}static including(t,e,s=3){const i=(t.north+t.south)/2,n=(t.east+t.west)/2,a=ot(i,t.east,i,n).x;let o=a;for(const r of e){const{x:c,z:h}=ot(r.lat,r.lng,i,n),l=Math.max(Math.abs(c),Math.abs(h));l<=a*s&&(o=Math.max(o,l*1.15))}return o<=a?t:{north:Ks(0,-o,i,n).lat,south:Ks(0,o,i,n).lat,east:Ks(o,0,i,n).lng,west:Ks(-o,0,i,n).lng}}static expand(t,e){const s=t.east-t.west,i=t.north-t.south;return{west:t.west-s*e,east:t.east+s*e,south:t.south-i*e,north:t.north+i*e}}static pointAt(t,e,s){const i=Yt.mercatorY01(t.north),n=Yt.mercatorY01(t.south);return{lat:Yt.latitudeAt(i+s*(n-i)),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}}class Th{constructor(t,e,s,i){this.width=t,this.height=e,this.samples=s,this.values=i}at(t,e,s=0){return this.values[(e*this.width+t)*this.samples+s]}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 s=e.getUint32(4,!0),i=e.getUint16(s,!0),n=new Map;for(let M=0;M<i;M++){const v=s+2+M*12;n.set(e.getUint16(v,!0),{type:e.getUint16(v+2,!0),count:e.getUint32(v+4,!0),value:e.getUint32(v+8,!0)})}const a=(M,v)=>{const y=n.get(M);if(y===void 0){if(v===void 0)throw new Error(`TIFF without tag ${M}`);return v}return y.type===3?y.value&65535:y.value},o=M=>{const v=n.get(M);if(v===void 0)throw new Error(`TIFF without tag ${M}`);const y=v.type===3?2:4,w=[];if(v.count*y<=4){const b=new DataView(new ArrayBuffer(4));b.setUint32(0,v.value,!0);for(let E=0;E<v.count;E++)w.push(y===2?b.getUint16(E*2,!0):b.getUint32(0,!0))}else for(let b=0;b<v.count;b++)w.push(y===2?e.getUint16(v.value+b*2,!0):e.getUint32(v.value+b*4,!0));return w};if(a(259,1)!==1)throw new Error("Compressed TIFF");if(n.has(322))throw new Error("Tiled TIFF");const r=a(256),c=a(257),h=a(277,1),l=o(258)[0],d=a(339,1)===3;if(!(d&&l===32||!d&&l===8))throw new Error(`Unsupported TIFF samples: ${l} bits`);const f=o(273),m=o(279),p=new Uint8Array(r*c*h*(l/8));let g=0;for(let M=0;M<f.length&&g<p.length;M++){const v=Math.min(m[M],p.length-g);p.set(new Uint8Array(t,f[M],v),g),g+=v}if(g<p.length)throw new Error("Truncated TIFF");return new Th(r,c,h,d?new Float32Array(p.buffer):p)}}class In extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class K1{constructor(t,e,s,i,n){this.heights=t,this.plants=e,this.buildings=s,this.size=i,this.metresPerPixel=n}structureAt(t,e){const s=Math.floor(t/this.metresPerPixel+this.size/2),i=Math.floor(this.size/2-e/this.metresPerPixel);if(s<0||i<0||s>=this.size||i>=this.size)return;const n=i*this.size+s;if(!(this.plants[n]||this.buildings[n]))return this.heights[n]}tallestStructureNear(t,e,s){let i;const n=Math.ceil(s/this.metresPerPixel);for(let a=-n;a<=n;a++)for(let o=-n;o<=n;o++){if(Math.hypot(o,a)*this.metresPerPixel>s)continue;const r=this.structureAt(t+o*this.metresPerPixel,e+a*this.metresPerPixel);r!==void 0&&(i===void 0||r>i)&&(i=r)}return i}}class V{static METRES_PER_DEGREE=111320;static MIN_BRIDGE_M=4;static DEFAULT_DECK_M=6;static FOOTBRIDGE_DECK_M=2.5;static DECK_MARGIN_M=2.4;static JOIN_M=1;static JOIN_DEG=25;static RAIL_MATCH_M=6;static ROAD_MATCH_M=12;static DECK_SEEN_M=1.5;static DECK_STEP_M=.5;static DECK_GAP_M=2;static DECK_REACH_M=20;static DECK_MEETS_M=.3;static DECK_BEARING_M=4;static DEFAULT_DECK_HEIGHT_M=4;static MIN_POLE_M=6;static MAX_POLE_M=70;static MAX_SPAN_M=800;static MAX_LINES=16;static BY_VOLTAGE=[{upToKv:25,poleM:11,dropM:1.2,spreadM:.8},{upToKv:70,poleM:20,dropM:3,spreadM:3},{upToKv:100,poleM:22,dropM:3.5,spreadM:3.5},{upToKv:170,poleM:27,dropM:4.5,spreadM:4.5},{upToKv:250,poleM:32,dropM:5.5,spreadM:5.5},{upToKv:1e3,poleM:42,dropM:7,spreadM:7.5}];static toMetres(t,e){const[s,i]=t;return{east:(s-e.lng)*V.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180),north:(i-e.lat)*V.METRES_PER_DEGREE}}static path(t,e){return t.geometry.type!=="LineString"?[]:t.geometry.coordinates.map(s=>V.toMetres(s,e))}static bearing(t,e){return(Math.atan2(e.east-t.east,e.north-t.north)*180/Math.PI+360)%360}static distanceToSegment(t,e,s){const i=s.east-e.east,n=s.north-e.north,a=i*i+n*n,o=a===0?0:Math.max(0,Math.min(1,((t.east-e.east)*i+(t.north-e.north)*n)/a));return Math.hypot(t.east-(e.east+o*i),t.north-(e.north+o*n))}static bridges(t,e,s,i){const n=t.elevatedRoads.map(r=>({path:V.path(r,e),properties:r.properties})),a=(t.elevatedRailways??[]).map(r=>V.path(r,e)),o=[];for(const r of V.joined(t.bridges.map(c=>V.path(c,e)))){const c=r[0],h=r[r.length-1],l=Math.hypot(h.east-c.east,h.north-c.north);if(l<V.MIN_BRIDGE_M)continue;const d={east:(c.east+h.east)/2,north:(c.north+h.north)/2};if(Math.hypot(d.east,d.north)>s+l/2||V.carriesRailway(c,h,a))continue;const[f,m]=V.deckReach(c,h,i);o.push({eastM:V.tenth((f.east+m.east)/2),northM:V.tenth((f.north+m.north)/2),lengthM:V.tenth(Math.hypot(m.east-f.east,m.north-f.north)),widthM:V.roadOf(d,n).width,heightM:V.tenth(V.deckHeight(c,h,i)),headingDeg:V.tenth(V.bearing(c,h)%180),...V.roadOf(d,n).name?{name:V.roadOf(d,n).name}:{}})}return o.sort((r,c)=>Math.hypot(r.eastM,r.northM)-Math.hypot(c.eastM,c.northM)),o}static carriesRailway(t,e,s){const i={east:(t.east+e.east)/2,north:(t.north+e.north)/2},n=V.bearing(t,e)%180;for(const a of s)for(let o=0;o+1<a.length;o++){if(V.distanceToSegment(i,a[o],a[o+1])>V.RAIL_MATCH_M)continue;const r=Math.abs(V.bearing(a[o],a[o+1])%180-n);if(Math.min(r,180-r)<=V.JOIN_DEG)return!0}return!1}static joined(t){const e=t.filter(s=>s.length>=2);for(let s=0;s<e.length;s++)for(let i=s+1;i<e.length;i++){const n=V.join(e[s],e[i]);n!==void 0&&(e[s]=n,e.splice(i,1),i=s)}return e}static join(t,e){for(const s of[t,[...t].reverse()])for(const i of[e,[...e].reverse()]){const n=s[s.length-1],a=i[0];if(Math.hypot(n.east-a.east,n.north-a.north)>V.JOIN_M)continue;const o=Math.abs(V.bearing(s[0],n)-V.bearing(a,i[i.length-1]));if(Math.min(o,360-o)<=V.JOIN_DEG)return[...s,...i.slice(1)]}}static roadOf(t,e){let s;for(const o of e)for(let r=0;r+1<o.path.length;r++){const c=V.distanceToSegment(t,o.path[r],o.path[r+1]);(s===void 0||c<s.distance)&&(s={distance:c,properties:o.properties})}if(s===void 0||s.distance>V.ROAD_MATCH_M)return{width:V.DEFAULT_DECK_M};const i=[s.properties.nom_voie_ban_gauche,s.properties.nom_voie_ban_droite,s.properties.cpx_toponyme_route_nommee].find(o=>typeof o=="string"&&o.length>0),n=Number(s.properties.largeur_de_chaussee),a=Number.isFinite(n)&&n>0?V.tenth(n+V.DECK_MARGIN_M):s.properties.nature==="Sentier"?V.FOOTBRIDGE_DECK_M:V.DEFAULT_DECK_M;return i?{width:a,name:i}:{width:a}}static deckReach(t,e,s){const i=Math.hypot(e.east-t.east,e.north-t.north);if(s===void 0||i===0)return[t,e];const n={east:(t.east+e.east)/2,north:(t.north+e.north)/2},a={east:(e.east-t.east)/i,north:(e.north-t.north)/i},o=d=>(s.structureAt(n.east+a.east*d,n.north+a.north*d)??0)>=V.DECK_SEEN_M,r=d=>s.structureAt(n.east+a.east*d,n.north+a.north*d)??0,c=d=>{let f;for(let p=0;p<=i/2+V.DECK_REACH_M;p+=V.DECK_STEP_M)if(o(d*p))f=p;else if(f!==void 0&&p-f>V.DECK_GAP_M)break;if(f===void 0)return i/2;let m=f;for(;m-f<V.DECK_REACH_M&&r(d*(m+V.DECK_STEP_M))>=V.DECK_MEETS_M;)m+=V.DECK_STEP_M;return Math.max(i/2,m+V.DECK_BEARING_M)},h=c(-1),l=c(1);return[{east:n.east-a.east*h,north:n.north-a.north*h},{east:n.east+a.east*l,north:n.north+a.north*l}]}static deckHeight(t,e,s){if(s===void 0)return V.DEFAULT_DECK_HEIGHT_M;const i=[],n=20;for(let a=4;a<=n-4;a++){const o=s.structureAt(t.east+(e.east-t.east)*a/n,t.north+(e.north-t.north)*a/n);o!==void 0&&o>=1.5&&i.push(o)}return i.length===0?V.DEFAULT_DECK_HEIGHT_M:(i.sort((a,o)=>a-o),i[Math.floor(i.length/2)])}static lines(t,e,s,i){const n=[];for(const a of t.lines){const o=String(a.properties.voltage??""),r=V.kilovolts(o);if(r===void 0)continue;const c=V.BY_VOLTAGE.find(l=>r<=l.upToKv)??V.BY_VOLTAGE[V.BY_VOLTAGE.length-1],h=V.path(a,e);for(let l=0;l+1<h.length;l++){const d=h[l],f=h[l+1],m=Math.hypot(f.east-d.east,f.north-d.north);if(m<5||m>V.MAX_SPAN_M||V.distanceToSegment({east:0,north:0},d,f)>s)continue;const p=V.poleHeight(d,f,i)??c.poleM;n.push({eastM:V.tenth((d.east+f.east)/2),northM:V.tenth((d.north+f.north)/2),lengthM:V.tenth(m),headingDeg:V.tenth(V.bearing(d,f)),heightM:V.tenth(Math.max(4,p-c.dropM)),poleHeightM:V.tenth(p),acrossM:[-c.spreadM,0,c.spreadM],voltage:o})}}return n.sort((a,o)=>Math.hypot(a.eastM,a.northM)-Math.hypot(o.eastM,o.northM)),n.slice(0,V.MAX_LINES)}static kilovolts(t){const e=/([\d.,]+)\s*kV/i.exec(t);if(e===null)return;const s=Number(e[1].replace(",","."));return Number.isFinite(s)&&s>0?s:void 0}static poleHeight(t,e,s){if(s===void 0)return;const i=[t,e].map(n=>s.tallestStructureNear(n.east,n.north,3)).filter(n=>n!==void 0&&n>=V.MIN_POLE_M&&n<=V.MAX_POLE_M);return i.length===0?void 0:i.reduce((n,a)=>n+a,0)/i.length}static tenth(t){return Math.round(t*10)/10}}class Dt{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??Dt.WMS,this.wfs=t.wfsEndpoint??Dt.WFS}static radius(t){return Math.min(t,Dt.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Dt.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const s=Dt.lidarRadius(e),i=Math.ceil(2*s/Dt.METRES_PER_PIXEL),[n,a]=await Promise.all([this.raster(t,s,i,Dt.HEIGHT_LAYER),this.raster(t,s,i,Dt.CLASS_LAYER)]);if(n.samples!==1||a.samples<3)throw new In("unreachable","The survey answered in a layout this does not read");const o=n.values;if(o.every(l=>l===Dt.NO_DATA))throw new In("no-coverage","No LiDAR HD survey here yet");const r=new Uint8Array(i*i),c=new Uint8Array(i*i);for(let l=0;l<i*i;l++){const d=a.values[l*a.samples],f=a.values[l*a.samples+1],m=a.values[l*a.samples+2];r[l]=f>d&&f>m?1:0,c[l]=d>120&&f<90&&m<90?1:0}const h=2*s/i;return{size:i,metresPerPixel:h,heights:o,vegetation:r,building:c,structures:new K1(o,r,c,i,h)}}async laserDate(t){return Dt.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Dt.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(s=>/^\d{4}-\d{2}-\d{2}/.exec(String(s??""))?.[0]).filter(s=>s!==void 0).sort().at(-1)}async dated(t,e,s,i){const a=[i.lng-1e-4,i.lat-1e-4,i.lng+1e-4,i.lat+1e-4].map(o=>o.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${a},'EPSG:4326')`,s,20)).map(o=>o.properties[s])}catch{return[]}}async photo(t,e){const s=Dt.radius(e),i=Math.min(Dt.MAX_PHOTO_PIXELS,Math.ceil(2*s/Dt.METRES_PER_PIXEL)),n=await this.raster(t,s,i,Dt.PHOTO_LAYER);if(n.samples<3)throw new In("unreachable","The photograph came in a layout this does not read");return{size:i,metresPerPixel:2*s/i,samples:n.samples,values:n.values}}async vectors(t,e,s){const i=Dt.radius(e),n=i/Dt.METRES_PER_DEGREE,a=i/(Dt.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),r=`BBOX(geometrie,${[t.lng-a,t.lat-n,t.lng+a,t.lat+n].map(M=>M.toFixed(6)).join(",")},'EPSG:4326')`,[c,h,l,d,f,m]=await Promise.all([this.features("construction_lineaire",`${r} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${r} 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",`${r} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",r,"voltage,geometrie"),s?this.features("batiment",r,Dt.BUILDING_PROPERTIES,5e3):Promise.resolve([]),s?this.features("zone_d_activite_ou_d_interet",r,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),p=s?await this.wholeWorship(m,f,[t.lng-a,t.lat-n,t.lng+a,t.lat+n]):[],g=[...f,...p];return{bridges:c,elevatedRoads:h,elevatedRailways:l,lines:d,buildings:g,zones:m,mapDate:Dt.latest(g.map(M=>M.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,s){const[i,n,a,o]=s,r=Dt.MAX_WHOLE_M/Dt.METRES_PER_DEGREE;let c;for(const l of t){if(l.properties.categorie!=="Religieux")continue;const[d,f,m,p]=Dt.extent(l);if(d>=i&&f>=n&&m<=a&&p<=o)continue;const g=[Math.max(d,i-r),Math.max(f,n-r),Math.min(m,a+r),Math.min(p,o+r)];c=c?[Math.min(c[0],g[0]),Math.min(c[1],g[1]),Math.max(c[2],g[2]),Math.max(c[3],g[3])]:g}if(!c)return[];const h=new Set(e.map(l=>l.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${c.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,Dt.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,s=1/0,i=-1/0,n=-1/0;const a=o=>{Array.isArray(o)&&typeof o[0]=="number"?(e=Math.min(e,o[0]),i=Math.max(i,o[0]),s=Math.min(s,o[1]),n=Math.max(n,o[1])):Array.isArray(o)&&o.forEach(a)};return a(t.geometry.coordinates),[e,s,i,n]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(n=>n.toFixed(6)).join(",")},'EPSG:4326')`,s=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),i=[];for(const n of s){const{type:a,coordinates:o}=n.geometry,r=a==="LineString"?[o]:a==="MultiLineString"?o:[];for(const c of r)i.push(c.map(h=>({lat:h[1],lng:h[0]})))}return i}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.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(s=>s.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(s=>s.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,s,i){const n=e/Dt.METRES_PER_DEGREE,a=e/(Dt.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),o=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-n,t.lng-a,t.lat+n,t.lng+a].map(c=>c.toFixed(6)).join(","),WIDTH:String(s),HEIGHT:String(s),FORMAT:"image/geotiff"});let r;try{r=await this.fetchImpl(`${this.wms}?${o}`)}catch(c){throw new In("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new In("unreachable",`The survey answered ${r.status}`);try{return Th.parse(await r.arrayBuffer())}catch(c){throw new In("unreachable",c instanceof Error?c.message:String(c))}}async features(t,e,s,i=200){const n=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(i),CQL_FILTER:e,PROPERTYNAME:s});let a;try{a=await this.fetchImpl(`${this.wfs}?${n}`)}catch(r){throw new In("unreachable",r instanceof Error?r.message:String(r))}if(!a.ok)throw new In("unreachable",`The map answered ${a.status}`);return(await a.json()).features??[]}}class Cn{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 s=e[0],i=e.map(o=>ot(o.lat,o.lng,s.lat,s.lng)),n=t.map(o=>ot(o.lat,o.lng,s.lat,s.lng));let a=0;for(let o=0;o<n.length-1;o++){const r=n[o],c=n[o+1],h=Math.hypot(c.x-r.x,c.z-r.z);if(h<1e-6)continue;const l=Math.max(1,Math.ceil(h/Cn.SAMPLE_M)),d=Math.atan2(c.x-r.x,-(c.z-r.z));for(let f=0;f<=l;f++){const m=f/l,p=Cn.nearest(i,r.x+(c.x-r.x)*m,r.z+(c.z-r.z)*m);p.distanceM>Cn.NEAR_M||Cn.angleBetween(d,p.heading)<=Cn.ALIGNED_DEG&&(a+=h/l)}}return a>=Cn.LONG_ENOUGH_M}static nearest(t,e,s){let i={distanceM:1/0,heading:0};for(let n=0;n<t.length-1;n++){const a=t[n],o=t[n+1],r=o.x-a.x,c=o.z-a.z,h=r*r+c*c,l=h<1e-9?0:Math.max(0,Math.min(1,((e-a.x)*r+(s-a.z)*c)/h)),d=Math.hypot(e-(a.x+r*l),s-(a.z+c*l));d<i.distanceM&&(i={distanceM:d,heading:Math.atan2(r,-c)})}return i}static angleBetween(t,e){const s=Math.abs((t-e)*180/Math.PI%180);return Math.min(s,180-s)}}class vt{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??vt.WMS,this.timeoutMs=t.timeoutMs??vt.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??vt.MAX_WINDOW_M,this.geoplatform=new Dt({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,s){const i={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Dt.covers(i.lat,i.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(ot(i.lat,t.east,i.lat,t.west).x),a=Math.abs(ot(t.north,i.lng,t.south,i.lng).z);e=this.finer(e,n,a);const o={x:n/Math.max(1,e.width-1),y:a/Math.max(1,e.height-1)},r={x:Math.min(o.x,this.maxWindowM),y:Math.min(o.y,this.maxWindowM)},c={south:t.south-r.y/vt.METRES_PER_DEGREE,north:t.north+r.y/vt.METRES_PER_DEGREE,west:t.west-r.x/(vt.METRES_PER_DEGREE*Math.cos(i.lat*Math.PI/180)),east:t.east+r.x/(vt.METRES_PER_DEGREE*Math.cos(i.lat*Math.PI/180))},h=p=>Math.min(vt.MAX_PIXELS,Math.max(vt.MIN_PIXELS,Math.ceil(p/vt.METRES_PER_PIXEL))),l={width:h(n+2*r.x),height:h(a+2*r.y)},d={x:(n+2*r.x)/l.width,y:(a+2*r.y)/l.height};let f=new Error("No layer of the IGN's relief answered");const m=Math.max(d.x,d.y)>vt.COARSE_METRES_PER_PIXEL;for(const p of m?[...vt.LAYERS].reverse():vt.LAYERS)try{const g=await this.heights(c,l,p);p===vt.LAYERS[0]&&await this.layBridgeDecks(g,c,l,s?.route);const M=this.sample(g,e,t,c,d,o);if(M)return{heights:M,width:e.width,height:e.height,bounds:t};f=new Error(`${p} does not cover this place`)}catch(g){f=g}throw f}finer(t,e,s){if(t.width<vt.MESH_FROM_VERTICES||t.height<vt.MESH_FROM_VERTICES)return t;const i=(n,a)=>{const o=Math.ceil(n/vt.FINE_SPACING_M),r=Math.max(a-1,Math.min(vt.MAX_SEGMENTS,o));return r%2===0?r:r+1};return{width:i(e,t.width)+1,height:i(s,t.height)+1}}async raster(t,e,s){const i=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:s,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(a=>a.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),n=await this.fetchImpl(`${this.wms}?${i}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok)throw new Error(`The IGN's relief answered ${n.status}`);return Th.parse(await n.arrayBuffer())}async heights(t,e,s){const i=await this.raster(t,e,s);if(i.samples!==1||!(i.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return i}async layBridgeDecks(t,e,s,i){if(!(!i||i.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(n=>n>vt.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(o=>Cn.follows(i,o));if(n.length===0)return;const a=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,s,n),this.layRouteDecks(t,a,e,n)}catch{}}async layClassifiedDecks(t,e,s,i){try{const n=await this.raster(e,s,vt.CLASS_LAYER);if(n.samples<3||n.width!==t.width||n.height!==t.height)return;const a=(g,[M,v,y])=>n.values[g*n.samples]===M&&n.values[g*n.samples+1]===v&&n.values[g*n.samples+2]===y,o=t.width,r=t.height,c=new Uint8Array(o*r);let h=!1;for(let g=0;g<c.length;g++)a(g,vt.DECK)&&(c[g]=1,h=!0);if(!h)return;const l=vt.DECK_END_PIXELS,d=[];for(let g=0;g<c.length;g++){if(c[g]!==1)continue;const M=g%o,v=(g-M)/o;for(let y=-l;y<=l;y++)for(let w=-l;w<=l;w++){const b=M+w,E=v+y;if(b<0||E<0||b>=o||E>=r)continue;const A=E*o+b;c[A]===0&&a(A,vt.NO_CLASS)&&d.push(A)}}for(const g of d)c[g]=1;const f=this.paint(i,e,o,r),m=this.touching(c,f,o,r);if(m.every(g=>g===0))return;const p=await this.heights(e,s,vt.SURFACE_LAYER);if(p.width!==o||p.height!==r)return;for(let g=0;g<m.length;g++){if(m[g]===0)continue;const M=p.values[g];Number.isFinite(M)&&M>vt.NO_DATA_BELOW&&M>t.values[g]&&(t.values[g]=M)}}catch{}}layRouteDecks(t,e,s,i){const{width:n,height:a}=t,o=(s.north+s.south)/2,r=(s.east-s.west)*vt.METRES_PER_DEGREE*Math.cos(o*Math.PI/180),c=(s.north-s.south)*vt.METRES_PER_DEGREE,h=r/n,l=c/a,d=M=>({x:(M.lng-s.west)/(s.east-s.west)*r,y:(s.north-M.lat)/(s.north-s.south)*c}),f=(M,v)=>{const y=Math.floor(M/h),w=Math.floor(v/l);if(y<0||w<0||y>=n||w>=a)return;const b=e[w*n+y];return Number.isFinite(b)&&b>vt.NO_DATA_BELOW?b:void 0},m=vt.DECK_HALF_WIDTH_M,p=vt.DECK_APPROACH_M,g=(M,v)=>{const y=Math.hypot(M.x-v.x,M.y-v.y)||1,w={x:(M.x-v.x)/y,y:(M.y-v.y)/y},b=[0,p/2,p].map(E=>f(M.x+w.x*E,M.y+w.y*E)).filter(E=>E!==void 0);return b.length>0?Math.max(...b):void 0};for(const M of vt.chains(i.map(v=>v.map(d)))){const v=[0];for(let I=1;I<M.length;I++)v.push(v[I-1]+Math.hypot(M[I].x-M[I-1].x,M[I].y-M[I-1].y));const y=v[v.length-1];if(y<1||y>vt.DECK_STRAIGHT_MAX_M)continue;const w=g(M[0],M[1]),b=g(M[M.length-1],M[M.length-2]);if(w===void 0||b===void 0)continue;const E=m+p,A=Math.max(0,Math.floor((Math.min(...M.map(I=>I.x))-E)/h)),S=Math.min(n-1,Math.ceil((Math.max(...M.map(I=>I.x))+E)/h)),x=Math.max(0,Math.floor((Math.min(...M.map(I=>I.y))-E)/l)),T=Math.min(a-1,Math.ceil((Math.max(...M.map(I=>I.y))+E)/l));for(let I=x;I<=T;I++)for(let R=A;R<=S;R++){const O=vt.nearestAlong(M,v,{x:(R+.5)*h,y:(I+.5)*l});if(O.distance>m||O.s<-p||O.s>y+p)continue;const P=w+(b-w)*Math.min(1,Math.max(0,O.s/y)),k=I*n+R;e[k]>=P||(t.values[k]=P)}}}static chains(t){const e=t.filter(n=>n.length>=2).map(n=>[...n]),s=[],i=(n,a)=>Math.hypot(n.x-a.x,n.y-a.y)<=1;for(;e.length>0;){let n=e.shift(),a=!0;for(;a;){a=!1;for(let o=0;o<e.length;o++){const r=e[o],c=n[0],h=n[n.length-1];if(i(h,r[0]))n=[...n,...r.slice(1)];else if(i(h,r[r.length-1]))n=[...n,...[...r].reverse().slice(1)];else if(i(c,r[r.length-1]))n=[...r.slice(0,-1),...n];else if(i(c,r[0]))n=[...[...r].reverse().slice(0,-1),...n];else continue;e.splice(o,1),a=!0;break}}s.push(n)}return s}static nearestAlong(t,e,s){let i={s:0,distance:1/0};for(let n=0;n<t.length-1;n++){const a=t[n],o=t[n+1],r=o.x-a.x,c=o.y-a.y,h=r*r+c*c;if(h<1e-9)continue;let l=((s.x-a.x)*r+(s.y-a.y)*c)/h;n>0&&(l=Math.max(0,l)),n<t.length-2&&(l=Math.min(1,l));const d=Math.hypot(s.x-(a.x+r*l),s.y-(a.y+c*l));d<i.distance&&(i={s:e[n]+l*Math.sqrt(h),distance:d})}return i}paint(t,e,s,i){const n=new Uint8Array(s*i),a=r=>(r-e.west)/(e.east-e.west)*s,o=r=>(e.north-r)/(e.north-e.south)*i;for(const r of t)for(let c=0;c<r.length-1;c++){const h=a(r[c].lng),l=o(r[c].lat),d=a(r[c+1].lng),f=o(r[c+1].lat),m=Math.max(1,Math.ceil(Math.hypot(d-h,f-l)*2));for(let p=0;p<=m;p++){const g=Math.floor(h+(d-h)*p/m),M=Math.floor(l+(f-l)*p/m);for(let v=-1;v<=1;v++)for(let y=-1;y<=1;y++){const w=g+y,b=M+v;w>=0&&b>=0&&w<s&&b<i&&(n[b*s+w]=1)}}}return n}touching(t,e,s,i){const n=new Uint8Array(t.length),a=new Uint8Array(t.length);for(let o=0;o<t.length;o++){if(t[o]===0||a[o]===1)continue;const r=[],c=[o];a[o]=1;let h=!1;for(;c.length>0;){const l=c.pop();r.push(l),e[l]===1&&(h=!0);const d=l%s,f=(l-d)/s;for(let m=-1;m<=1;m++)for(let p=-1;p<=1;p++){const g=d+p,M=f+m;if(g<0||M<0||g>=s||M>=i)continue;const v=M*s+g;t[v]===1&&a[v]===0&&(a[v]=1,c.push(v))}}if(h)for(const l of r)n[l]=1}return n}sample(t,e,s,i,n,a){const{width:o,height:r}=e,c=new Float32Array(o*r),h=new Uint8Array(o*r),l=Math.min(a.x,this.maxWindowM)/n.x,d=Math.min(a.y,this.maxWindowM)/n.y;let f=0;for(let m=0;m<r;m++){const p=s.north+(s.south-s.north)*(r===1?.5:m/(r-1)),g=(i.north-p)/(i.north-i.south)*t.height-.5;for(let M=0;M<o;M++){const y=(s.west+(s.east-s.west)*(o===1?.5:M/(o-1))-i.west)/(i.east-i.west)*t.width-.5,w=l>1||d>1?this.tent(t,y,g,Math.max(1,l),Math.max(1,d)):this.bilinear(t,y,g),b=m*o+M;w===void 0?f++:(c[b]=w,h[b]=1)}}if(!(f===o*r||f/(o*r)>vt.MAX_HOLE_SHARE))return this.fill(c,h,o,r),c}tent(t,e,s,i,n){let a=0,o=0,r=0;const c=Math.max(0,Math.ceil(s-n)),h=Math.min(t.height-1,Math.floor(s+n)),l=Math.max(0,Math.ceil(e-i)),d=Math.min(t.width-1,Math.floor(e+i));for(let f=c;f<=h;f++){const m=1-Math.abs(f-s)/n;if(!(m<=0))for(let p=l;p<=d;p++){const g=m*(1-Math.abs(p-e)/i);if(g<=0)continue;r+=g;const M=t.at(p,f);!Number.isFinite(M)||M<vt.NO_DATA_BELOW||(a+=g*M,o+=g)}}return r>0&&o>=r*.5?a/o:void 0}bilinear(t,e,s){const i=Math.max(0,Math.min(t.width-1,Math.floor(e))),n=Math.max(0,Math.min(t.height-1,Math.floor(s))),a=Math.min(t.width-1,i+1),o=Math.min(t.height-1,n+1),r=Math.max(0,Math.min(1,e-i)),c=Math.max(0,Math.min(1,s-n)),h=t.at(i,n),l=t.at(a,n),d=t.at(i,o),f=t.at(a,o);for(const g of[h,l,d,f])if(!Number.isFinite(g)||g<vt.NO_DATA_BELOW)return;const m=h+(l-h)*r,p=d+(f-d)*r;return m+(p-m)*c}fill(t,e,s,i){let n=e.reduce((a,o)=>a+(o?0:1),0);for(;n>0;){const a=[];for(let o=0;o<i;o++)for(let r=0;r<s;r++){const c=o*s+r;if(e[c])continue;let h=0,l=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const m=o+d,p=r+f;m<0||p<0||m>=i||p>=s||!e[m*s+p]||(h+=t[m*s+p],l++)}l>0&&a.push([c,h/l])}if(a.length===0)return;for(const[o,r]of a)t[o]=r,e[o]=1;n-=a.length}}}class Y1{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,s){let i=new Error("No source of relief to ask");for(const n of this.providers)try{return await n.getElevationGrid(t,e,s)}catch(a){i=a}throw i}}class Um{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 cm(t,e,s=>this.tileUrlTemplate.replace("{z}",String(s.z)).replace("{y}",String(s.y)).replace("{x}",String(s.x)),this.fetchImpl)}}class ks{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(t,e=ks.ENDPOINTS){const s=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!s)return[...e];const[i,n,a,o]=s.slice(1).map(Number),r=(i+a)/2,c=(n+o)/2,h=ks.FRANCE;return r>=h.south&&r<=h.north&&c>=h.west&&c<=h.east?[ks.FRANCE_ENDPOINT,...e.filter(d=>d!==ks.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=ks.queue.then(t,t);return ks.queue=e.catch(()=>{}),e}async ask(t){let e;for(const s of this.endpoints??ks.endpointsFor(t))for(let i=0;i<2;i++){try{const n=await this.fetchImpl(`${s}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(ks.HANG_MS)});if(n.ok)return await n.json();if(e=new Error(`${new URL(s).host} refused (${n.status})`),n.status!==429&&n.status!==504)break}catch(n){e=new Error(`${new URL(s).host} unreachable (${String(n)})`);break}await new Promise(n=>setTimeout(n,ks.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class _n{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 ks(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:30];way["highway"~"^(${_n.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(s))}waysFrom(t){const e=[];for(const s of t.elements??[]){const i=s.geometry,n=s.tags;!n||!i||i.length<2||e.push({id:`osm-${s.id??e.length}`,name:n.name,surface:_n.surfaceOf(n),widthM:_n.widthOf(n),..._n.paintOf(n),points:i.map(a=>({lat:a.lat,lng:a.lon}))})}return e}static paintOf(t){const e=t.highway??"",s=t.junction==="roundabout"||t.junction==="circular",i=t.oneway,n=i==="yes"||i==="1"||i==="true"||i===void 0&&(e==="motorway"||s),a=i==="-1"||i==="reverse",o=Number.parseInt(t.lanes??"",10),r=Number.parseInt(t.maxspeed??"",10),c=s?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(n||a)?"dual":e?"road":void 0;return{...c?{kind:c}:{},...Number.isFinite(o)&&o>0?{lanes:o}:{},...i!==void 0||e==="motorway"||s?{direction:a?"backward":n?"forward":"both"}:{},...Number.isFinite(r)&&r>0?{speedKmh:r}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const s=Number.parseInt(t.lanes??"",10);return Number.isFinite(s)&&s>0?s*3.5:_n.WIDTH_M[t.highway]??_n.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 Hh="https://ufoathome.org/roads/index.json";class fo{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??fo.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 s=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,s}async held(t){let e;try{e=await this.load()}catch{return}const s=e.find(({entry:i})=>i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west);if(s)try{const i=await this.fetchImpl(new URL(s.entry.file,s.indexUrl).href);if(!i.ok)return;const n=await i.json();return Array.isArray(n?.ways)?(this.attributionRead=n.attribution,this.contemporaryRead=n.contemporary,n.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1568
|
-
`);let e=fo.shared.get(t);return e||(e=this.fetchFirstAvailable(),fo.shared.set(t,e),e.then(s=>{s.length===0&&fo.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 s=await e.json();if(Array.isArray(s?.entries))return s.entries.map(i=>({entry:i,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.204.
|
|
1569
|
-
`);let e=mo.shared.get(t);return e||(e=this.fetchFirstAvailable(),mo.shared.set(t,e),e.then(s=>{s.length===0&&mo.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 s=await e.json();if(Array.isArray(s?.entries))return s.entries.map(i=>({entry:i,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.204.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==Uh?[e,Uh]:[Uh]).map(s=>s+t)}}class Ss{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=Ss.key(t);let s=Ss.asked.get(e);return s===void 0&&(s=this.recalled(e,t),Ss.asked.set(e,s),s.catch(()=>Ss.asked.delete(e))),structuredClone(await s)}static forget(){Ss.asked.clear()}static key(t){return`v${Ss.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const s=await Ss.openCache(),i=Ss.request(t);if(s)try{const a=await s.match(i);if(a){const{savedAt:o,surfaces:r}=await a.json();if(Date.now()-o<Ss.MAX_AGE_MS&&Array.isArray(r))return r;await s.delete(i)}}catch{}const n=await this.water.getWater(e);return s&&Ss.store(s,i,n),n}static async store(t,e,s){try{const i={savedAt:Date.now(),surfaces:s};await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const a of n.slice(0,Math.max(0,n.length-Ss.MAX_STORED)))await t.delete(a)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ss.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Wn{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 Dt(t)}static covers(t){return Dt.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((s,i)=>Wn.linesOf(s,i))}static linesOf(t,e){const{type:s,coordinates:i}=t.geometry,n=s==="LineString"?[i]:s==="MultiLineString"?i:[],a=Wn.BY_NATURE[String(t.properties.nature??"")];if(!a)return[];const o=String(t.properties.cleabs??`ign-rail-${e}`),r=Number(t.properties.nombre_de_voies),c=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,l=Wn.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Wn.electrificationOf(a.kind,l,t.properties.electrifie);return n.flatMap((f,m)=>{const p=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>Wn.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return p.length<2?[]:[{id:n.length>1?`${o}-${m}`:o,...typeof h=="string"&&h.length>0?{name:h}:{},kind:a.kind,...a.service?{service:!0}:{},...a.highSpeed?{highSpeed:!0}:{},gaugeMm:l,tracks:Number.isInteger(r)&&r>0?r:1,...d?{electrification:d}:{},level:Number.isFinite(c)?c:0,points:p}]})}static electrificationOf(t,e,s){if(s===!1)return"none";if(s===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class is{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 ks(t)}async named(t,e){if(t.length===0)return[...t];const s=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:120];way["railway"~"^(${is.KINDS})$"](${s})->.w;.w out tags geom;rel(bw.w)["route"~"^(${is.ROUTES})$"];out body;`;return is.apply(t,await this.client.query(i),e)}static apply(t,e,s){const i={lat:(s.north+s.south)/2,lng:(s.east+s.west)/2},n=is.ways(e,i);return n.length===0?[...t]:t.map(a=>{const o=a.points.map(M=>ot(M.lat,M.lng,i.lat,i.lng)),r=new Map,c=new Map,h=new Map;let l=0;const d=n.filter(M=>M.service===!!a.service);for(const M of is.samples(o)){l++;const v=is.waysAt(d,M);if(v.length===0)continue;const[y]=v;y.name&&r.set(y.name,(r.get(y.name)??0)+1),y.voltageV&&c.set(y.voltageV,(c.get(y.voltageV)??0)+1);for(const w of new Set(v.flatMap(b=>b.services)))h.set(w,(h.get(w)??0)+1)}const f=M=>[...M.entries()].sort((v,y)=>y[1]-v[1])[0]?.[0],m=a.name??f(r),p=a.voltageV??(a.electrification==="none"?void 0:f(c)),g=[...h.entries()].filter(([,M])=>M*4>=l).sort((M,v)=>v[1]-M[1]||M[0].localeCompare(v[0])).map(([M])=>M);return{...a,...m?{name:m}:{},...p?{voltageV:p}:{},...g.length>0?{services:g}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const s of t.elements??[]){if(s.type!=="relation"||!s.tags)continue;const i=is.serviceOf(s.tags);if(i)for(const n of s.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const a=e.get(n.ref)??new Set;a.add(i),e.set(n.ref,a)}}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 s=is.servicesByWay(t),i=[];for(const n of t.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const a=n.tags??{},o=is.voltageOf(a);i.push({service:!!a.service||a.usage==="industrial",...a.name?{name:a.name}:{},...o?{voltageV:o}:{},services:[...s.get(n.id??-1)??[]],path:n.geometry.map(r=>ot(r.lat,r.lon,e.lat,e.lng))})}return i}static samples(t){const e=[];for(let s=0;s<t.length-1;s++){const i=Math.hypot(t[s+1].x-t[s].x,t[s+1].z-t[s].z);if(i<1e-6)continue;const n=(t[s+1].x-t[s].x)/i,a=(t[s+1].z-t[s].z)/i;for(let o=is.SAMPLE_M/2;o<i;o+=is.SAMPLE_M)e.push({x:t[s].x+n*o,z:t[s].z+a*o,dx:n,dz:a})}return e}static waysAt(t,e){const s=Math.cos(is.ALIGNED_DEG*Math.PI/180),i=[];for(const n of t){let a;for(let o=0;o<n.path.length-1;o++){const r=n.path[o],c=n.path[o+1],h=c.x-r.x,l=c.z-r.z,d=Math.hypot(h,l);if(d<1e-6||Math.abs((h*e.dx+l*e.dz)/d)<s)continue;const f=Math.max(0,Math.min(1,((e.x-r.x)*h+(e.z-r.z)*l)/(d*d))),m=Math.hypot(e.x-(r.x+h*f),e.z-(r.z+l*f));m<=is.NEAR_M&&(a===void 0||m<a)&&(a=m)}a!==void 0&&i.push({way:n,distance:a})}return i.sort((n,a)=>n.distance-a.distance).map(({way:n})=>n)}}class po{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 ks(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:25];way["railway"~"^(${po.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${is.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(s))}linesFrom(t){const e=[],s=is.servicesByWay(t);for(const i of t.elements??[]){const n=i.geometry,a=i.tags;if(i.type==="relation"||!a||!n||n.length<2)continue;const o=[...s.get(i.id??-1)??[]].sort(),r=is.voltageOf(a),c=po.kindOf(a),h=Number.parseInt((a.gauge??"").split(";")[0],10),l=Number.parseInt(a.tracks??"",10),d=po.electrificationOf(a.electrified),f=a.highspeed==="yes"||Number.parseInt(a.maxspeed??"",10)>=250;e.push({id:`osm-rail-${i.id??e.length}`,...a.name?{name:a.name}:{},...o.length>0?{services:o}:{},...r?{voltageV:r}:{},kind:c,...a.service||a.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:a.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(l)&&l>0?l:1,...d?{electrification:d}:{},level:po.levelOf(a),points:n.map(m=>({lat:m.lat,lng:m.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 q1{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(!Wn.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(s){if(e)return e;throw s}}}class xe{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=xe.key(t);let s=xe.asked.get(e)??xe.containing(t);if(s===void 0){const i=this.recalled(e,t);s={bounds:t,answer:i},xe.asked.set(e,s),i.catch(()=>xe.asked.delete(e))}return structuredClone(await s.answer)}static forget(){xe.asked.clear(),xe.failedAt=-1/0}static key(t){return`v${xe.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of xe.asked.values()){const s=e.bounds;if(s.north>=t.north&&s.south<=t.south&&s.east>=t.east&&s.west<=t.west)return e}}async recalled(t,e){const s=await xe.openCache(),i=xe.request(t);let n;if(s)try{const o=await s.match(i);if(o){const{savedAt:r,lines:c}=await o.json();if(Array.isArray(c)){if(this.now()-r<xe.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-xe.failedAt<xe.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let a;try{a=await this.railways.getRailways(e)}catch(o){if(xe.failedAt=this.now(),n)return n;throw o}return s&&xe.store(s,i,{savedAt:this.now(),lines:a}),a}static async store(t,e,s){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const i=await t.keys();for(const n of i.slice(0,Math.max(0,i.length-xe.MAX_STORED)))await t.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(xe.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Gh="https://ufoathome.org/railways/index.json";class go{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??go.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 s=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,s}async held(t){const s=(await this.load().catch(()=>[])).find(({entry:i})=>i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west);if(s)try{const i=await this.fetchImpl(new URL(s.entry.file,s.indexUrl).href);if(!i.ok)return;const n=await i.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1570
|
-
`);let e=go.shared.get(t);return e||(e=this.fetchFirstAvailable(),go.shared.set(t,e),e.then(s=>{s.length===0&&go.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 s=await e.json();if(Array.isArray(s?.entries))return s.entries.map(i=>({entry:i,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.204.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Gh?[e,Gh]:[Gh]).map(s=>s+t)}}function Gm(){return{elevation:Bm(),imagery:Vm(),roads:j1(),water:Z1(),railways:J1()}}function Bm(){return new Y1(new vt,new hm)}function Vm(){return new Um}function j1(){return new fo({fallback:new $1(new Vn,new _n)})}function Z1(){return new mo({fallback:new Ss(new X1(new Fr,new la))})}function J1(){return new go({fallback:new xe(new q1(new Wn,new po))})}const Q1=new Set,Lo="show-observer-map",No="hide-milestones",ma="minified";class Tt extends HTMLElement{static get observedAttributes(){return["src",Lo,No,ma]}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 Yt;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=Bf.create();issues=[];issueCheck=0;sightingAudio=new Wd;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new Wd(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>Tt.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"),s=()=>t.scrollWidth>t.clientWidth+1,i=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&s()){t.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!s())break;t.classList.add(n)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!i,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Tt.setIcon(this.moreButton,t?Q.UNFOLDED:Q.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=Q.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",s=>{s.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:s}=await H(async()=>{const{VideoButton:n}=await import("./VideoButton-BseBKx2r.js");return{VideoButton:n}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]),import.meta.url);if(this.videoElement!==e)return;const i=new s(t,e);this.videoButton=i,this.messages&&(i.messages=this.messages),this.stageElement.append(i.panel),i.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,s=t.caption&&this.sighting.milestones.length>0?Zr(this.sighting.milestones,e):void 0,i=s?this.said.read(s.label)??"":void 0,n=this.canvas.getBoundingClientRect(),a=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...s?{caption:{label:i,note:this.said.read(s.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...a&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(a.left-n.left)/n.width,top:(a.top-n.top)/n.height,width:a.width/n.width,height:a.height/n.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),s=e&&this.shapeAt(e.x,e.y),i=this.namesHeldValue?void 0:this.said.read(s?.shape.title);if(!i){this.tooltip.hidden=!0;return}this.tooltip.textContent=i,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-n.left+12}px`,this.tooltip.style.top=`${t.clientY-n.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 s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.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)<Tt.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const s=this.observerMapCanvas.getBoundingClientRect();return s.width>0&&s.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/s.width,(t.clientY-e.lastY)/s.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 s=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-s*.002))};zoomObserverMap(t,e,s){this.observerMapView.zoomAt(t,e,s),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Yt.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Yt.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Tt.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,s=this.observerMapCanvas.getBoundingClientRect();if(!e||s.width===0||s.height===0)return;const i=Yt.pointAt(e,(t.clientX-s.left)/s.width,(t.clientY-s.top)/s.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:i,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${_1}</style>${C1}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Vo(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",o=>{o.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 ha(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",o=>{o.key!=="Enter"&&o.key!==" "||(o.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"),s=e.querySelector(".mini-track"),i=o=>{const r=s.getBoundingClientRect(),c=this.player.seekableDuration;if(r.width<=0||c<=0)return;const h=Math.min(Math.max((o.clientX-r.left)/r.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;e.addEventListener("pointerdown",o=>{o.button===0&&(o.stopPropagation(),e.setPointerCapture(o.pointerId),e.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,i(o))}),e.addEventListener("pointermove",o=>{e.hasPointerCapture(o.pointerId)&&i(o)});const a=o=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(o.pointerId)&&e.releasePointerCapture(o.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a),e.addEventListener("click",o=>o.stopPropagation()),this.miniMuteButton.addEventListener("click",o=>{o.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",o=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(o),this.seekPreview.hidden=!0,this.beginTouchScrub(o)}),this.seekInput.addEventListener("pointerup",o=>{this.seekSnapArmed=!1,this.endTouchScrub(o)}),this.seekInput.addEventListener("pointercancel",o=>this.endTouchScrub(o)),this.seekInput.addEventListener("pointermove",o=>{this.nameMarkUnder(o),this.hoverSeek(o),this.touchScrub(o)}),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 o of["touchend","click"])this.stageElement.addEventListener(o,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",o=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}o.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",o=>{!this.enableClickToPlay||this.minified||(o.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,s){if(t==="src"&&s&&s!==e&&this.isConnected&&this.loadFromSrc(s),t===Lo&&this.applyObserverMapDefault(),t===No&&this.setMilestonesShown(!this.hasAttribute(No)),t===ma){const i=this.minified;this.stageElement.classList.toggle("minified",i),i&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(ma)}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(Km)))};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 Uf.recording(t)}get sightingData(){return Nm(this.currentSighting)}set sightingData(t){const e=ku.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=Ku(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 s=++this.issueCheck;let i=[];try{const{default:n}=await H(async()=>{const{default:a}=await import("./sightingSchema-DoPVOlCB.js");return{default:a}},[],import.meta.url);i=new ti(n).issues(t)}catch{}s===this.issueCheck&&(this.issues=[...i,...e.loadIssues],vd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(e2,{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(s=>{const i=document.createElement("li");return i.textContent=vd.text(s,this.messages.issueTemplates),i}))}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 s=document.createElement("button");s.type="button",s.className="cited-mark",s.innerHTML=ig.INTERVIEW,s.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const i=e.quote??"";return s.title=i,s.setAttribute("aria-label",i),s.addEventListener("click",()=>this.player.seek(e.at*1e3)),s}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Tt.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(t2,{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(i=>this.highlightedSourceIds.has(i))||(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 s of e)t.appendChild(s);else{const s=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const i of e)this.controlsRight.insertBefore(i,s)}}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(s=>s.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,s=4;e.style.bottom=`${Math.max(s,window.innerHeight-t.top+s)}px`,e.style.top="auto";const i=e.getBoundingClientRect().width;e.style.left=`${Math.max(s,Math.min(t.left,window.innerWidth-i-s))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const s=this.viewOfReference(e),i=this.said.read(e.title)??e.id,n=document.createElement("div");n.className="reference-row";const a=document.createElement("label"),o=document.createElement("input");o.type="checkbox",o.checked=s.shown;const r=document.createElement("span");r.textContent=i,r.title=i,a.append(o,r);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(s.opacity),c.title=this.messages?.referenceOpacity??"",c.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${i}`),c.disabled=!s.shown,o.addEventListener("change",()=>{s.shown=o.checked,c.disabled=!s.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{s.opacity=Number(c.value),this.dispatchReferenceView()}),n.append(a,c),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,s=e?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(s)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Tt.setIcon(this.referencesButton,s?Q.PICTURES_ON:Q.PICTURES_OFF);const i=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=i,this.referencesButton.setAttribute("aria-label",i),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)),Tt.setIcon(this.tracesButton,this.tracesShownState?Q.TRACES_ON:Q.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?vr(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(s=>{const i=document.createElement("button");i.type="button",i.className="milestone-mark",i.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`;const n=this.said.read(s.label)??"",a=this.said.read(s.note),o=a?`${n} — ${a}`:n;return i.title=o,i.setAttribute("aria-label",o),i.dataset.t=String(s.t),i.addEventListener("click",()=>this.player.seek(s.t)),i})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(s=>s.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(s=>{const i=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(s.t);const a=this.said.read(s.label)??"",o=this.said.read(s.note);return n.textContent=o?`${a} — ${o}`:a,n.addEventListener("click",()=>{this.player.seek(s.t),this.closeMomentsMenu()}),i.appendChild(n),i})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const s=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==s&&(this.momentsCurrent.textContent=s);for(const i of this.momentsMenu.querySelectorAll("button")){const n=t!==void 0&&Number(i.dataset.t)===t.t;i.getAttribute("aria-current")==="true"!==n&&i.setAttribute("aria-current",String(n))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=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 i=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(a=>a>0&&a<t))].sort((a,o)=>a-o):[],Math.max(t,0)];this.seekSegmentList=[];const n=[];for(let a=0;a<i.length-1;a++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(i[a+1]-i[a],1));const r=document.createElement("i");r.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(r,c),n.push(o),this.seekSegmentList.push({start:i[a],end:i[a+1],element:o,played:c,hover:r})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const s=t.end-t.start,i=s>0?(e-t.start)/s:e>=t.end?1:0;return`${Math.min(Math.max(i,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,s=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=s,this.miniDot.style.left=s,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const s of this.seekSegmentList)s.played.style.width=Tt.fillOf(s,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(),s=this.player.seekableDuration;if(e.width<=0||s<=0)return;const i=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),n=i*s,a=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,m)=>{f.hover.style.width=Tt.fillOf(f,n),f.element.classList.toggle("hovered",n>=f.start&&(n<f.end||m===a))});const o=this.milestonesShown?this.sighting.milestones:[],r=o.length>0?Zr(o,n):void 0,c=r?this.said.read(r.label)??"":"",h=r?this.said.read(r.note):void 0,l=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=l,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(i*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(n)}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"),s=this.overlayPainter!==void 0||this.selectionShown;if(!s&&!this.chromeDirty)return;const i=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||i===0||n===0){t(this.canvasRenderer);return}const a=window.devicePixelRatio||1,o=Math.max(1,Math.round(i*a)),r=Math.max(1,Math.round(n*a));this.chromeCanvas.width!==o&&(this.chromeCanvas.width=o),this.chromeCanvas.height!==r&&(this.chromeCanvas.height=r),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,o,r),this.chromeDirty=!1,s&&(e.setTransform(o/this.canvas.width,0,0,r/this.canvas.height,0,0),this.chromeRenderer??=new Vo(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(),s=this.player.seekableDuration;if(e.width<=0||s<=0)return;const i=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(i*s))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,s=this.seekInput.getBoundingClientRect().width;if(e<=0||s<=0)return;const i=Tt.MARK_SNAP_PX/s*e;let n;for(const a of this.milestoneMarks.children){const o=Number(a.dataset.t);Math.abs(o-t)>i||(!n||Math.abs(o-t)<Math.abs(n.t-t))&&(n={t:o,name:a.title})}return n}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),s=this.player.seekableDuration;if(e.width<=0||s<=0)return;const i=(t.clientX-e.left)/e.width*s,n=this.markNear(i);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Zr(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const s=document.createElement("b");s.textContent=this.said.read(e.label)??"";const i=this.said.read(e.note),n=i?` — ${i}`:"";this.milestoneCaption.replaceChildren(s,document.createTextNode(n))}exposureInstants(t){const e=this.exposureTimes(t),s=1/e.length;return e.map(i=>({shapes:this.shapesAt(i),share:s}))}exposureTimes(t=this.currentTime){const e=ls.windowEndingAt(t,this.currentSighting.exposureAt(t)??0);if(e.ms<Tt.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const s=Math.min(Tt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Tt.SHORTEST_VISIBLE_EXPOSURE_MS))),i=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Tt.EXPOSURE_STEP_PX),n=Math.min(Tt.MAX_TRAVEL_STEPS,Math.max(s,i)),a=[];for(let o=0;o<n;o++)a.push(e.fromMs+e.ms*o/(n-1));return a}travelPxOver(t,e){const s=this.shapesAt(t),i=this.shapesAt(t+e);let n=0;for(const[a,o]of s){const r=i.get(a);if(!r)continue;const c=r.bounds.x+r.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=r.bounds.y+r.bounds.height/2-(o.bounds.y+o.bounds.height/2);n=Math.max(n,Math.hypot(c,h))}return n}shapeAt(t,e,s){if(this.accountHidden)return;const i=this.exposureTimes(),n=this.currentSighting.timeline;for(const r of i){const c=n.hitTest(r,t,e,s);if(c)return c}const a=this.canvas.getBoundingClientRect().width;if(a===0)return;const o=Tt.SHAPE_REACH_CSS_PX*this.canvas.width/a;for(const r of i){const c=n.hitNear(r,t,e,o,s);if(c)return c}}static SHAPE_REACH_CSS_PX=8;shapesAt(t){const e=new Map;for(const s of this.currentSighting.timeline.sourceIds){const i=this.currentSighting.timeline.getInterpolatedShapeAt(t,s);i&&e.set(s,i)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(t=this.currentTime){const e=je.frameWidthPx(this.currentSighting.instrumentAt(t),this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(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.currentSighting.changesInstrument&&this.applyFrameFormat(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const s=this.playbackState!=="playing"?this.highlightedSourceIds:Q1;this.canvasRenderer.setStarPoints(je.starPointsOf(this.sighting.instrumentAt(t),pt(this.sighting,t)?.fNumber));const i=(pt(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(i*Math.PI/180);const n=this.exposureInstants(t),a=this.frameShift;if(this.paintsShapes)for(const r of n)for(const[,c]of r.shapes){const h=r.share,l=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(l,a))}for(const[r,c]of n[0].shapes)!this.selectionShown||!s.has(r)||(this.paintsShapes?s.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,a)));const o=this.selectionShown&&s.size>1?Es.groupBoundsFor([...e].filter(([r])=>s.has(r)).map(([,r])=>r.bounds)):void 0;this.chromeDraw=r=>{o&&r.paintGroupHandles(o),this.overlayPainter?.(r)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(r=>[...r.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,a).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(Vf(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 z1(this.currentSighting.timeline,(e,s)=>this.onFrame(e,s));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(s=>s instanceof HTMLElement&&(s.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(s.tagName)&&s.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 s=this.player.seekableDuration;this.player.seek(Math.min(s,Math.max(0,this.player.time+e*Tt.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"?Q.PLAY:Q.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Tt.icons.get(t)!==e&&(Tt.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set namesHeld(t){this.namesHeldValue=t,t&&(this.tooltip.hidden=!0)}namesHeldValue=!1;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},Tt.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(),Tt.setIcon(this.playPauseButton,t?Q.PAUSE:Q.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const s=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=s,this.playPauseButton.setAttribute("aria-label",s)}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(Lo),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;Tt.setIcon(this.observerMapButton,t?Q.MAP_ON:Q.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const s=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[i,n]of s)i.title=n,i.setAttribute("aria-label",n)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=ko.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(i=>i.points):[],s=Yt.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,s))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,s),this.observerMapBounds=s,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 s=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<s&&Math.abs(t.south-e.south)<s&&Math.abs(t.west-e.west)<s&&Math.abs(t.east-e.east)<s}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,s=e?Yt.expand(t,Tt.OBSERVER_MAP_IMAGERY_AHEAD):t,i=Yt.IMAGERY_PX*(e?1+2*Tt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=s,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,a=n?void 0:Vm();try{const o=a?await a.getImageryTexture(s,{width:i,height:i}):await n.getImagery();if(this.observerMapImageryBounds!==s)return;this.observerMapImagery=o,this.observerMapImageryCredit=(a??n).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==s)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===s&&(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 s=this.observerMapImagery?.bounds??e,i=this.observerMapView.changed?Yt.expand(t,Tt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,n=i.west>=s.west&&i.east<=s.east&&i.south>=s.south&&i.north<=s.north,a=t.east-t.west>this.observerMapImageryViewWidth/2;return!n||!a}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],s=(c,h,l)=>{for(const d of e)if(!(d.x+d.width<c-l||d.x>h+l)&&!(d.y>t.bottom+l||d.y+d.height<t.top-l))return!0;return!1},i=[this.canvas.width-t.width,this.canvas.width],n=[0,t.width],a=Tt.OBSERVER_MAP_CLEARANCE_PX,o=s(...i,0),r=s(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&r&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(r||!s(i[0],i[1],a))&&this.observerMapPanel.classList.remove("on-the-left");return}s(i[0],i[1],0)&&!s(n[0],n[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 s=this.canvas.width/e.width,i=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*s,top:(t.top-e.top)*i,bottom:(t.bottom-e.top)*i}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=pt(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},Tt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const s=this.currentSighting.instrumentAt(t),i=[],n=this.currentSighting.milestones.length>0?Zr(this.currentSighting.milestones,t):void 0;for(const a of this.milestonesShown?vr(this.currentSighting.milestones):[]){const o=pt(this.currentSighting,a.t);o?.lat===void 0||o.lng===void 0||i.push({label:this.said.read(a.label)??"",note:this.said.read(a.note),t:a.t,lat:o.lat,lng:o.lng,current:a===n})}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?Yi.of(s,this.canvas.height,e.fovDeg).halfWidthAngleDeg(je.aspectOf(s)):void 0,markers:i,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(a=>({kind:a.kind,points:a.points,color:a.color,label:this.said.read(a.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,vr(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??"",Tt.setIcon(this.milestonesButton,this.milestonesShown?Q.MILESTONES_ON:Q.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=pt(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(s=>s.kind!=="crop").map(s=>{const i=wi(s,t),{lat:n,lng:a}=Ks(i.eastM,-i.northM,e.lat,e.lng);return{lat:n,lng:a,headingDeg:i.headingDeg,label:this.said.read(s.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,s=this.lookPitchDeg+t.pitchDeg;if(e===0&&s===0)return{x:0,y:0};const i=pt(this.currentSighting,this.currentTime),n=Yi.of(this.currentSighting.instrumentAt(this.currentTime),this.canvas.height,i?.fovDeg??60);return{x:-n.angleDegToRadiusPx(e),y:n.angleDegToRadiusPx(s)}}gaitAt(t){return Bt.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=Tt.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)),Tt.setIcon(this.miniMuteButton,this.mutedState?Q.MUTED:Q.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){Tt.setIcon(this.muteButton,Q.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Tt.setIcon(this.muteButton,this.mutedState?Q.MUTED:Q.VOLUME);const s=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=s,this.muteButton.setAttribute("aria-label",s),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Tt.setIcon(this.fullscreenButton,t?Q.EXIT_FULLSCREEN:Q.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 Nr(pn.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=pr(pn.preferencesFor(this),gr);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await Lp.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=Wf(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?_p(t.time):void 0;const s=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&s>0?s/this.realDurationMs:1,this.player.durationOverrideMs=s>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 Rn(t);const e=this.currentSighting.timeline.duration,s=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?Yd(Kd(this.realStartMs+s)):Rn(s)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Rn(t):Rn(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Rn(Math.max(0,e-t));const s=e>0&&t<=e?t/e*this.realDurationMs:t;return Rn(Math.max(0,this.realDurationMs-s))}formatEndOfTimeline(){return this.realDurationMs===void 0?Rn(this.currentSighting.timeline.duration):this.canShowClockTime?Yd(Kd(this.realStartMs+this.realDurationMs)):Rn(this.realDurationMs)}}function Kd(u){const t=new Date(u);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function Yd(u){if(u.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return u.second?`${t(u.hour)}:${t(u.minute??0)}:${t(u.second)}`:`${t(u.hour)}:${t(u.minute??0)}`}function Rn(u){const t=Math.round(u/1e3),e=Math.floor(t/60),s=t%60;return`${e}:${String(s).padStart(2,"0")}`}const au="rr0-ufo";function Wm(){customElements.get(au)||customElements.define(au,Tt)}const t2="timechange",e2="recordingissues",Km="minifiedreset";class so{constructor(t,e){this.labels=t,this.number=new Intl.NumberFormat(e,{minimumFractionDigits:2,maximumFractionDigits:2}),this.percent=new Intl.NumberFormat(e,{style:"percent",maximumFractionDigits:0})}static CANDIDATES_SECTION="candidates-section";static HVS_SECTION="hvs-section";static matrices=new Map;async poherOf(t,e){const[{PoherAnswers:s,PoherMatrix:i},{PoherAccountFacts:n},{WitnessError:a},{SightingFetch:o}]=await Promise.all([H(()=>import("./PoherMatrix-C2fcLqDH.js"),[],import.meta.url),H(()=>import("./PoherSelfCheck-pcYj_hQ1.js"),__vite__mapDeps([11,2,3,1,12,4,5,6,7,8,9,10]),import.meta.url),H(()=>Promise.resolve().then(()=>N1),void 0,import.meta.url),H(()=>import("./rr0-ufoathome.mjs").then(m=>m.a5),[],import.meta.url)]),r=i.chosenVersion(),c=`${r}/${e}`;let h=so.matrices.get(c);h||(h=i.load(r,e,m=>o.json(m)),h.catch(()=>so.matrices.delete(c)),so.matrices.set(c,h));const{matrix:l,labels:d}=await h,f=new s(a.MODELS[0],t.account?.conditions).of(n.of(t)).filter(m=>l.has(m.question));return this.poher(l.rank(f),f.length,d,r)}number;percent;poher(t,e,s,i){if(t.length===0||e===0)return;const n=this.labels.hypotheses,a=t.filter(f=>f.excludedBy.length===0),o=t.filter(f=>f.excludedBy.length>0),r=f=>s[f.phenomenon]??f.phenomenon,c=a[0];let h=n.allExcluded,l;if(c){const f=a.filter(m=>Math.abs(m.mean-c.mean)<1e-9).length-1;h=f>0?n.tied.replace("{name}",r(c)).replace("{n}",String(f)):r(c),l=n.poherDetail.replace("{mean}",this.percent.format(c.mean)).replace("{possible}",String(a.length)).replace("{of}",String(t.length))}const d=[...a.length>0?[n.possible.replace("{n}",String(a.length)).replace("{of}",String(t.length)),...a.map(f=>`${r(f)} ${this.percent.format(f.mean)}`)]:[],...o.length>0?[...a.length>0?[""]:[],n.excluded.replace("{n}",String(o.length)),o.map(r).join(", ")]:[]].join(`
|
|
1568
|
+
`);let e=fo.shared.get(t);return e||(e=this.fetchFirstAvailable(),fo.shared.set(t,e),e.then(s=>{s.length===0&&fo.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 s=await e.json();if(Array.isArray(s?.entries))return s.entries.map(i=>({entry:i,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.204.2")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==Hh?[e,Hh]:[Hh]).map(s=>s+t)}}class Vn{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 Dt(t)}static covers(t){return Dt.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((s,i)=>Vn.wayOf(s,i))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const s=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(s.length<2)return[];const i=String(t.properties.nature??""),n=Vn.BY_NATURE[i]??Vn.DEFAULT,a=Number(t.properties.largeur_de_chaussee),o=Number(t.properties.nombre_de_voies),r=Number(t.properties.vitesse_moyenne_vl),c=Vn.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=Vn.KINDS[i],l=[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}`),...l?{name:l}:{},surface:n.surface,widthM:Number.isFinite(a)&&a>0?a:n.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(o)&&o>0?{lanes:o}:{},...c?{direction:c}:{},...Number.isFinite(r)&&r>0?{speedKmh:r}:{},points:s}]}}class $1{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(Vn.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Fr{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Dt(t)}static covers(t){return Dt.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((s,i)=>Fr.surfacesOf(s,i))}static surfacesOf(t,e){const{type:s,coordinates:i}=t.geometry,n=s==="Polygon"?[i]:s==="MultiPolygon"?i:[],a=String(t.properties.cleabs??`ign-water-${e}`);return n.flatMap((o,r)=>{const c=o.map(h=>Fr.open(h.map(l=>({lat:l[1],lng:l[0]})))).filter(h=>h.length>=3);return c.length>0?[{id:n.length>1?`${a}-${r}`:a,rings:c}]:[]})}static open(t){const e=t[0],s=t[t.length-1];return t.length>1&&e.lat===s.lat&&e.lng===s.lng?t.slice(0,-1):t}}class la{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new ks(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,s=`[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 la.surfacesFrom(await this.client.query(s))}static surfacesFrom(t){const e=t.elements??[],s=new Map;for(const a of e)a.type==="way"&&a.id!==void 0&&a.geometry&&s.set(a.id,a.geometry.map(o=>({lat:o.lat,lng:o.lon})));const i=[],n=new Set;for(const a of e){if(a.type!=="relation")continue;const o=c=>(a.members??[]).filter(h=>h.type==="way"&&h.role===c&&h.ref!==void 0&&s.has(h.ref)).map(h=>(n.add(h.ref),s.get(h.ref))),r=la.rings(o("inner"));for(const[c,h]of la.rings(o("outer")).entries()){const l=r.filter(d=>la.contains(h,d[0]));i.push({id:`osm-r${a.id}-${c}`,rings:[h,...l]})}}for(const a of e)if(!(a.type!=="way"||!a.tags||a.id===void 0||n.has(a.id))&&!(a.tags.natural!=="water"&&a.tags.waterway!=="riverbank"))for(const o of la.rings([s.get(a.id)??[]]))i.push({id:`osm-w${a.id}`,rings:[o]});return i}static rings(t){const e=(n,a)=>n.lat===a.lat&&n.lng===a.lng,s=t.filter(n=>n.length>=2).map(n=>[...n]),i=[];for(;s.length>0;){let n=s.pop(),a=!0;for(;!e(n[0],n[n.length-1])&&a;){a=!1;for(let o=0;o<s.length;o++){const r=s[o],c=n[n.length-1];if(e(c,r[0]))n=[...n,...r.slice(1)];else if(e(c,r[r.length-1]))n=[...n,...[...r].reverse().slice(1)];else continue;s.splice(o,1),a=!0;break}}n.length>=4&&e(n[0],n[n.length-1])&&i.push(n.slice(0,-1))}return i}static contains(t,e){let s=!1;for(let i=0,n=t.length-1;i<t.length;n=i++){const a=t[i],o=t[n];a.lat>e.lat!=o.lat>e.lat&&e.lng<(o.lng-a.lng)*(e.lat-a.lat)/(o.lat-a.lat)+a.lng&&(s=!s)}return s}}class X1{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Fr.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const Uh="https://ufoathome.org/water/index.json";class mo{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??mo.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 s=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,s}async held(t){const s=(await this.load().catch(()=>[])).find(({entry:i})=>i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west);if(s)try{const i=await this.fetchImpl(new URL(s.entry.file,s.indexUrl).href);if(!i.ok)return;const n=await i.json();return Array.isArray(n?.surfaces)?(this.attributionRead=n.attribution,n.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1569
|
+
`);let e=mo.shared.get(t);return e||(e=this.fetchFirstAvailable(),mo.shared.set(t,e),e.then(s=>{s.length===0&&mo.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 s=await e.json();if(Array.isArray(s?.entries))return s.entries.map(i=>({entry:i,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.204.2")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==Uh?[e,Uh]:[Uh]).map(s=>s+t)}}class Ss{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=Ss.key(t);let s=Ss.asked.get(e);return s===void 0&&(s=this.recalled(e,t),Ss.asked.set(e,s),s.catch(()=>Ss.asked.delete(e))),structuredClone(await s)}static forget(){Ss.asked.clear()}static key(t){return`v${Ss.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const s=await Ss.openCache(),i=Ss.request(t);if(s)try{const a=await s.match(i);if(a){const{savedAt:o,surfaces:r}=await a.json();if(Date.now()-o<Ss.MAX_AGE_MS&&Array.isArray(r))return r;await s.delete(i)}}catch{}const n=await this.water.getWater(e);return s&&Ss.store(s,i,n),n}static async store(t,e,s){try{const i={savedAt:Date.now(),surfaces:s};await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const a of n.slice(0,Math.max(0,n.length-Ss.MAX_STORED)))await t.delete(a)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ss.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Wn{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 Dt(t)}static covers(t){return Dt.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((s,i)=>Wn.linesOf(s,i))}static linesOf(t,e){const{type:s,coordinates:i}=t.geometry,n=s==="LineString"?[i]:s==="MultiLineString"?i:[],a=Wn.BY_NATURE[String(t.properties.nature??"")];if(!a)return[];const o=String(t.properties.cleabs??`ign-rail-${e}`),r=Number(t.properties.nombre_de_voies),c=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,l=Wn.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Wn.electrificationOf(a.kind,l,t.properties.electrifie);return n.flatMap((f,m)=>{const p=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>Wn.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return p.length<2?[]:[{id:n.length>1?`${o}-${m}`:o,...typeof h=="string"&&h.length>0?{name:h}:{},kind:a.kind,...a.service?{service:!0}:{},...a.highSpeed?{highSpeed:!0}:{},gaugeMm:l,tracks:Number.isInteger(r)&&r>0?r:1,...d?{electrification:d}:{},level:Number.isFinite(c)?c:0,points:p}]})}static electrificationOf(t,e,s){if(s===!1)return"none";if(s===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class is{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 ks(t)}async named(t,e){if(t.length===0)return[...t];const s=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:120];way["railway"~"^(${is.KINDS})$"](${s})->.w;.w out tags geom;rel(bw.w)["route"~"^(${is.ROUTES})$"];out body;`;return is.apply(t,await this.client.query(i),e)}static apply(t,e,s){const i={lat:(s.north+s.south)/2,lng:(s.east+s.west)/2},n=is.ways(e,i);return n.length===0?[...t]:t.map(a=>{const o=a.points.map(M=>ot(M.lat,M.lng,i.lat,i.lng)),r=new Map,c=new Map,h=new Map;let l=0;const d=n.filter(M=>M.service===!!a.service);for(const M of is.samples(o)){l++;const v=is.waysAt(d,M);if(v.length===0)continue;const[y]=v;y.name&&r.set(y.name,(r.get(y.name)??0)+1),y.voltageV&&c.set(y.voltageV,(c.get(y.voltageV)??0)+1);for(const w of new Set(v.flatMap(b=>b.services)))h.set(w,(h.get(w)??0)+1)}const f=M=>[...M.entries()].sort((v,y)=>y[1]-v[1])[0]?.[0],m=a.name??f(r),p=a.voltageV??(a.electrification==="none"?void 0:f(c)),g=[...h.entries()].filter(([,M])=>M*4>=l).sort((M,v)=>v[1]-M[1]||M[0].localeCompare(v[0])).map(([M])=>M);return{...a,...m?{name:m}:{},...p?{voltageV:p}:{},...g.length>0?{services:g}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const s of t.elements??[]){if(s.type!=="relation"||!s.tags)continue;const i=is.serviceOf(s.tags);if(i)for(const n of s.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const a=e.get(n.ref)??new Set;a.add(i),e.set(n.ref,a)}}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 s=is.servicesByWay(t),i=[];for(const n of t.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const a=n.tags??{},o=is.voltageOf(a);i.push({service:!!a.service||a.usage==="industrial",...a.name?{name:a.name}:{},...o?{voltageV:o}:{},services:[...s.get(n.id??-1)??[]],path:n.geometry.map(r=>ot(r.lat,r.lon,e.lat,e.lng))})}return i}static samples(t){const e=[];for(let s=0;s<t.length-1;s++){const i=Math.hypot(t[s+1].x-t[s].x,t[s+1].z-t[s].z);if(i<1e-6)continue;const n=(t[s+1].x-t[s].x)/i,a=(t[s+1].z-t[s].z)/i;for(let o=is.SAMPLE_M/2;o<i;o+=is.SAMPLE_M)e.push({x:t[s].x+n*o,z:t[s].z+a*o,dx:n,dz:a})}return e}static waysAt(t,e){const s=Math.cos(is.ALIGNED_DEG*Math.PI/180),i=[];for(const n of t){let a;for(let o=0;o<n.path.length-1;o++){const r=n.path[o],c=n.path[o+1],h=c.x-r.x,l=c.z-r.z,d=Math.hypot(h,l);if(d<1e-6||Math.abs((h*e.dx+l*e.dz)/d)<s)continue;const f=Math.max(0,Math.min(1,((e.x-r.x)*h+(e.z-r.z)*l)/(d*d))),m=Math.hypot(e.x-(r.x+h*f),e.z-(r.z+l*f));m<=is.NEAR_M&&(a===void 0||m<a)&&(a=m)}a!==void 0&&i.push({way:n,distance:a})}return i.sort((n,a)=>n.distance-a.distance).map(({way:n})=>n)}}class po{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 ks(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:25];way["railway"~"^(${po.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${is.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(s))}linesFrom(t){const e=[],s=is.servicesByWay(t);for(const i of t.elements??[]){const n=i.geometry,a=i.tags;if(i.type==="relation"||!a||!n||n.length<2)continue;const o=[...s.get(i.id??-1)??[]].sort(),r=is.voltageOf(a),c=po.kindOf(a),h=Number.parseInt((a.gauge??"").split(";")[0],10),l=Number.parseInt(a.tracks??"",10),d=po.electrificationOf(a.electrified),f=a.highspeed==="yes"||Number.parseInt(a.maxspeed??"",10)>=250;e.push({id:`osm-rail-${i.id??e.length}`,...a.name?{name:a.name}:{},...o.length>0?{services:o}:{},...r?{voltageV:r}:{},kind:c,...a.service||a.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:a.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(l)&&l>0?l:1,...d?{electrification:d}:{},level:po.levelOf(a),points:n.map(m=>({lat:m.lat,lng:m.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 q1{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(!Wn.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(s){if(e)return e;throw s}}}class xe{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=xe.key(t);let s=xe.asked.get(e)??xe.containing(t);if(s===void 0){const i=this.recalled(e,t);s={bounds:t,answer:i},xe.asked.set(e,s),i.catch(()=>xe.asked.delete(e))}return structuredClone(await s.answer)}static forget(){xe.asked.clear(),xe.failedAt=-1/0}static key(t){return`v${xe.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of xe.asked.values()){const s=e.bounds;if(s.north>=t.north&&s.south<=t.south&&s.east>=t.east&&s.west<=t.west)return e}}async recalled(t,e){const s=await xe.openCache(),i=xe.request(t);let n;if(s)try{const o=await s.match(i);if(o){const{savedAt:r,lines:c}=await o.json();if(Array.isArray(c)){if(this.now()-r<xe.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-xe.failedAt<xe.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let a;try{a=await this.railways.getRailways(e)}catch(o){if(xe.failedAt=this.now(),n)return n;throw o}return s&&xe.store(s,i,{savedAt:this.now(),lines:a}),a}static async store(t,e,s){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const i=await t.keys();for(const n of i.slice(0,Math.max(0,i.length-xe.MAX_STORED)))await t.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(xe.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Gh="https://ufoathome.org/railways/index.json";class go{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??go.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 s=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,s}async held(t){const s=(await this.load().catch(()=>[])).find(({entry:i})=>i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west);if(s)try{const i=await this.fetchImpl(new URL(s.entry.file,s.indexUrl).href);if(!i.ok)return;const n=await i.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1570
|
+
`);let e=go.shared.get(t);return e||(e=this.fetchFirstAvailable(),go.shared.set(t,e),e.then(s=>{s.length===0&&go.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 s=await e.json();if(Array.isArray(s?.entries))return s.entries.map(i=>({entry:i,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.204.2")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Gh?[e,Gh]:[Gh]).map(s=>s+t)}}function Gm(){return{elevation:Bm(),imagery:Vm(),roads:j1(),water:Z1(),railways:J1()}}function Bm(){return new Y1(new vt,new hm)}function Vm(){return new Um}function j1(){return new fo({fallback:new $1(new Vn,new _n)})}function Z1(){return new mo({fallback:new Ss(new X1(new Fr,new la))})}function J1(){return new go({fallback:new xe(new q1(new Wn,new po))})}const Q1=new Set,Lo="show-observer-map",No="hide-milestones",ma="minified";class Tt extends HTMLElement{static get observedAttributes(){return["src",Lo,No,ma]}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 Yt;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=Bf.create();issues=[];issueCheck=0;sightingAudio=new Wd;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new Wd(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>Tt.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"),s=()=>t.scrollWidth>t.clientWidth+1,i=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&s()){t.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!s())break;t.classList.add(n)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!i,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Tt.setIcon(this.moreButton,t?Q.UNFOLDED:Q.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=Q.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",s=>{s.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:s}=await H(async()=>{const{VideoButton:n}=await import("./VideoButton-CvAmQpx0.js");return{VideoButton:n}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]),import.meta.url);if(this.videoElement!==e)return;const i=new s(t,e);this.videoButton=i,this.messages&&(i.messages=this.messages),this.stageElement.append(i.panel),i.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,s=t.caption&&this.sighting.milestones.length>0?Zr(this.sighting.milestones,e):void 0,i=s?this.said.read(s.label)??"":void 0,n=this.canvas.getBoundingClientRect(),a=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...s?{caption:{label:i,note:this.said.read(s.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...a&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(a.left-n.left)/n.width,top:(a.top-n.top)/n.height,width:a.width/n.width,height:a.height/n.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),s=e&&this.shapeAt(e.x,e.y),i=this.namesHeldValue?void 0:this.said.read(s?.shape.title);if(!i){this.tooltip.hidden=!0;return}this.tooltip.textContent=i,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-n.left+12}px`,this.tooltip.style.top=`${t.clientY-n.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 s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.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)<Tt.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const s=this.observerMapCanvas.getBoundingClientRect();return s.width>0&&s.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/s.width,(t.clientY-e.lastY)/s.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 s=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-s*.002))};zoomObserverMap(t,e,s){this.observerMapView.zoomAt(t,e,s),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Yt.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Yt.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Tt.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,s=this.observerMapCanvas.getBoundingClientRect();if(!e||s.width===0||s.height===0)return;const i=Yt.pointAt(e,(t.clientX-s.left)/s.width,(t.clientY-s.top)/s.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:i,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${_1}</style>${C1}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Vo(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",o=>{o.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 ha(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",o=>{o.key!=="Enter"&&o.key!==" "||(o.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"),s=e.querySelector(".mini-track"),i=o=>{const r=s.getBoundingClientRect(),c=this.player.seekableDuration;if(r.width<=0||c<=0)return;const h=Math.min(Math.max((o.clientX-r.left)/r.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;e.addEventListener("pointerdown",o=>{o.button===0&&(o.stopPropagation(),e.setPointerCapture(o.pointerId),e.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,i(o))}),e.addEventListener("pointermove",o=>{e.hasPointerCapture(o.pointerId)&&i(o)});const a=o=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(o.pointerId)&&e.releasePointerCapture(o.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a),e.addEventListener("click",o=>o.stopPropagation()),this.miniMuteButton.addEventListener("click",o=>{o.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",o=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(o),this.seekPreview.hidden=!0,this.beginTouchScrub(o)}),this.seekInput.addEventListener("pointerup",o=>{this.seekSnapArmed=!1,this.endTouchScrub(o)}),this.seekInput.addEventListener("pointercancel",o=>this.endTouchScrub(o)),this.seekInput.addEventListener("pointermove",o=>{this.nameMarkUnder(o),this.hoverSeek(o),this.touchScrub(o)}),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 o of["touchend","click"])this.stageElement.addEventListener(o,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",o=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}o.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",o=>{!this.enableClickToPlay||this.minified||(o.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,s){if(t==="src"&&s&&s!==e&&this.isConnected&&this.loadFromSrc(s),t===Lo&&this.applyObserverMapDefault(),t===No&&this.setMilestonesShown(!this.hasAttribute(No)),t===ma){const i=this.minified;this.stageElement.classList.toggle("minified",i),i&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(ma)}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(Km)))};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 Uf.recording(t)}get sightingData(){return Nm(this.currentSighting)}set sightingData(t){const e=ku.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=Ku(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 s=++this.issueCheck;let i=[];try{const{default:n}=await H(async()=>{const{default:a}=await import("./sightingSchema-DoPVOlCB.js");return{default:a}},[],import.meta.url);i=new ti(n).issues(t)}catch{}s===this.issueCheck&&(this.issues=[...i,...e.loadIssues],vd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(e2,{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(s=>{const i=document.createElement("li");return i.textContent=vd.text(s,this.messages.issueTemplates),i}))}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 s=document.createElement("button");s.type="button",s.className="cited-mark",s.innerHTML=ig.INTERVIEW,s.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const i=e.quote??"";return s.title=i,s.setAttribute("aria-label",i),s.addEventListener("click",()=>this.player.seek(e.at*1e3)),s}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Tt.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(t2,{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(i=>this.highlightedSourceIds.has(i))||(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 s of e)t.appendChild(s);else{const s=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const i of e)this.controlsRight.insertBefore(i,s)}}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(s=>s.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,s=4;e.style.bottom=`${Math.max(s,window.innerHeight-t.top+s)}px`,e.style.top="auto";const i=e.getBoundingClientRect().width;e.style.left=`${Math.max(s,Math.min(t.left,window.innerWidth-i-s))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const s=this.viewOfReference(e),i=this.said.read(e.title)??e.id,n=document.createElement("div");n.className="reference-row";const a=document.createElement("label"),o=document.createElement("input");o.type="checkbox",o.checked=s.shown;const r=document.createElement("span");r.textContent=i,r.title=i,a.append(o,r);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(s.opacity),c.title=this.messages?.referenceOpacity??"",c.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${i}`),c.disabled=!s.shown,o.addEventListener("change",()=>{s.shown=o.checked,c.disabled=!s.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{s.opacity=Number(c.value),this.dispatchReferenceView()}),n.append(a,c),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,s=e?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(s)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Tt.setIcon(this.referencesButton,s?Q.PICTURES_ON:Q.PICTURES_OFF);const i=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=i,this.referencesButton.setAttribute("aria-label",i),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)),Tt.setIcon(this.tracesButton,this.tracesShownState?Q.TRACES_ON:Q.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?vr(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(s=>{const i=document.createElement("button");i.type="button",i.className="milestone-mark",i.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`;const n=this.said.read(s.label)??"",a=this.said.read(s.note),o=a?`${n} — ${a}`:n;return i.title=o,i.setAttribute("aria-label",o),i.dataset.t=String(s.t),i.addEventListener("click",()=>this.player.seek(s.t)),i})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(s=>s.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(s=>{const i=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(s.t);const a=this.said.read(s.label)??"",o=this.said.read(s.note);return n.textContent=o?`${a} — ${o}`:a,n.addEventListener("click",()=>{this.player.seek(s.t),this.closeMomentsMenu()}),i.appendChild(n),i})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const s=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==s&&(this.momentsCurrent.textContent=s);for(const i of this.momentsMenu.querySelectorAll("button")){const n=t!==void 0&&Number(i.dataset.t)===t.t;i.getAttribute("aria-current")==="true"!==n&&i.setAttribute("aria-current",String(n))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=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 i=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(a=>a>0&&a<t))].sort((a,o)=>a-o):[],Math.max(t,0)];this.seekSegmentList=[];const n=[];for(let a=0;a<i.length-1;a++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(i[a+1]-i[a],1));const r=document.createElement("i");r.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(r,c),n.push(o),this.seekSegmentList.push({start:i[a],end:i[a+1],element:o,played:c,hover:r})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const s=t.end-t.start,i=s>0?(e-t.start)/s:e>=t.end?1:0;return`${Math.min(Math.max(i,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,s=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=s,this.miniDot.style.left=s,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const s of this.seekSegmentList)s.played.style.width=Tt.fillOf(s,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(),s=this.player.seekableDuration;if(e.width<=0||s<=0)return;const i=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),n=i*s,a=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,m)=>{f.hover.style.width=Tt.fillOf(f,n),f.element.classList.toggle("hovered",n>=f.start&&(n<f.end||m===a))});const o=this.milestonesShown?this.sighting.milestones:[],r=o.length>0?Zr(o,n):void 0,c=r?this.said.read(r.label)??"":"",h=r?this.said.read(r.note):void 0,l=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=l,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(i*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(n)}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"),s=this.overlayPainter!==void 0||this.selectionShown;if(!s&&!this.chromeDirty)return;const i=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||i===0||n===0){t(this.canvasRenderer);return}const a=window.devicePixelRatio||1,o=Math.max(1,Math.round(i*a)),r=Math.max(1,Math.round(n*a));this.chromeCanvas.width!==o&&(this.chromeCanvas.width=o),this.chromeCanvas.height!==r&&(this.chromeCanvas.height=r),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,o,r),this.chromeDirty=!1,s&&(e.setTransform(o/this.canvas.width,0,0,r/this.canvas.height,0,0),this.chromeRenderer??=new Vo(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(),s=this.player.seekableDuration;if(e.width<=0||s<=0)return;const i=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(i*s))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,s=this.seekInput.getBoundingClientRect().width;if(e<=0||s<=0)return;const i=Tt.MARK_SNAP_PX/s*e;let n;for(const a of this.milestoneMarks.children){const o=Number(a.dataset.t);Math.abs(o-t)>i||(!n||Math.abs(o-t)<Math.abs(n.t-t))&&(n={t:o,name:a.title})}return n}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),s=this.player.seekableDuration;if(e.width<=0||s<=0)return;const i=(t.clientX-e.left)/e.width*s,n=this.markNear(i);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Zr(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const s=document.createElement("b");s.textContent=this.said.read(e.label)??"";const i=this.said.read(e.note),n=i?` — ${i}`:"";this.milestoneCaption.replaceChildren(s,document.createTextNode(n))}exposureInstants(t){const e=this.exposureTimes(t),s=1/e.length;return e.map(i=>({shapes:this.shapesAt(i),share:s}))}exposureTimes(t=this.currentTime){const e=ls.windowEndingAt(t,this.currentSighting.exposureAt(t)??0);if(e.ms<Tt.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const s=Math.min(Tt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Tt.SHORTEST_VISIBLE_EXPOSURE_MS))),i=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Tt.EXPOSURE_STEP_PX),n=Math.min(Tt.MAX_TRAVEL_STEPS,Math.max(s,i)),a=[];for(let o=0;o<n;o++)a.push(e.fromMs+e.ms*o/(n-1));return a}travelPxOver(t,e){const s=this.shapesAt(t),i=this.shapesAt(t+e);let n=0;for(const[a,o]of s){const r=i.get(a);if(!r)continue;const c=r.bounds.x+r.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=r.bounds.y+r.bounds.height/2-(o.bounds.y+o.bounds.height/2);n=Math.max(n,Math.hypot(c,h))}return n}shapeAt(t,e,s){if(this.accountHidden)return;const i=this.exposureTimes(),n=this.currentSighting.timeline;for(const r of i){const c=n.hitTest(r,t,e,s);if(c)return c}const a=this.canvas.getBoundingClientRect().width;if(a===0)return;const o=Tt.SHAPE_REACH_CSS_PX*this.canvas.width/a;for(const r of i){const c=n.hitNear(r,t,e,o,s);if(c)return c}}static SHAPE_REACH_CSS_PX=8;shapesAt(t){const e=new Map;for(const s of this.currentSighting.timeline.sourceIds){const i=this.currentSighting.timeline.getInterpolatedShapeAt(t,s);i&&e.set(s,i)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(t=this.currentTime){const e=je.frameWidthPx(this.currentSighting.instrumentAt(t),this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(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.currentSighting.changesInstrument&&this.applyFrameFormat(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const s=this.playbackState!=="playing"?this.highlightedSourceIds:Q1;this.canvasRenderer.setStarPoints(je.starPointsOf(this.sighting.instrumentAt(t),pt(this.sighting,t)?.fNumber));const i=(pt(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(i*Math.PI/180);const n=this.exposureInstants(t),a=this.frameShift;if(this.paintsShapes)for(const r of n)for(const[,c]of r.shapes){const h=r.share,l=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(l,a))}for(const[r,c]of n[0].shapes)!this.selectionShown||!s.has(r)||(this.paintsShapes?s.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,a)));const o=this.selectionShown&&s.size>1?Es.groupBoundsFor([...e].filter(([r])=>s.has(r)).map(([,r])=>r.bounds)):void 0;this.chromeDraw=r=>{o&&r.paintGroupHandles(o),this.overlayPainter?.(r)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(r=>[...r.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,a).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(Vf(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 z1(this.currentSighting.timeline,(e,s)=>this.onFrame(e,s));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(s=>s instanceof HTMLElement&&(s.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(s.tagName)&&s.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 s=this.player.seekableDuration;this.player.seek(Math.min(s,Math.max(0,this.player.time+e*Tt.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"?Q.PLAY:Q.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Tt.icons.get(t)!==e&&(Tt.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set namesHeld(t){this.namesHeldValue=t,t&&(this.tooltip.hidden=!0)}namesHeldValue=!1;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},Tt.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(),Tt.setIcon(this.playPauseButton,t?Q.PAUSE:Q.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const s=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=s,this.playPauseButton.setAttribute("aria-label",s)}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(Lo),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;Tt.setIcon(this.observerMapButton,t?Q.MAP_ON:Q.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const s=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[i,n]of s)i.title=n,i.setAttribute("aria-label",n)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=ko.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(i=>i.points):[],s=Yt.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,s))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,s),this.observerMapBounds=s,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 s=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<s&&Math.abs(t.south-e.south)<s&&Math.abs(t.west-e.west)<s&&Math.abs(t.east-e.east)<s}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,s=e?Yt.expand(t,Tt.OBSERVER_MAP_IMAGERY_AHEAD):t,i=Yt.IMAGERY_PX*(e?1+2*Tt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=s,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,a=n?void 0:Vm();try{const o=a?await a.getImageryTexture(s,{width:i,height:i}):await n.getImagery();if(this.observerMapImageryBounds!==s)return;this.observerMapImagery=o,this.observerMapImageryCredit=(a??n).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==s)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===s&&(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 s=this.observerMapImagery?.bounds??e,i=this.observerMapView.changed?Yt.expand(t,Tt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,n=i.west>=s.west&&i.east<=s.east&&i.south>=s.south&&i.north<=s.north,a=t.east-t.west>this.observerMapImageryViewWidth/2;return!n||!a}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],s=(c,h,l)=>{for(const d of e)if(!(d.x+d.width<c-l||d.x>h+l)&&!(d.y>t.bottom+l||d.y+d.height<t.top-l))return!0;return!1},i=[this.canvas.width-t.width,this.canvas.width],n=[0,t.width],a=Tt.OBSERVER_MAP_CLEARANCE_PX,o=s(...i,0),r=s(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&r&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(r||!s(i[0],i[1],a))&&this.observerMapPanel.classList.remove("on-the-left");return}s(i[0],i[1],0)&&!s(n[0],n[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 s=this.canvas.width/e.width,i=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*s,top:(t.top-e.top)*i,bottom:(t.bottom-e.top)*i}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=pt(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},Tt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const s=this.currentSighting.instrumentAt(t),i=[],n=this.currentSighting.milestones.length>0?Zr(this.currentSighting.milestones,t):void 0;for(const a of this.milestonesShown?vr(this.currentSighting.milestones):[]){const o=pt(this.currentSighting,a.t);o?.lat===void 0||o.lng===void 0||i.push({label:this.said.read(a.label)??"",note:this.said.read(a.note),t:a.t,lat:o.lat,lng:o.lng,current:a===n})}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?Yi.of(s,this.canvas.height,e.fovDeg).halfWidthAngleDeg(je.aspectOf(s)):void 0,markers:i,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(a=>({kind:a.kind,points:a.points,color:a.color,label:this.said.read(a.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,vr(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??"",Tt.setIcon(this.milestonesButton,this.milestonesShown?Q.MILESTONES_ON:Q.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=pt(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(s=>s.kind!=="crop").map(s=>{const i=wi(s,t),{lat:n,lng:a}=Ks(i.eastM,-i.northM,e.lat,e.lng);return{lat:n,lng:a,headingDeg:i.headingDeg,label:this.said.read(s.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,s=this.lookPitchDeg+t.pitchDeg;if(e===0&&s===0)return{x:0,y:0};const i=pt(this.currentSighting,this.currentTime),n=Yi.of(this.currentSighting.instrumentAt(this.currentTime),this.canvas.height,i?.fovDeg??60);return{x:-n.angleDegToRadiusPx(e),y:n.angleDegToRadiusPx(s)}}gaitAt(t){return Bt.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=Tt.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)),Tt.setIcon(this.miniMuteButton,this.mutedState?Q.MUTED:Q.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){Tt.setIcon(this.muteButton,Q.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Tt.setIcon(this.muteButton,this.mutedState?Q.MUTED:Q.VOLUME);const s=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=s,this.muteButton.setAttribute("aria-label",s),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Tt.setIcon(this.fullscreenButton,t?Q.EXIT_FULLSCREEN:Q.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 Nr(pn.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=pr(pn.preferencesFor(this),gr);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await Lp.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=Wf(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?_p(t.time):void 0;const s=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&s>0?s/this.realDurationMs:1,this.player.durationOverrideMs=s>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 Rn(t);const e=this.currentSighting.timeline.duration,s=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?Yd(Kd(this.realStartMs+s)):Rn(s)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Rn(t):Rn(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Rn(Math.max(0,e-t));const s=e>0&&t<=e?t/e*this.realDurationMs:t;return Rn(Math.max(0,this.realDurationMs-s))}formatEndOfTimeline(){return this.realDurationMs===void 0?Rn(this.currentSighting.timeline.duration):this.canShowClockTime?Yd(Kd(this.realStartMs+this.realDurationMs)):Rn(this.realDurationMs)}}function Kd(u){const t=new Date(u);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function Yd(u){if(u.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return u.second?`${t(u.hour)}:${t(u.minute??0)}:${t(u.second)}`:`${t(u.hour)}:${t(u.minute??0)}`}function Rn(u){const t=Math.round(u/1e3),e=Math.floor(t/60),s=t%60;return`${e}:${String(s).padStart(2,"0")}`}const au="rr0-ufo";function Wm(){customElements.get(au)||customElements.define(au,Tt)}const t2="timechange",e2="recordingissues",Km="minifiedreset";class so{constructor(t,e){this.labels=t,this.number=new Intl.NumberFormat(e,{minimumFractionDigits:2,maximumFractionDigits:2}),this.percent=new Intl.NumberFormat(e,{style:"percent",maximumFractionDigits:0})}static CANDIDATES_SECTION="candidates-section";static HVS_SECTION="hvs-section";static matrices=new Map;async poherOf(t,e){const[{PoherAnswers:s,PoherMatrix:i},{PoherAccountFacts:n},{WitnessError:a},{SightingFetch:o}]=await Promise.all([H(()=>import("./PoherMatrix-C2fcLqDH.js"),[],import.meta.url),H(()=>import("./PoherSelfCheck-BjmenygA.js"),__vite__mapDeps([11,2,3,1,12,4,5,6,7,8,9,10]),import.meta.url),H(()=>Promise.resolve().then(()=>N1),void 0,import.meta.url),H(()=>import("./rr0-ufoathome.mjs").then(m=>m.a5),[],import.meta.url)]),r=i.chosenVersion(),c=`${r}/${e}`;let h=so.matrices.get(c);h||(h=i.load(r,e,m=>o.json(m)),h.catch(()=>so.matrices.delete(c)),so.matrices.set(c,h));const{matrix:l,labels:d}=await h,f=new s(a.MODELS[0],t.account?.conditions).of(n.of(t)).filter(m=>l.has(m.question));return this.poher(l.rank(f),f.length,d,r)}number;percent;poher(t,e,s,i){if(t.length===0||e===0)return;const n=this.labels.hypotheses,a=t.filter(f=>f.excludedBy.length===0),o=t.filter(f=>f.excludedBy.length>0),r=f=>s[f.phenomenon]??f.phenomenon,c=a[0];let h=n.allExcluded,l;if(c){const f=a.filter(m=>Math.abs(m.mean-c.mean)<1e-9).length-1;h=f>0?n.tied.replace("{name}",r(c)).replace("{n}",String(f)):r(c),l=n.poherDetail.replace("{mean}",this.percent.format(c.mean)).replace("{possible}",String(a.length)).replace("{of}",String(t.length))}const d=[...a.length>0?[n.possible.replace("{n}",String(a.length)).replace("{of}",String(t.length)),...a.map(f=>`${r(f)} ${this.percent.format(f.mean)}`)]:[],...o.length>0?[...a.length>0?[""]:[],n.excluded.replace("{n}",String(o.length)),o.map(r).join(", ")]:[]].join(`
|
|
1571
1571
|
`);return this.entry(so.CANDIDATES_SECTION,n.poher[i],h,l,t.length>1?d:void 0)}hvs(t,e){if(t.hypotheses.length===0)return;const s=this.labels.hypotheses,i=t.hypotheses.find(r=>r.dominant),n=i?[e(i.id),i.hvs?this.number.format(i.hvs.preferred):void 0].filter(Boolean).join(" "):s.noDominant,a=r=>r.hvs?.preferred??-1,o=[...t.hypotheses].sort((r,c)=>a(c)-a(r)).map(r=>{const c=this.number.format((r.csDiscriminating??r.csRaw).preferred),h=r.hvs&&r.ps?s.hvsLine.replace("{hvs}",this.number.format(r.hvs.preferred)).replace("{cs}",c).replace("{ps}",this.number.format(r.ps.preferred)):s.hvsLineNoPs.replace("{cs}",c),l=[r.admissible?s.admissible:s.notAdmissible,...r.dominant?[s.dominant]:[]].join(", ");return`${e(r.id)} — ${h} (${l})`}).join(`
|
|
1572
|
-
`);return this.entry(so.HVS_SECTION,s.hvs,n,i?this.hvsDetail(i):void 0,t.hypotheses.length>1?o:void 0)}hvsDetail(t){const e=t.csDiscriminating??t.csRaw;if(!t.hvs||!t.ps)return;const s=i=>this.number.format(i.preferred);return this.labels.hypotheses.hvsDetail.replace("{hvs}",s(t.hvs)).replace("{cs}",s(e)).replace("{ps}",s(t.ps))}entry(t,e,s,i,n){return{group:"hypothesis",field:t,label:e,value:n?`${s}…`:s,unit:"",fromSource:!1,about:"observation",...i?{detail:i}:{},...n?{expandable:n}:{}}}static fold(t,e,s,i){const
|
|
1572
|
+
`);return this.entry(so.HVS_SECTION,s.hvs,n,i?this.hvsDetail(i):void 0,t.hypotheses.length>1?o:void 0)}hvsDetail(t){const e=t.csDiscriminating??t.csRaw;if(!t.hvs||!t.ps)return;const s=i=>this.number.format(i.preferred);return this.labels.hypotheses.hvsDetail.replace("{hvs}",s(t.hvs)).replace("{cs}",s(e)).replace("{ps}",s(t.ps))}entry(t,e,s,i,n){return{group:"hypothesis",field:t,label:e,value:n?`${s}…`:s,unit:"",fromSource:!1,about:"observation",...i?{detail:i}:{},...n?{expandable:n}:{}}}static fold(t,e,s,i,n){const a=s.expandable;if(a===void 0)return;const o=n?document.createElement("button"):void 0;o&&n&&(o.type="button",o.className="chip-more",o.textContent=n.label,o.addEventListener("click",h=>{h.stopPropagation(),n.open()}),o.addEventListener("keydown",h=>h.stopPropagation()));const r=()=>{const h=i.has(s.field);t.toggleAttribute("data-expanded",h),t.setAttribute("aria-expanded",String(h)),e.textContent=h?a:s.value,o&&(h?t.append(o):o.remove())},c=h=>{h.stopPropagation(),i.delete(s.field)||i.add(s.field),r()};t.classList.add("expandable"),t.tagName!=="BUTTON"&&(t.tabIndex=0,t.setAttribute("role","button"),t.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),c(h))})),t.addEventListener("click",c),r()}static CSS=`
|
|
1573
1573
|
.param-chip.expandable, .param-label.expandable {
|
|
1574
1574
|
cursor: pointer;
|
|
1575
1575
|
}
|
|
@@ -1585,6 +1585,10 @@ canvas[data-cursor="rotate"] {
|
|
|
1585
1585
|
font-weight: normal;
|
|
1586
1586
|
margin-top: 0.2em;
|
|
1587
1587
|
}
|
|
1588
|
+
.param-chip .chip-more, .param-label .chip-more {
|
|
1589
|
+
display: block; margin-top: 0.35em; padding: 0; border: 0; background: none; color: inherit; font: inherit;
|
|
1590
|
+
text-decoration: underline; text-underline-offset: 2px; cursor: pointer;
|
|
1591
|
+
}
|
|
1588
1592
|
`}class qw{static sync(t,e,s,i,n){if(t.querySelector(".param-description")?.remove(),e===void 0){t.removeAttribute("data-describing");return}const a=document.createElement("div");a.className="param-description";const o=document.createElement("div");o.className="param-description-head";const r=document.createElement("span");r.className="param-nest-label",r.textContent=s;const c=document.createElement("button");c.type="button",c.className="param-description-close",c.textContent="×",c.title=i,c.setAttribute("aria-label",i),c.addEventListener("click",n),o.append(r,c);const h=document.createElement("p");h.className="param-description-text",h.textContent=e,a.append(o,h),a.addEventListener("keydown",l=>{l.key==="Escape"&&n()}),t.setAttribute("data-describing",""),t.append(a),c.focus({preventScroll:!0})}static CSS=`
|
|
1589
1593
|
.param-summary[data-describing] > :not(.param-description) {
|
|
1590
1594
|
display: none;
|
|
@@ -1626,7 +1630,7 @@ canvas[data-cursor="rotate"] {
|
|
|
1626
1630
|
.param-chip.describable, .param-label.describable {
|
|
1627
1631
|
cursor: pointer;
|
|
1628
1632
|
}
|
|
1629
|
-
`}class Ys{static earliestOf(t){return Date.UTC(t.year??0,(t.month??1)-1,t.day??1,t.hour??0,t.minute??0,t.second??0)}static latestOf(t){const e=t.year??9999;return t.month===void 0?Date.UTC(e+1,0,1)-1:t.day===void 0?Date.UTC(e,t.month,1)-1:t.hour===void 0?Date.UTC(e,t.month-1,t.day+1)-1:t.minute===void 0?Date.UTC(e,t.month-1,t.day,t.hour+1)-1:Date.UTC(e,t.month-1,t.day,t.hour,t.minute+1)-1}static boundsOf(t){const[e,s]=t.split("/"),i=e?ai(e):void 0,n=s?ai(s):void 0;if(!(!i||!n))return{min:Ys.timeAt(Ys.earliestOf(i)),max:Ys.timeAt(Ys.latestOf(n)-59999)}}static timeAt(t){const e=new Date(t);return{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate(),hour:e.getUTCHours(),minute:e.getUTCMinutes()}}}class pa{constructor(t){this.rateAt=t}static HISTORY_S=20;sums=[0];at(t){if(!(t>0))return 0;const e=Math.floor(t);for(;this.sums.length<=e+1;){const s=this.sums.length-1;this.sums.push(this.sums[s]+(this.rateAt(s)+this.rateAt(s+1))/2)}return this.sums[e]+(this.sums[e+1]-this.sums[e])*(t-e)}stateAt(t){return{impacts:this.at(t),history:Array.from({length:pa.HISTORY_S},(e,s)=>this.at(t-s-1))}}}class wt{static NONE={ghosts:[],blades:0,bladeAngleRad:0,scattered:0,drops:0,impacts:0,history:[],still:!1,running:0,reachDeg:30,placed:[]};static PHONE=[{scale:-1,share:5e-5,blur:.006,cause:"sensor",tint:[.41,1,.83]},{scale:-.45,share:5e-6,blur:.02,tint:[.7,1,.8]},{scale:.55,share:375e-8,blur:.035,tint:[1,.75,1]}];static CAMERA=[{scale:-1.4,share:3e-4,blur:.045,tint:[1,.8,1]},{scale:-.8,share:4e-4,blur:.02,tint:[.75,1,.8]},{scale:-.35,share:25e-5,blur:.012,tint:[1,.9,.7]},{scale:.3,share:2e-4,blur:.03,tint:[.8,.9,1]},{scale:.65,share:15e-5,blur:.06,tint:[1,.85,1]}];static FILTER={scale:-1,share:.001,blur:.004,cause:"filter"};static WINDOW={scale:1,share:.0016,blur:.002,offset:[0,.006],cause:"glass"};static WINDSCREEN={scale:1,share:.02,blur:.003,offset:[0,.025],cause:"glass"};static OFF_FRAME_REACH_DEG=30;static offFrameShare(t,e,s=wt.OFF_FRAME_REACH_DEG){const i=Math.min(Math.max((t-e)/s,0),1);return 1-i*i*(3-2*i)}static REFERENCE_F_NUMBER=4;static of(t){return t.ghosts?t.ghosts:wt.records(t)?t.category==="phone"?wt.PHONE:wt.CAMERA:[]}static records(t){return t.medium!==void 0||t.category==="camera"||t.category==="dslr"||t.category==="phone"}static optics(t,e,s,i,n=0){const a=wt.of(t);if(a.length===0)return wt.NONE;const o=t.fNumber??wt.REFERENCE_F_NUMBER,r=e??o,c=[...a,...s?.ghosts??[]].map(w=>({...w,blur:w.blur*o/r}));s?.glass==="filter"?c.push({...wt.FILTER}):s?.glass==="window"?c.push({...wt.WINDOW}):s?.glass==="windscreen"&&c.push({...wt.WINDSCREEN});const h=wt.share(s?.condensation),l=wt.share(s?.dirt),d=wt.falling(s),f=d?i?.impacts??0:0,m=d?i?.history??[]:[],p=f-(m[wt.DROP_LIFE_S-1]??0),g=s?.drops!==void 0?wt.share(s.drops):d?Math.min(1,p):0;h>0&&(c.push({scale:1,share:.25*h,blur:.03,cause:"condensation"}),c.push({scale:1,share:.15*h,blur:.12,cause:"condensation"})),l>0&&(c.push({scale:1,share:.03*l,blur:.04,cause:"dirt"}),c.push({scale:1,share:.02*l,blur:.15,cause:"dirt"})),g>0&&c.push({scale:1,share:.12*g,blur:.025,cause:"drops"});const M=c.filter(w=>wt.scatters(w)).reduce((w,b)=>w+b.share,0),v=je.bladesShowing(t,e)>=.5?t.apertureBlades??0:0,y=s?.glass==="window"||s?.glass==="windscreen"?1:.25;return{ghosts:c,blades:v,bladeAngleRad:.3,scattered:Math.min(.9,M),drops:g,impacts:f,history:m,still:s?.drops!==void 0,running:y,reachDeg:s?.reachDeg??wt.OFF_FRAME_REACH_DEG,placed:(s?.placedDrops??[]).map(w=>wt.placedAt(w,n))}}static placedAt(t,e){const s=t.track,i=s.findIndex(r=>r.t>e);if(i===0)return{x:s[0].x,y:s[0].y,radius:t.radius};if(i===-1){const r=s[s.length-1];return{x:r.x,y:r.y,radius:t.radius}}const n=s[i-1],a=s[i],o=(e-n.t)/(a.t-n.t);return{x:n.x+(a.x-n.x)*o,y:n.y+(a.y-n.y)*o,radius:t.radius}}static falling(t){return t?.drops===void 0&&!t?.sheltered}static DROP_LIFE_S=8;static impactRate(t,e,s){const i=wt.dropsFrom(t);if(i===0)return 0;const n=t.precipitationType==="snow"?1:6.5,a=((s?.windFromDeg??0)+180)*Math.PI/180,o=s?.windSpeedMS??0,r=[Math.sin(a)*o,Math.cos(a)*o,-n],c=(s?.headingDeg??0)*Math.PI/180,h=(e==="window"?0:e==="windscreen"?60:s?.pitchDeg??0)*Math.PI/180,l=[Math.sin(c)*Math.cos(h),Math.cos(c)*Math.cos(h),Math.sin(h)],d=Math.hypot(r[0],r[1],r[2]),f=Math.max(0,-(r[0]*l[0]+r[1]*l[1]+r[2]*l[2])/d);return i*.4*(.02+.98*f)}static scatters(t){return t.cause==="condensation"||t.cause==="dirt"||t.cause==="drops"}static dropsFrom(t){if(!t||t.precipitationType==="none"||t.precipitationType==="hail")return 0;const e=wt.share(t.precipitationIntensity);return e===0?0:t.precipitationType==="snow"?.5*e:Math.min(1,.3+.7*e)}static positionOf(t,e){return{x:e.x*t.scale+2*(t.offset?.[0]??0),y:e.y*t.scale+2*(t.offset?.[1]??0)}}static sourceOf(t,e){return{x:(e.x-2*(t.offset?.[0]??0))/t.scale,y:(e.y-2*(t.offset?.[1]??0))/t.scale}}static share(t){return Math.max(0,Math.min(1,t??0))}}const We=Math.PI/180;class tt{constructor(t){this.words=t}static COARSE_DEG=2;static FINE_DEG=.25;findingsOf(t,e){const s=as.strip(e).recording,i=s.interpretation?.mechanism;if(!i)return[];const n=tt.settingOf(t,i.explains);if(!n)return[];const a="interpretation.mechanism";switch(i.kind){case"fixed-in-frame":{const o=tt.missOf(n.samples,tt.fixedPoint(n.samples));return[this.finding(this.words.bestFixed,o,n,{},"established",a)]}case"driven-one-way":{const{miss:o,directionDeg:r}=tt.oneWay(n.samples);return[this.finding(this.words.bestOneWay,o,n,{direction:Math.round(r)},"established",a)]}case"lens-ghost":return this.lensGhostFindings(n,s,a);case"stated-ghost":return this.statedGhostFindings(n,s,a);case"ghost-of":return this.ghostOfFindings(n,s,i.of,a);case"real-object":return[this.realObjectFinding(n,s,i.explains,a)]}}ghostOfFindings(t,e,s,i){const n=e.interpretation?.bodies?.find(l=>l.id===s);if(!n)return[];const a=t.samples.map(l=>{const d=tt.bodyDirectionAt(n,l.t);if(!d)return;const f=d.applyQuaternion(l.frame.inverse);return f.z<0?{x:f.x/-f.z,y:f.y/-f.z}:void 0}),o=wt.of(je.byId(e.instrument)).filter(l=>!wt.scatters(l)).map(l=>l.scale);let r;for(const l of o){const d=a.map(m=>m?{x:l*m.x,y:l*m.y}:void 0),f=tt.missOfTrack(t.samples,d);(!r||f.medianDeg<r.miss.medianDeg)&&(r={miss:f,k:l,track:d})}if(!r)return[];const c=r.track.filter(l=>l!==void 0);let h=0;for(const l of c)for(const d of c)h=Math.max(h,tt.angleDeg(l,d));return[this.finding(this.words.bestGhostOf,r.miss,t,{k:this.number(r.k),ghostTravel:this.number(h)},"established",i)]}realObjectFinding(t,e,s,i){const a=e.interpretation?.bodies?.find(c=>c.explains?.includes(s))?.track[0]?.distanceM??tt.DEFAULT_DISTANCE_M,o=t.samples.map(c=>new D(c.at.x,c.at.y,-1).normalize().applyQuaternion(c.frame.rotation));let r=0;for(let c=0;c<o.length;c++){const h=t.samples.findIndex(l=>l.t>=t.samples[c].t+tt.RATE_WINDOW_MS);if(h<0)break;r=Math.max(r,o[c].angleTo(o[h])/((t.samples[h].t-t.samples[c].t)/1e3))}return{text:this.fill(this.words.bestRealObject,{medianDeg:0,maxDeg:0},t,{distance:Math.round(a),width:this.number(a*t.sizeDeg*We),speed:Math.round(a*r)}),outcome:"holds",against:"established",path:i}}static bodyDirectionAt(t,e){const s=t.track.filter(c=>c.azimuthDeg!==void 0&&c.altitudeDeg!==void 0);if(s.length===0)return;const i=s.findIndex(c=>c.t>e),n=s[i<=0?i===0?0:s.length-1:i-1],a=i<=0?n:s[i],o=a.t>n.t?(e-n.t)/(a.t-n.t):0,r=((a.azimuthDeg-n.azimuthDeg)%360+540)%360-180;return tt.direction(n.azimuthDeg+r*o,n.altitudeDeg+(a.altitudeDeg-n.altitudeDeg)*o)}static DEFAULT_DISTANCE_M=1e3;static RATE_WINDOW_MS=500;static lays(t){return t?.kind==="fixed-in-frame"||t?.kind==="driven-one-way"||t?.kind==="real-object"}bestSceneOf(t,e){const i=as.strip(e).recording.interpretation?.mechanism;if(!tt.lays(i))return;const n=tt.settingOf(t,i.explains);if(!n)return;const a=structuredClone(e);if(i.kind==="fixed-in-frame"||i.kind==="real-object"){const o=a.interpretation??{bodies:[]},r=o.bodies??[],c=r.findIndex(d=>d.explains?.includes(i.explains)),h=c>=0?r[c]:void 0,l=i.kind==="fixed-in-frame"?tt.stillBody(n,i.explains,h):tt.sightLineBody(n,i.explains,h);a.interpretation={...o,bodies:c>=0?r.map((d,f)=>f===c?l:d):[...r,l]}}else{const{track:o}=tt.oneWay(n.samples),r=a.lens?.placedDrops?.[0],c=n.samples[0],h=r?.radius??tt.round(n.sizeDeg/c.frame.fovDeg,4),l=n.samples.map((d,f)=>{const m=Math.tan(d.frame.fovDeg/2*We);return{t:d.t,x:tt.round(.5+o[f].x/(2*m*n.aspect),4),y:tt.round(.5-o[f].y/(2*m),4)}});a.lens={...a.lens,placedDrops:[{radius:h,track:l}]}}return a}static stillBody(t,e,s){const i=tt.fixedPoint(t.samples),n=t.samples[0].t,a=t.samples[t.samples.length-1].t,o=[...new Set([...t.samples.map(r=>r.t),...t.keyframes.map(r=>r.t).filter(r=>r>n&&r<a)])].sort((r,c)=>r-c);return tt.bodyAlong(t,e,s,o,()=>i)}static sightLineBody(t,e,s){return tt.bodyAlong(t,e,s,t.samples.map(i=>i.t),(i,n)=>t.samples[n].at)}static bodyAlong(t,e,s,i,n){const a=i[i.length-1],o=s?.track[0],r=o?.distanceM??tt.DEFAULT_DISTANCE_M,c=o?.sizeM??(()=>{const f=tt.round(r*t.sizeDeg*We,4);return{widthM:f,lengthM:f,heightM:f}})(),h=o?.appearance??{color:"#f4f6f5"},l=i.map((f,m)=>{const p=n(f,m),g=new D(p.x,p.y,-1).normalize().applyQuaternion(tt.frameAt(t.keyframes,f).rotation);return{t:f,...m===0?{present:!0,sizeM:c,appearance:h}:{},azimuthDeg:tt.round((Math.atan2(g.x,-g.z)/We+360)%360,3),altitudeDeg:tt.round(Math.asin(Math.min(1,Math.max(-1,g.y)))/We,3),distanceM:r}}),d=i.length>1?i[i.length-1]-i[i.length-2]:40;return{...s??{id:e,explains:[e],model:{id:"sphere"}},track:[...l,{t:a+d,present:!1}]}}static round(t,e){return Math.round(t*10**e)/10**e}lensGhostFindings(t,e,s){const i=wt.of(je.byId(e.instrument)).filter(c=>!wt.scatters(c)).map(c=>c.scale),n=e.lens?.reachDeg??wt.OFF_FRAME_REACH_DEG,a=c=>{const h=tt.sunTrack(t,c,n);if(!h)return;let l;for(const d of i){const f=tt.missOfTrack(t.samples,h.map(m=>({x:d*m.x,y:d*m.y})));(!l||f.medianDeg<l.miss.medianDeg)&&(l={miss:f,k:d})}return l},o=tt.bestSun(t,!0,a),r=[];if(o?r.push(this.finding(this.words.bestGhost,o.result.miss,t,{...this.sunWords(o.sun),k:this.number(o.result.k)},t.lightingGround,s)):r.push({text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:s}),t.lighting&&(!o||o.result.miss.medianDeg>t.sizeDeg)){const c=tt.bestSun(t,!1,a);c&&(!o||c.result.miss.medianDeg<o.result.miss.medianDeg-1e-6)&&r.push({text:this.fill(this.words.bestGhostNeeds,c.result.miss,t,{...this.sunWords(c.sun),k:this.number(c.result.k)}),outcome:"fails",against:t.lightingGround,path:"lighting"})}return r}statedGhostFindings(t,e,s){const i=e.lens?.reachDeg??wt.OFF_FRAME_REACH_DEG,n=r=>{const c=tt.sunTrack(t,r,i);if(!c)return;const h=tt.linearFit(c,t.samples.map(d=>d.at)),l=c.map(d=>({x:h.k*d.x+h.offset.x,y:h.k*d.y+h.offset.y}));return{miss:tt.missOfTrack(t.samples,l),...h}},a=tt.bestSun(t,!0,n);if(!a)return[{text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:s}];const o=Math.atan(Math.hypot(a.result.offset.x,a.result.offset.y))/We;return[this.finding(this.words.bestStatedGhost,a.result.miss,t,{...this.sunWords(a.sun),k:this.number(a.result.k),offset:this.number(o)},t.lightingGround,s)]}finding(t,e,s,i,n,a){return{text:this.fill(t,e,s,i),outcome:e.medianDeg<=s.sizeDeg?"holds":"fails",against:n,path:a}}fill(t,e,s,i){const n={median:this.number(e.medianDeg),max:this.number(e.maxDeg),size:this.number(s.sizeDeg),travel:this.number(s.travelDeg),...i};return t.replace(/\{(\w+)\}/g,(a,o)=>o in n?String(n[o]):a)}sunWords(t){return{bearing:Math.round(t.bearing),altitude:this.number(t.altitudeDeg)}}number(t){const e=Math.abs(t)<1?2:1;return t.toFixed(e).replace(".",this.words.decimal)}static settingOf(t,e){const{recording:s,provenance:i}=as.strip(t),n=s.observerTrack?.keyframes??[];if(n.length===0)return;const a=je.aspectOf(je.byId(s.instrument)),o=[],r=[];for(const d of s.timeline?.keyframes??[])for(const f of d.shapes??[]){const m=f.shape;if(f.sourceId!==e||!m.aim)continue;const p=tt.frameAt(n,d.t),g=tt.direction(m.aim.azimuthDeg,m.aim.altitudeDeg).applyQuaternion(p.inverse);g.z>=0||(o.push({t:d.t,at:{x:g.x/-g.z,y:g.y/-g.z},frame:p}),m.angular?.widthDeg&&r.push(m.angular.widthDeg))}if(o.length===0)return;r.sort((d,f)=>d-f);let c=0;for(const d of o)for(const f of o)c=Math.max(c,tt.angleDeg(d.at,f.at));const h=n[0].pose,l=h.lat??0;return{samples:o,keyframes:n,sizeDeg:r.length>0?r[Math.floor(r.length/2)]:.5,travelDeg:c,aspect:a,headingDeg:h.headingDeg??0,lighting:s.lighting,lightingGround:as.free(i.at("lighting"))?"supposed":"established",altitudes:{minDeg:-Math.acos(6371e3/(6371e3+Math.max(h.elevationM??0,0)))/We,maxDeg:tt.highestSun(s.time,i.at("time")?.range,l,h.lng??0)}}}static highestSun(t,e,s,i){const[n,a]=(typeof e=="string"?e:t??"").split("/"),o=n?ai(n):void 0,r=a?ai(a):o;if(!o||!r)return 90;const c=Ys.earliestOf(o),h=Ys.latestOf(r),l=864e5;let d=-90;for(let f=Math.floor(c/l)*l;f<=h;f+=l){const m=f+(12-i/15)*36e5;for(let p=-60;p<=60;p+=10)d=Math.max(d,Bn("Sun",new Date(m+p*6e4),{lat:s,lng:i,elevationM:0}).altitudeDeg)}return d}static frameAt(t,e){const s=t.findIndex(l=>l.t>e),i=t[s<=0?s===0?0:t.length-1:s-1],n=s<=0?i:t[s],a=n.t>i.t?(e-i.t)/(n.t-i.t):0,o=(l,d,f)=>(l??f)+((d??l??f)-(l??f))*a,r=(((n.pose.headingDeg??0)-(i.pose.headingDeg??0))%360+540)%360-180,c=(i.pose.headingDeg??0)+r*a,h=new Oa().setFromEuler(new $f(o(i.pose.pitchDeg,n.pose.pitchDeg,0)*We,-c*We,o(i.pose.rollDeg,n.pose.rollDeg,0)*We,"YXZ"));return{rotation:h,inverse:h.clone().invert(),fovDeg:o(i.pose.fovDeg,n.pose.fovDeg,50)}}static direction(t,e){const s=t*We,i=e*We;return new D(Math.sin(s)*Math.cos(i),Math.sin(i),-Math.cos(s)*Math.cos(i))}static angleDeg(t,e){const s=(t.x*e.x+t.y*e.y+1)/Math.sqrt((t.x*t.x+t.y*t.y+1)*(e.x*e.x+e.y*e.y+1));return Math.acos(Math.min(1,Math.max(-1,s)))/We}static missOf(t,e){return tt.missOfTrack(t,t.map(()=>e))}static missOfTrack(t,e){const s=t.map((i,n)=>e[n]?tt.angleDeg(i.at,e[n]):180).sort((i,n)=>i-n);return{medianDeg:s[Math.floor(s.length/2)],maxDeg:s[s.length-1]}}static fixedPoint(t){let e={x:t.reduce((s,i)=>s+i.at.x,0)/t.length,y:t.reduce((s,i)=>s+i.at.y,0)/t.length};for(let s=0;s<100;s++){let i=0,n=0,a=0;for(const o of t){const r=1/Math.max(Math.hypot(o.at.x-e.x,o.at.y-e.y),1e-9);i+=o.at.x*r,n+=o.at.y*r,a+=r}e={x:i/a,y:n/a}}return e}static oneWay(t){let e;for(let s=0;s<360;s+=5){const i={x:Math.sin(s*We),y:Math.cos(s*We)},n={x:i.y,y:-i.x},a=t.map(d=>d.at.x*i.x+d.at.y*i.y),o=t.map(d=>d.at.x*n.x+d.at.y*n.y).sort((d,f)=>d-f),r=o[Math.floor(o.length/2)],h=tt.neverBack(a).map(d=>({x:d*i.x+r*n.x,y:d*i.y+r*n.y})),l=tt.missOfTrack(t,h);(!e||l.medianDeg<e.miss.medianDeg||l.medianDeg===e.miss.medianDeg&&l.maxDeg<e.miss.maxDeg)&&(e={miss:l,directionDeg:s,track:h})}return e}static neverBack(t){const e=[];for(const s of t)for(e.push({sum:s,count:1});e.length>1&&e[e.length-2].sum/e[e.length-2].count>e[e.length-1].sum/e[e.length-1].count;){const i=e.pop();e[e.length-1].sum+=i.sum,e[e.length-1].count+=i.count}return e.flatMap(s=>new Array(s.count).fill(s.sum/s.count))}static sunTrack(t,e,s){const i=tt.direction(t.headingDeg+e.bearing,e.altitudeDeg),n=[];for(const a of t.samples){const o=i.clone().applyQuaternion(a.frame.inverse),r=Math.acos(Math.min(1,Math.max(-1,-o.z)))/We,c=Math.tan(a.frame.fovDeg/2*We),h=Math.atan(c*Math.hypot(1,t.aspect))/We;if(o.z>=0||r>=h+s)return;n.push({x:o.x/-o.z,y:o.y/-o.z})}return n}static linearFit(t,e){const s=t.length,i=h=>({x:h.reduce((l,d)=>l+d.x,0)/s,y:h.reduce((l,d)=>l+d.y,0)/s}),n=i(t),a=i(e);let o=0,r=0;for(let h=0;h<s;h++)o+=(t[h].x-n.x)*(e[h].x-a.x)+(t[h].y-n.y)*(e[h].y-a.y),r+=(t[h].x-n.x)**2+(t[h].y-n.y)**2;const c=r>1e-12?o/r:0;return{k:c,offset:{x:a.x-c*n.x,y:a.y-c*n.y}}}static bestSun(t,e,s){const i=h=>h.altitudeDeg>=t.altitudes.minDeg&&h.altitudeDeg<=t.altitudes.maxDeg&&(!e||!t.lighting||tt.lights(t.lighting,h));let n;const a=h=>{if(!i(h))return;const l=s(h);l&&(!n||l.miss.medianDeg<n.result.miss.medianDeg)&&(n={sun:h,result:l})},{minDeg:o,maxDeg:r}=t.altitudes;for(let h=0;h<360;h+=tt.COARSE_DEG){for(let l=o;l<=r;l+=tt.COARSE_DEG/2)a({bearing:h,altitudeDeg:l});a({bearing:h,altitudeDeg:r})}if(!n)return;const c=n.sun;for(let h=-2;h<=tt.COARSE_DEG;h+=tt.FINE_DEG)for(let l=-2;l<=tt.COARSE_DEG;l+=tt.FINE_DEG)a({bearing:((c.bearing+h)%360+360)%360,altitudeDeg:c.altitudeDeg+l});return n}static lights(t,e){const s=t.sunFromViewDeg,i=s?((e.bearing-s.fromDeg)%360+360)%360:0,n=s?((s.toDeg-s.fromDeg)%360+360)%360:360,a=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return i<=n&&a}}const s2=[{path:"place.locations.0.lat",what:"latitude"},{path:"place.locations.0.lng",what:"longitude"}];class pe{constructor(t){this.words=t,this.bestCases=new tt(t)}bestCases;found=new WeakMap;findingsOf(t,e){const s=as.strip(t),i=as.strip(e).recording,n=[],a=this.timeFinding(s.recording.time,s.provenance.at("time"),i.time);a&&n.push(a);for(const{path:r,what:c}of s2){const h=this.numberFinding(pe.at(s.recording,r),s.provenance.at(r),pe.at(i,r),this.words[c]);h&&n.push({...h,path:r})}const o=s.recording.lighting;if(o&&pe.movesTheSun(s.recording,i)){const r=this.lightingFinding(o,s.provenance.at("lighting"),i);r&&n.push(r)}return n.push(...this.bestCasesOf(t,e)),n}bestCasesOf(t,e){const s=JSON.stringify([e.interpretation?.mechanism,e.lens,e.instrument]),i=this.found.get(e);if(i&&i.account===t&&i.key===s)return i.findings;const n=this.bestCases.findingsOf(t,e);return this.found.set(e,{account:t,key:s,findings:n}),n}static withinInterval(t,e){const[s,i]=e.split("/"),n=s?ai(s):void 0,a=i?ai(i):void 0;if(!(!n&&!a))return!(n&&t.getTime()<Ys.earliestOf(n)||a&&t.getTime()>Ys.latestOf(a))}timeFinding(t,e,s){if(t===void 0||s===void 0||t===s)return;const i=ai(s),n=i?dn(i,0,0):void 0;if(typeof e?.range=="string"&&n){const a=pe.withinInterval(n,e.range);if(a===void 0)return;const o=a?this.words.timeWithin:this.words.timeOutside;return{text:pe.fill(o,{time:s,range:e.range}),outcome:a?"holds":"fails",against:"established",path:"time"}}if(!as.free(e))return{text:pe.fill(this.words.timeChanged,{from:t,time:s}),outcome:"fails",against:"established",path:"time"}}numberFinding(t,e,s,i){if(!(typeof t!="number"||typeof s!="number"||Math.abs(t-s)<1e-9)){if(Array.isArray(e?.range)){const[n,a]=e.range,o=(n===null||s>=n)&&(a===null||s<=a);return{text:pe.fill(o?this.words.valueWithin:this.words.valueOutside,{what:i,value:s,bounds:this.boundsOf(e.range)}),outcome:o?"holds":"fails",against:"established"}}if(!as.free(e))return{text:pe.fill(this.words.valueChanged,{what:i,from:t,value:s}),outcome:"fails",against:"established"}}}static movesTheSun(t,e){const s=a=>a.observerTrack?.keyframes?.[0]?.pose,i=s(t),n=s(e);return t.time!==e.time||t.utcOffsetHours!==e.utcOffsetHours||JSON.stringify(t.place)!==JSON.stringify(e.place)||i?.lat!==n?.lat||i?.lng!==n?.lng||i?.headingDeg!==n?.headingDeg}lightingFinding(t,e,s){const i=s.time?ai(s.time):void 0,n=i?pe.sunOf(i,s):void 0;if(!n)return;const{bearing:a}=n,{fromDeg:o,toDeg:r}=t.sunFromViewDeg??{fromDeg:0,toDeg:360},{minDeg:c,maxDeg:h}=t.sunAltitudeDeg??{minDeg:-90,maxDeg:90},l=pe.lights(t,n),d=as.free(e)?"supposed":"established",f=m=>Math.round(m);return{text:pe.fill(l?this.words.lightingHolds:this.words.lightingFails,{bearing:f(a),altitude:f(n.altitudeDeg),from:o,to:r,altitudes:t.sunAltitudeDeg?pe.fill(this.words.altitudes,{min:c,max:h}):""}),outcome:l?"holds":"fails",against:d,path:"lighting",...e?.rationale?{rationale:e.rationale}:{}}}static standOf(t){const e=as.strip(t).recording,s=e.observerTrack?.keyframes?.[0]?.pose,i=e.place?.locations?.[0],n=s?.lat??i?.lat,a=s?.lng??i?.lng;if(!(n===void 0||a===void 0||s?.headingDeg===void 0))return{lat:n,lng:a,elevationM:s.elevationM??0,headingDeg:s.headingDeg,utcOffsetHours:e.utcOffsetHours}}static sunOf(t,e){const s=pe.standOf(e);return s?pe.sunFrom(t,s):void 0}static sunFrom(t,e){if(t.hour===void 0)return;const s=dn(t,e.lng,e.utcOffsetHours);if(!s)return;const i=Bn("Sun",s,e);return{bearing:((i.azimuthDeg-e.headingDeg)%360+360)%360,altitudeDeg:i.altitudeDeg}}static lights(t,e){const s=t.sunFromViewDeg?pe.onArc(e.bearing,t.sunFromViewDeg.fromDeg,t.sunFromViewDeg.toDeg):!0,i=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return s&&i}static nearestLit(t,e,s){const i=l=>({...e,hour:Math.floor(l/60),minute:l%60,second:void 0,raw:void 0}),n=pe.standOf(s);if(!n)return;const a=l=>{const d=pe.sunFrom(i(l),n);return d!==void 0&&pe.lights(t,d)};if(e.hour===void 0)return;const o=e.hour*60+(e.minute??0);if(a(o))return e;const r=5;let c;for(let l=0;l<1440;l+=r)a(l)&&(c===void 0||Math.abs(l-o)<Math.abs(c-o))&&(c=l);if(c===void 0)return;const h=o<c?-1:1;for(;c+h>=0&&c+h<1440&&a(c+h)&&Math.abs(c+h-o)<Math.abs(c-o);)c+=h;return i(c)}static onArc(t,e,s){const i=((s-e)%360+360)%360;return((t-e)%360+360)%360<=i}static at(t,e){return e.split(".").reduce((s,i)=>s?.[i],t)}boundsOf([t,e]){return t===null?pe.fill(this.words.atMost,{max:e??""}):e===null?pe.fill(this.words.atLeast,{min:t}):pe.fill(this.words.between,{min:t,max:e})}static fill(t,e){return t.replace(/\{(\w+)\}/g,(s,i)=>i in e?String(e[i]):s)}}const jw=Sn.catalog({en:()=>H(()=>import("./ReadingCheckTexts_en-C5qzU8K7.js"),[],import.meta.url).then(u=>u.readingCheckTexts_en),fr:()=>H(()=>import("./ReadingCheckTexts_fr-COtovvqc.js"),[],import.meta.url).then(u=>u.readingCheckTexts_fr),es:()=>H(()=>import("./ReadingCheckTexts_es-DdhtmSew.js"),[],import.meta.url).then(u=>u.readingCheckTexts_es),it:()=>H(()=>import("./ReadingCheckTexts_it-Bz32XGh6.js"),[],import.meta.url).then(u=>u.readingCheckTexts_it)});class Zw{static of(t){if(!(!t||t.length===0))return t.some(e=>e.outcome==="fails"&&e.against!=="supposed")?"incompatible":t.some(e=>e.outcome!=="holds")?"unsettled":"compatible"}}class vs{constructor(t,e,s,i="en"){this.parts=t,this.messages=e,this.onChange=s,this.locale=i,e&&this.setMessages(e),t.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),t.picker.addEventListener("change",()=>this.writeFromPicker()),t.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),t.text.addEventListener("blur",()=>this.validate()),t.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";setBounds(t){this.bounds=t;const{picker:e}=this.parts;e.min=t?vs.pickerValueOf(t.min):"",e.max=t?vs.pickerValueOf(t.max):""}bounds;bounded(t){if(!this.bounds)return t;const e=Ys.latestOf(t)<Ys.earliestOf(this.bounds.min)?this.bounds.min:Ys.earliestOf(t)>Ys.earliestOf(this.bounds.max)?this.bounds.max:t;return this.bounds.adjust?.(e)??e}get isPrecise(){return this.precise}setMessages(t,e=this.locale){this.messages=t,this.locale=e,t.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=t.edtfPlaceholder),this.parts.mode.title=t.edtfModeTitle,this.parts.mode.setAttribute("aria-label",t.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(t){this.precise=t,this.parts.picker.hidden=!t,this.parts.text.hidden=t,this.parts.mode.textContent=(t?this.messages?.datePrecise:this.messages?.dateEdtf)??"",this.parts.mode.setAttribute("aria-pressed",String(!t)),this.parts.help&&(this.parts.help.hidden=t),this.showDeduction()}set(t){const{text:e,picker:s}=this.parts;e.value=t?oo(t):"",s.type!=="date"&&(s.step=vs.stepFor(t)),s.value=s.type==="date"?vs.pickerDateOf(t):vs.pickerValueOf(t),e.setCustomValidity(""),e.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...t){return t.every(e=>e===void 0||vs.isPickable(e)&&vs.qualifierOf(oo(e))==="")}static opensPreciseDate(...t){return t.every(e=>e===void 0||vs.isFullDate(e)&&vs.qualifierOf(oo(e))==="")}static isFullDate(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0}static pickerDateOf(t){if(!vs.isFullDate(t))return"";const e=(s,i=2)=>String(s).padStart(i,"0");return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}`}static isPickable(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0&&t.hour!==void 0&&t.minute!==void 0}static pickerValueOf(t){if(!vs.isPickable(t))return"";const e=(i,n=2)=>String(i).padStart(n,"0"),s=t.second?`:${e(t.second)}`:"";return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}T${e(t.hour)}:${e(t.minute)}${s}`}static stepFor(t){return t?.second?"1":"60"}static qualifierOf(t){const e=/[?%]/.test(t),s=/[~%]/.test(t);return e&&s?"%":e?"?":s?"~":""}describe(t){return this.messages?vs.describeTime(t,this.messages,this.locale):""}static describeTime(t,e,s){const i=oo(t),n=vs.qualifierOf(i),a=h=>String(h).padStart(2,"0"),o=[];if(t.season!==void 0){const h={spring:e.timeSeasonSpring,summer:e.timeSeasonSummer,autumn:e.timeSeasonAutumn,winter:e.timeSeasonWinter}[t.season];o.push(t.year!==void 0?`${h} ${t.year}`:h)}else if(t.year!==void 0){const h=t.day!==void 0?{...t.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:t.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},l=new Date(Date.UTC(t.year,(t.month??1)-1,t.day??1));o.push(new Intl.DateTimeFormat(s,{...h,timeZone:"UTC"}).format(l))}t.hour!==void 0&&o.push(`${a(t.hour)}:${a(t.minute??0)}${t.second!==void 0?`:${a(t.second)}`:""}`);const r=o.join(", "),c=n==="~"?e.timeQualifierApproximate:n==="?"?e.timeQualifierUncertain:n==="%"?e.timeQualifierBoth:"";return c?`${r} — ${c.toLowerCase()}`:r}setHint(t){this.hint=t,this.showDeduction()}showDeduction(){const{text:t}=this.parts,e=t.value.trim();if(this.precise||e===""){t.title=this.hint;return}const s=ai(e);t.title=s?`→ ${this.describe(s)}`:this.messages?.edtfInvalid??""}readText(){const t=this.parts.text.value.trim();if(t===""){this.clean(),this.onChange(void 0);return}const e=ai(t);if(!e)return;this.clean();const s=this.bounded(e);s!==e&&this.set(s),this.onChange(s)}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:t,text:e}=this.parts;t.value===""&&t.validity.badInput||(e.value=t.value===""?"":t.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:t}=this.parts,e=t.value.trim();e===""||ai(e)||(t.setCustomValidity(this.messages?.edtfInvalid??""),t.classList.add("invalid"))}}const $d="#ff2200",Xd="#00ff44",ta="#ffffff",tc="#ffa500",Ua="#ff0000",i2="#2244ff",ou=[{id:"airliner",name:"Airliner",kinds:["aircraft"],referenceSizeM:{widthM:34,heightM:12,lengthM:36},create:()=>[{id:"nav-port",offsetM:{x:-17,y:0,z:0},color:$d,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:Xd,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:ta,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:Ua,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:Ua,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:ta,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:ta,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01,phase:.08}}]},{id:"helicopter",name:"Helicopter",kinds:["aircraft"],referenceSizeM:{widthM:10,heightM:4,lengthM:14},create:()=>[{id:"nav-port",offsetM:{x:-5,y:0,z:0},color:$d,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:Xd,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:ta,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:Ua,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:ta,intensity:15,pattern:{kind:"flash",perMinute:75,dutyCycle:.015}}]},{id:"car-headlights",name:"Car, headlights on",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"head-left",offsetM:{x:-.7,y:.6,z:2},color:ta,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:ta,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:Ua,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:Ua,pattern:{kind:"steady"}}]},{id:"car-hazards",name:"Car, hazard flashers",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"hazard-front-left",offsetM:{x:-.8,y:.6,z:2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}}]},{id:"emergency-beacons",name:"Emergency vehicle beacons",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"beacon-blue",offsetM:{x:-.4,y:1.6,z:0},color:i2,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:Ua,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>at.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>at.pedestrianLights(0)},{id:"streetlamp",name:"Streetlamp",kinds:["streetlight"],referenceSizeM:{widthM:1,heightM:5,lengthM:1},create:()=>[{id:"lamp",offsetM:{x:0,y:5,z:0},color:"#ffd9a0",intensity:2,pattern:{kind:"steady"}}]}];class jc{static forKind(t){return ou.filter(e=>e.kinds.includes(t))}static byId(t){return ou.find(e=>e.id===t)}}class at{static CYCLE_S=90;static GREEN_S=41;static AMBER_S=3;static PEDESTRIAN_DELAY_S=2;static PEDESTRIAN_GREEN_S=30;static VEHICLE_INTENSITY=3;static PEDESTRIAN_INTENSITY=1.5;static LENS_RADIUS_M=.1;static BEAM_DEG=30;static VEHICLE_HEAD_Y_M=2.9;static PEDESTRIAN_HEAD_Y_M=2.6;static LENS_SPACING_M=.3;static LENS_FRONT_M=.13;static RED="#ff1e00";static AMBER="#ffa200";static GREEN="#00ff8c";static phaseOf(t){const e=(t%180+180)%180;return e>=45&&e<135?1:0}static vehicleLights(t){const e=t*at.CYCLE_S/2,s=at.VEHICLE_HEAD_Y_M,i=at.LENS_SPACING_M;return[at.lamp("red",at.RED,s+i,e+at.GREEN_S+at.AMBER_S,at.CYCLE_S-at.GREEN_S-at.AMBER_S,at.VEHICLE_INTENSITY),at.lamp("amber",at.AMBER,s,e+at.GREEN_S,at.AMBER_S,at.VEHICLE_INTENSITY),at.lamp("green",at.GREEN,s-i,e,at.GREEN_S,at.VEHICLE_INTENSITY)]}static pedestrianLights(t){const e=t*at.CYCLE_S/2+at.GREEN_S+at.AMBER_S+at.PEDESTRIAN_DELAY_S,s=at.PEDESTRIAN_HEAD_Y_M,i=at.LENS_SPACING_M/2;return[at.lamp("ped-red",at.RED,s+i,e+at.PEDESTRIAN_GREEN_S,at.CYCLE_S-at.PEDESTRIAN_GREEN_S,at.PEDESTRIAN_INTENSITY),at.lamp("ped-green",at.GREEN,s-i,e,at.PEDESTRIAN_GREEN_S,at.PEDESTRIAN_INTENSITY)]}static isPedestrian(t){return t?.some(e=>e.id==="ped-green")??!1}static figureOf(t){return t.id==="ped-red"?"standing":t.id==="ped-green"?"walking":void 0}static lamp(t,e,s,i,n,a){const o=at.CYCLE_S,r=Math.round(((1-i/o)%1+1)%1*1e6)/1e6;return{id:t,color:e,intensity:a,radiusM:at.LENS_RADIUS_M,beamDeg:at.BEAM_DEG,offsetM:{x:0,y:s,z:-.13},pattern:{kind:"flash",perMinute:60/o,dutyCycle:Math.round(n/o*1e6)/1e6,...r?{phase:r}:{}}}}}class yr{static of(t,e){const s=yr.drawnAsModel(t);return{color:e?.color??!s,lit:e?.lit??yr.litByDefault(t.kind,s),headlights:t.kind==="vehicle",lights:(e?.lights??!0)&&yr.rigsFor(t.kind,e).length>0,windows:!s&&am(t.kind),floors:!s&&t.kind==="building",observerSide:Bo(t.kind)}}static rigsFor(t,e){return jc.forKind(t).filter(s=>e?.lightRigs===void 0||e.lightRigs.includes(s.id))}static drawnAsModel(t){return Bc(t)!==void 0&&!(t.observerSide!==void 0&&Bo(t.kind))}static litByDefault(t,e){return t==="streetlight"||t==="vehicle"&&!e}}class qt{static sideLabel(t){return qt.SIDE_LABELS[t]}static SIDE_LABELS={front:"front",behind:"behind",left:"left",right:"right","front-left":"frontLeft","front-right":"frontRight","behind-left":"behindLeft","behind-right":"behindRight"};static WINDOWS="windows";static BUILDING="building";static BRIDGE="bridge";static RAILING="railing";static WIRE="overheadLine";static together(t,e){return`${t} ${e}`}static of(t,e){const s=[],i=yr.drawnAsModel(t);if(!i&&t.kind==="building"&&s.push(...qt.floors(),...qt.walls(),...qt.roof()),!i&&am(t.kind)&&s.push(...qt.windows(t.kind)),t.kind==="vehicle"&&s.push(...qt.engine()),t.kind==="observer"&&s.push(...qt.observerRecording()),t.kind==="aircraft"&&s.push(...qt.aircraftSound(e)),t.kind==="bridge"&&s.push(...qt.bridge()),t.kind==="wire"&&s.push(...qt.wire()),e?.parameters&&s.push(...e.parameters.map(n=>({...n,key:`modelParameters.${n.key}`}))),s.length!==0)return{kind:`decor-${t.kind}`,title:"properties",parameters:s}}static floors(){const t=e=>ur.read(e,"floors")??Vc;return[{type:"number",key:"floors",min:0,max:20,step:1,effective:()=>Vc,label:"floors",hint:"upperStoriesAboveTheGround",group:qt.BUILDING},{type:"number",key:"occupiedFloor",min:0,max:20,step:1,effective:()=>0,bounds:e=>({max:t(e)}),label:"occupiedFloor",hint:"theFloorTheWitnessIs",group:qt.BUILDING}]}static walls(){const t="walls";return[{type:"colour",key:"facade.color",group:t,fallback:"#d3cab8",label:"wallColour",hint:"theColourOfTheWalls"},{type:"choice",key:"facade.openings",group:t,label:"facade",empty:"aHouseS",hint:"aHouseSAWindowEvery",choices:[{value:"tall",label:"oldBuilding"},{value:"lancet",label:"church"},{value:"plain",label:"bareWall"},{value:"none",label:"noFacade"}]}]}static roof(){const t="roof";return[{type:"choice",key:"roof.shape",group:t,label:"roof",empty:"flat",hint:"flatTheBoxTwoSlopes",choices:[{value:"flat",label:"flat"},{value:"gable",label:"twoSlopes"},{value:"hip",label:"fourSlopes"},{value:"dome",label:"dome"}]},{type:"number",key:"roof.riseM",min:0,max:15,step:.1,unit:"m",group:t,effective:()=>3,label:"rise",hint:"howFarTheRidgeStands",visibleWhen:s=>["gable","hip","dome"].includes(String(ur.read(s,"roof.shape")))},{type:"choice",key:"roof.ridge",group:t,required:!1,label:"ridgeAlong",empty:"theWidth",choices:[{value:"width",label:"theWidth"},{value:"depth",label:"theDepth"}],visibleWhen:s=>ur.read(s,"roof.shape")==="gable"},{type:"colour",key:"roof.color",group:t,fallback:"#7a5a4a",label:"roofColour"}]}static windows(t){return ag(t).map(e=>({type:"number",key:`windows.${e}`,step:5,unit:"%",min:rg(t,e)?0:og,max:100,label:qt.SIDE_LABELS[e],summary:qt.together(qt.WINDOWS,qt.SIDE_LABELS[e]),hint:"opacityOfTheWindowOn",group:qt.WINDOWS}))}static engine(){const t="engineSound";return[{type:"choice",key:"engine.kind",group:t,label:"engine",hint:"whetherTheVehicleIsHeard",empty:"silentParked",choices:[{value:"car",label:"car"},{value:"van",label:"van"},{value:"truck",label:"truck"},{value:"motorcycle",label:"motorcycle"},{value:"generic",label:"unknown"}]},{type:"number",key:"engine.noise",min:.1,max:3,step:.1,group:t,effective:()=>1,label:"loudness",hint:"againstAnOrdinaryOneOf",visibleWhen:e=>ur.read(e,"engine.kind")!==void 0||e.engine!==void 0}]}static observerRecording(){return[{type:"text",key:"sightingUrl",placeholder:"https://…/sighting.json",label:"theirOwnRecordingURL"}]}static aircraftSound(t){return[{type:"choice",key:"aircraftSound",group:"sound",label:"noiseInFlight",hint:"whatItSoundsLikeWhile",empty:t?.sound==="silent"?"silentAsTheModel":"asTheModel",choices:[{value:"airliner-narrow",label:"aircraftNarrowBodyAirliner"},{value:"airliner-wide",label:"aircraftWideBodyAirliner"},{value:"airliner-supersonic",label:"aircraftSupersonicAirliner"},{value:"regional-jet",label:"aircraftRegionalJet"},{value:"regional-turboprop",label:"aircraftTurboprop"},{value:"business-jet",label:"aircraftBusinessJet"},{value:"light-piston",label:"aircraftLightPistonAircraft"},{value:"piston-heavy",label:"aircraftHeavyPistonAircraft"},{value:"helicopter-light",label:"aircraftLightHelicopter"},{value:"helicopter-medium",label:"aircraftMediumHelicopter"},{value:"helicopter-heavy",label:"aircraftHeavyHelicopter"},{value:"military-jet",label:"aircraftMilitaryJet"},{value:"ultralight",label:"aircraftUltralight"},{value:"unmanned",label:"aircraftDrone"},{value:"glider",label:"aircraftGlider"},{value:"silent",label:"aircraftSilent"}]}]}static bridge(){const t=(e,s,i,n,a,o,r,c,h)=>({type:"number",key:e,label:s,min:i,max:n,step:a,unit:o,group:c,hint:h,effective:r===void 0?void 0:()=>r});return[t("bridge.spanM","span",.1,5e3,.1,"m",void 0,qt.BRIDGE,"metresOfOpenSpanUnder"),t("bridge.deckThicknessM","deckThickness",.1,20,.1,"m",1.2,qt.BRIDGE),t("bridge.railing.heightM","height",.1,5,.05,"m",1.05,qt.RAILING),t("bridge.railing.postSpacingM","postSpacing",.2,20,.1,"m",1.5,qt.RAILING),t("bridge.railing.rails","rails",0,8,1,"",2,qt.RAILING)]}static wire(){return[{type:"choice",key:"wire.poles",group:qt.WIRE,label:"poles",hint:"whichEndsStandOnA",choices:[{value:"both",label:"both"},{value:"start",label:"start"},{value:"end",label:"end"},{value:"none",label:"noPoles"}],effective:()=>"both"},{type:"number",key:"wire.diameterM",min:.001,max:.2,step:.001,unit:"m",effective:()=>.008,group:qt.WIRE,label:"strandThickness"},{type:"number",key:"wire.poleHeightM",min:.5,max:100,step:.1,unit:"m",group:qt.WIRE,label:"poleHeight",hint:"emptyHalfAMetreOver"}]}}class vi{static NONE={id:"none",name:"No filter",opticalDensity:0};static SOLAR_VISUAL={id:"solar-visual",name:"Solar filter for the eye (OD 5)",opticalDensity:5,usableWith:["eye","binoculars","telescope"]};static SOLAR_PHOTO={id:"solar-photo",name:"Solar film for a camera (OD 3.8)",opticalDensity:3.8,usableWith:["camera","dslr","phone","telescope"]};static ALL=[vi.NONE,vi.SOLAR_VISUAL,vi.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return vi.ALL.find(e=>e.id===t)??vi.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class n2{constructor(t){this.names=t}name(t){return this.names[t.toLowerCase()]??t}stored(t){const e=t.trim().toLowerCase();for(const[s,i]of Object.entries(this.names))if(i.toLowerCase()===e)return s;return t.trim()}}class io{constructor(t,e,s,i=new n2({}),n,a={}){this.labels=t,this.naming=e,this.said=s,this.tags=i,this.timeWords=n,this.decorParameterTexts=a}entriesFor(t,e,s={}){const i=[];return this.addSummary(i,t),this.addObservation(i,t),this.addObserver(i,t,e),this.addLocation(i,t,e,s.groundElevationM,s.roadGradeDeg??0),this.addDecor(i,t,e,s),s.phenomena===!0&&this.addPhenomena(i,t,e),this.addTemporal(i,t),this.addWeather(i,t,e),this.addSound(i,t,e),i}push(t,e,s,i,n,a="",o={}){n===void 0||n===""||t.push({group:e,field:s,label:i,value:String(n),unit:a,color:o.color,fromSource:o.fromSource===!0})}percent(t){return t===void 0?void 0:`${Math.round(t*100)} %`}rounded(t,e=0){return t===void 0?void 0:String(Number(t.toFixed(e)))}shows(t,e=0){return t!==void 0&&Number(t.toFixed(e))!==0}showsPercent(t){return this.shows(t===void 0?void 0:t*100)}percentShown(t){return this.showsPercent(t)?this.percent(t):void 0}roundedShown(t,e=0){return this.shows(t,e)?this.rounded(t,e):void 0}static DESCRIPTION_WORDS=3;addSummary(t,e){const s=this.said.read(e.event.description)?.trim();if(!s)return;const i=s.split(/\s+/),n=i.length>io.DESCRIPTION_WORDS?`${i.slice(0,io.DESCRIPTION_WORDS).join(" ")}…`:s;this.push(t,"summary","description",this.labels.summaryDescription,n),t[t.length-1].full=s}addObservation(t,e){const s=e.event.tags;this.push(t,"observation","tags",this.labels.tags,s&&s.length>0?s.map(i=>this.tags.name(i)).join(", "):void 0)}filterName(t){return t===vi.SOLAR_VISUAL?this.labels.filterSolarVisual:t===vi.SOLAR_PHOTO?this.labels.filterSolarPhoto:t.name}addObserver(t,e,s){const i=e.observer;this.push(t,"observer","observerId",this.labels.observerId,i?.id),this.push(t,"observer","observerTitle",this.labels.observerTitle,this.said.read(i?.title)),this.push(t,"observer","observerLastName",this.labels.observerLastName,i?.lastName);const n=i?.firstNames;this.push(t,"observer","observerFirstNames",this.labels.observerFirstNames,n&&n.length>0?n.join(", "):void 0);const a=e.instrument;this.push(t,"observer","instrument",this.labels.instrument,this.naming.instrument(a));const o=e.exposure;this.push(t,"observer","exposureSeconds",this.labels.exposure,o===void 0?void 0:o<1?`1/${Math.round(1/o)}`:this.rounded(o,2),"s");const r=pt(e,s);if(r){const c=je.focalLengthMmFor(a,r.fovDeg);c===void 0?this.push(t,"observer","focalLength",this.labels.fieldOfView,this.rounded(r.fovDeg,1),"°"):this.push(t,"observer","focalLength",this.labels.focalLength,this.rounded(c,1),"mm"),this.push(t,"observer","fNumber",this.labels.aperture,this.rounded(r.fNumber??a.fNumber,1)),this.push(t,"observer","focusDistance",this.labels.focusDistance,this.rounded(r.focusDistanceM,1),"m"),this.push(t,"observer","roll",this.labels.roll,this.roundedShown(r.rollDeg),"°");const h=vi.byId(r.filter);h!==vi.NONE&&this.push(t,"observer","filter",this.labels.filter,this.filterName(h))}}degreesMinutesSeconds(t,e,s){if(t===void 0||!Number.isFinite(t))return;const i=Math.round(Math.abs(t)*3600),n=Math.floor(i/3600),a=Math.floor(i%3600/60),o=i%60;return`${n}°${String(a).padStart(2,"0")}′${String(o).padStart(2,"0")}″ ${this.naming.point(t<0?s:e)}`}static WALK_KMH=7;static SPEED_SPAN_MS=1e3;static speedKmhAt(t,e){const s=io.SPEED_SPAN_MS/2,i=Math.max(0,e-s),n=pt(t,i),a=pt(t,i+2*s);if(n?.lat===void 0||n.lng===void 0||a?.lat===void 0||a.lng===void 0)return;const o=(a.lat-n.lat)*111320,r=(a.lng-n.lng)*111320*Math.cos(n.lat*Math.PI/180);return Math.hypot(o,r)/(2*s/1e3)*3.6}addLocation(t,e,s,i,n){const a=e.event.place?.[0];this.push(t,"location","placeName",this.labels.placeName,a?.name);const o=pt(e,s);if(!o)return;this.push(t,"location","lat",this.labels.latitude,this.degreesMinutesSeconds(o.lat,0,180)),this.push(t,"location","lng",this.labels.longitude,this.degreesMinutesSeconds(o.lng,90,270));const r=this.rounded(o.headingDeg);this.push(t,"location","heading",this.labels.heading,r,o.headingDeg===void 0?"°":`° (${this.naming.point(o.headingDeg)})`),this.push(t,"location","pitch",this.labels.pitch,o.pitchDeg===void 0?void 0:this.rounded(o.pitchDeg+n),"°");const c=io.speedKmhAt(e,s);c!==void 0&&c>io.WALK_KMH&&this.push(t,"location","speed",this.labels.speed,Math.round(c),"km/h"),i===void 0?this.push(t,"location","elevation",this.labels.heightAboveGround,this.roundedShown(o.elevationM),"m"):this.push(t,"location","elevation",this.labels.elevation,this.rounded(i+o.elevationM),"m")}addDecor(t,e,s,i){const n=e.decor.find(h=>h.id===i.decorId);if(!n){if(i.decorPicker===!0)for(const h of e.decor)this.push(t,"decor",`decor:${h.id}`,this.decorLabel(h),this.decorKindName(h.kind));return}this.push(t,"decor","decorBase.title",this.labels.decorTitle,this.said.read(n.title));const a=wi(n,s);this.push(t,"decor","decorBase.eastM",this.labels.decorEast,this.rounded(a.eastM,1),"m"),this.push(t,"decor","decorBase.northM",this.labels.decorNorth,this.rounded(a.northM,1),"m"),this.push(t,"decor","decorBase.altitudeM",this.labels.decorAltitude,this.roundedShown(a.altitudeM),"m"),this.push(t,"decor","decorBase.headingDeg",this.labels.decorHeading,this.rounded(a.headingDeg),"°"),Lu(n,s)&&this.push(t,"decor","decorState.lit",this.labels.decorLit,"✓");const o=n.lights?.map(h=>h.id).join()??"",r=o===""?void 0:ou.find(h=>h.create().map(l=>l.id).join()===o);this.push(t,"decor","decorState.lightRig",this.labels.decorLights,r&&this.naming.lightRig(r)),this.push(t,"decor","decorState.observerSide",this.labels.decorObserverSide,this.decorSideName(n.observerSide));const c=qt.of(n);for(const h of(c&&ng.resolve(c,this.decorParameterTexts))?.parameters??[]){const l=ur.read(n,h.key);if(l==null)continue;const d=h.type==="choice"?this.said.read(h.choices.find(f=>f.value===l)?.label)??String(l):l;this.push(t,"decor",`decorParam.${h.key}`,this.said.read(h.summary??h.label)??h.key,typeof d=="boolean"?d?"✓":"":d,h.type==="number"?h.unit:void 0)}}timeText(t){return this.timeWords?vs.describeTime(t,this.timeWords.messages,this.timeWords.locale):oo(t)}addTemporal(t,e){const s=e.event;this.push(t,"temporal","obs-time",this.labels.observationTime,s.time&&this.timeText(s.time)),this.push(t,"temporal","obs-end-time",this.labels.observationEndTime,s.endTime&&this.timeText(s.endTime));const i=Wf(s);this.push(t,"temporal","durationSeconds",this.labels.duration,this.roundedShown(i&&i/1e3,1),"s"),this.push(t,"temporal","timeZone",this.labels.utcOffset,s.timeZone),this.push(t,"temporal","utcOffsetHours",this.labels.utcOffset,this.rounded(s.utcOffsetHours,1),"UTC±h")}addWeather(t,e,s){const i=Qa(e,s),a={fromSource:e.weatherSource!==void 0},o=this.showsPercent(i.cloudCover)||this.showsPercent(i.lowerCloudCover)||this.showsPercent(i.highCloudCover);this.push(t,"weather","cloudCover",this.labels.cloudCover,this.percentShown(i.cloudCover),"",a),this.push(t,"weather","highCloudCover",this.labels.highCloudCover,this.percentShown(i.highCloudCover),"",a),this.push(t,"weather","iceCrystalAlignment",this.labels.iceCrystalAlignment,this.showsPercent(i.highCloudCover)?this.percent(i.iceCrystalAlignment):void 0),this.push(t,"weather","rareIceCrystals",this.labels.rareIceCrystals,this.showsPercent(i.highCloudCover)?this.percent(i.rareIceCrystals):void 0),this.push(t,"weather","cloudDarkness",this.labels.cloudDarkness,o?this.percent(i.cloudDarkness):void 0,"",a),this.push(t,"weather","cloudBase",this.labels.cloudBase,o?this.rounded(i.cloudBaseM):void 0,"m",a);const r=i.precipitationType!=="none"&&this.showsPercent(i.precipitationIntensity);this.push(t,"weather","precipitationType",this.labels.precipitationType,r?this.precipitationName(i.precipitationType):void 0,"",a),this.push(t,"weather","precipitationIntensity",this.labels.precipitationIntensity,r?this.percent(i.precipitationIntensity):void 0,"",a),this.push(t,"weather","windDirection",this.labels.windDirection,this.shows(i.windSpeed,2)?this.rounded(i.windDirectionDeg):void 0,"°",a),this.push(t,"weather","windSpeed",this.labels.windSpeed,this.roundedShown(i.windSpeed,2),"m/s",a),i.storm&&this.push(t,"weather","storm",this.labels.storm,"✓","",a)}addSound(t,e,s){const i=Vf(e,s);i.kind!=="none"&&(this.push(t,"sound","soundKind",this.labels.soundKind,this.soundKindName(i.kind)),this.push(t,"sound","soundVolume",this.labels.soundVolume,this.percentShown(i.volume)),this.push(t,"sound","soundPitch",this.labels.soundPitch,this.roundedShown(i.pitchHz),"Hz"),this.push(t,"sound","soundSrc",this.labels.soundSrc,i.src))}addPhenomena(t,e,s){for(const i of e.timeline.sourceIds){const n=e.timeline.getInterpolatedShapeAt(s,i),a=n?.angular,o=a?`${this.rounded(a.widthDeg,2)} × ${this.rounded(a.heightDeg,2)}°`:void 0;this.push(t,"phenomenon",`shape:${i}`,this.said.read(n?.title)??i,o)}for(const i of e.interpretation?.bodies??[]){const n=i.track.find(o=>o.sizeM?.widthM!==void 0)?.sizeM?.widthM,a=i.model.id??i.model.url?.replace(/^.*\//,"");this.push(t,"phenomenon",`body:${i.id}`,this.said.read(i.title)??i.id,[a,n!==void 0?`${this.rounded(n,2)} m`:void 0].filter(Boolean).join(", "))}}decorLabel(t){return this.said.read(t.title)??this.decorKindName(t.kind)}decorKindName(t){switch(t){case"building":return this.labels.decorBuilding;case"tree":return this.labels.decorTree;case"shrub":return this.labels.decorShrub;case"bridge":return this.labels.decorBridge;case"wire":return this.labels.decorWire;case"crop":return this.labels.decorCrop;case"terrace":return this.labels.decorTerrace;case"mound":return this.labels.decorMound;case"wall":return this.labels.decorWall;case"streetlight":return this.labels.decorStreetlight;case"trafficlight":return this.labels.decorTrafficLight;case"peak":return this.labels.decorPeak;case"crossing":return this.labels.decorCrossing;case"roadsign":return this.labels.decorRoadSign;case"vehicle":return this.labels.decorVehicle;case"aircraft":return this.labels.decorAircraft;default:return this.labels.decorObserver}}decorSideName(t){switch(t){case"front":return this.labels.decorSideFront;case"behind":return this.labels.decorSideBehind;case"left":return this.labels.decorSideLeft;case"right":return this.labels.decorSideRight;case"front-left":return this.labels.decorSideFrontLeft;case"front-right":return this.labels.decorSideFrontRight;case"behind-left":return this.labels.decorSideBehindLeft;case"behind-right":return this.labels.decorSideBehindRight;default:return}}precipitationName(t){switch(t){case"rain":return this.labels.precipitationRain;case"snow":return this.labels.precipitationSnow;case"hail":return this.labels.precipitationHail;default:return this.labels.precipitationNone}}soundKindName(t){switch(t){case"hum":return this.labels.soundHum;case"whistle":return this.labels.soundWhistle;case"rumble":return this.labels.soundRumble;case"crackle":return this.labels.soundCrackle;default:return this.labels.soundNone}}}const a2="Global Meteor Network",o2="https://globalmeteornetwork.org/data/",r2="GFZ, Kp and Hp60 indices",c2="https://kp.gfz.de/",h2="“Thunder” by Jerimee",l2="https://creativecommons.org/licenses/by/3.0/",u2="CC BY 3.0";class Qe{static fill(t,e){t.innerHTML="";const s=d=>t.appendChild(d),i=e.currentTerrainAttribution;i&&s(Qe.text(i));const n=e.currentRoadAttribution;n&&s(Qe.text(n));const a=e.currentWaterAttribution;a&&s(Qe.text(a));const o=e.currentRailwayAttribution;o&&s(Qe.text(o));const r=e.ufoElement.observerMapCredit;r&&!i?.includes(r)&&s(Qe.text(r));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",m=document.createElement("li");d.sourceUrl?m.append(Qe.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):m.textContent=`${d.title}${f} (${d.license})`,s(m)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(Qe.link(d.creditUrl,d.credit)):f.textContent=d.credit,s(f)}if(e.ufoElement.sighting.traces.length>0){const d=new Nr(pn.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(m=>d.read(m.source)).filter(m=>!!m));for(const m of f)s(Qe.text(m))}const c=e.satelliteState;if(c.status==="ready"&&c.credit){const d=document.createElement("li");d.appendChild(Qe.link(c.creditUrl??"",c.credit)),s(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(Qe.link(o2,a2),document.createTextNode(" (CC BY 4.0)")),s(d)}if(e.archivedAuroraShown){const d=document.createElement("li");d.append(Qe.link(c2,r2),document.createTextNode(" (CC BY 4.0)")),s(d)}const h=e.aircraftState;if(h.status==="ready"&&h.shown>0){const d=document.createElement("li");if(d.appendChild(Qe.link(h.creditUrl,h.credit)),s(d),h.trailCredit){const f=document.createElement("li");f.appendChild(Qe.link(h.trailCredit.creditUrl,h.trailCredit.credit)),s(f)}}const l=Qe.text(`${h2} (`);l.append(Qe.link(l2,u2),document.createTextNode(")")),s(l)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const s=document.createElement("a");return s.href=t,s.target="_blank",s.rel="noopener",s.textContent=e,s}}const d2=ke.point("assessment").provide(ke.BUILT_IN,[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async u=>{const{CoverageAssessor:t}=await H(async()=>{const{CoverageAssessor:e}=await import("./CoverageAssessor-BbqRqh0C.js");return{CoverageAssessor:e}},__vite__mapDeps([13,1,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async u=>{const{HynekAssessor:t}=await H(async()=>{const{HynekAssessor:e}=await import("./HynekAssessor-BwjRkQWT.js");return{HynekAssessor:e}},__vite__mapDeps([14,15,1,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})},{id:"ballester-guasp",name:"Ballester-Guasp",credit:"V.-J. Ballester-Olmos & M. Guasp",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Ballester-Guasp.html",create:()=>({about:"observer",assess:async u=>{const{BallesterGuaspAssessor:t}=await H(async()=>{const{BallesterGuaspAssessor:e}=await import("./BallesterGuaspAssessor-DUNQZ9e8.js");return{BallesterGuaspAssessor:e}},__vite__mapDeps([16,17,1,15,13,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async u=>{const{PoherAssessor:t}=await H(async()=>{const{PoherAssessor:e}=await import("./PoherAssessor-Dmro58tC.js");return{PoherAssessor:e}},__vite__mapDeps([18,1,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})}]);class Ym{constructor(t){this.labels=t}async read(t){const e=[],s=new Set;for(const i of d2){let n;try{n=await i.create().assess(t)}catch{continue}for(const o of n.criteria)o.basis===void 0&&!o.unsupported&&s.add(o.id);const a=n.score===void 0?n.verdict===void 0?"":this.verdictName(i.id,n.verdict):`${Math.round(n.score*100)}%`;a!==""&&e.push({group:"assessment",field:i.id,label:this.labels.assessmentNames[i.id]??i.name,value:a,unit:"",fromSource:!1,about:i.create().about,...n.factors?{detail:Ym.factorsText(n.factors)}:{}})}return{entries:e,unanswered:s}}static factorsText(t){const e={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(t).map(([s,i])=>`${e[s]??s} ${i.toFixed(2)}`).join(" × ")}verdictName(t,e){return this.labels.assessmentVerdicts[`${t}.${e}`]??e.toUpperCase()}}class Mo{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,s){const i=t.event.place?.[0],n=t.observerTrack;if(!i)return 0;const a=p=>{const g=n.getInterpolatedPoseAt(Math.max(0,p));if(!g||g.lat===void 0||g.lng===void 0)return;const M=ot(g.lat,g.lng,i.lat,i.lng);return{eastM:M.x,northM:-M.z,heading:g.headingDeg,aboveM:g.elevationM??0,altitudeM:g.altitudeM}},o=a(e-Mo.HALF_SPAN_MS),r=a(e+Mo.HALF_SPAN_MS),c=a(e);if(!o||!r||!c)return 0;const h=Math.hypot(r.eastM-o.eastM,r.northM-o.northM),l=2*Mo.HALF_SPAN_MS/1e3;if(h/l<Mo.MIN_SPEED_MS)return 0;const d=r.altitudeM!==void 0&&o.altitudeM!==void 0?r.altitudeM-o.altitudeM:s.heightAt(r.eastM,r.northM)+r.aboveM-s.heightAt(o.eastM,o.northM)-o.aboveM,f=Math.atan2(d,h)*180/Math.PI;if(c.heading===void 0)return f;const m=Math.atan2(r.eastM-o.eastM,r.northM-o.northM)*180/Math.PI;return f*Math.max(0,Math.cos((c.heading-m)*Math.PI/180))}}const f2=.08,qd=.15,jd=2,m2=2e3;class Zd{context;constructor(t){this.context=t}noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}qs.isLive(this.context)&&qs.unlock(this.context),this.apply()}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}setPaused(t){t!==this.paused&&(this.paused=t,this.apply())}setVoices(t){this.requested=t,this.apply()}dispose(){for(const t of[...this.voices.keys()])this.release(t);qs.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}apply(){const t=this.context;if(!t)return;const e=this.paused?[]:this.requested.filter(i=>i.inside||i.distanceM<m2),s=new Set(e.map(i=>i.id));for(const i of[...this.voices.keys()])s.has(i)||this.release(i);for(const i of e){const n=this.voices.get(i.id)??this.build(t,i.id);this.retarget(t,n,i)}}build(t,e){const s=t.createGain();s.gain.value=0;const i=t.createBiquadFilter();i.type="lowpass",i.connect(s).connect(this.masterOf(t));const n=t.createOscillator();n.type="sawtooth";const a=t.createOscillator();a.type="sine";const o=t.createGain(),r=t.createBiquadFilter();r.type="lowpass",r.frequency.value=900,n.connect(r),a.connect(r),r.connect(o).connect(i);const c=()=>{const b=t.createBufferSource();return b.buffer=this.noise(t),b.loop=!0,b.loopStart=Math.random()*jd*.5,b},h=c(),l=t.createBiquadFilter();l.type="bandpass",l.Q.value=4;const d=t.createGain();h.connect(l).connect(d).connect(i);const f=c(),m=t.createBiquadFilter();m.type="lowpass",m.frequency.value=600;const p=t.createGain();f.connect(m).connect(p).connect(i);const g=c(),M=t.createBiquadFilter();M.type="bandpass",M.frequency.value=1400,M.Q.value=.7;const v=t.createGain();g.connect(M).connect(v).connect(i);const y=[n,a,h,f,g];for(const b of y)b.start();const w={nodes:[s,i,o,r,l,d,m,p,M,v,...y],sources:y,firing:n,crank:a,knock:l,engineGain:o,knockGain:d,roadGain:p,windGain:v,cabin:i,output:s};return this.voices.set(e,w),w}retarget(t,e,{profile:s,state:i,noise:n,inside:a,windowsOpen:o,distanceM:r}){const c=t.currentTime,h=(v,y)=>v.setTargetAtTime(y,c,f2),l=i.rpm/60,d=l*s.cylinders/2,f=Math.min(1,i.rpm/s.shiftUpRpm),m=Math.min(1.5,i.speedMps/30);h(e.firing.frequency,d),h(e.crank.frequency,l),h(e.knock.frequency,d*3),h(e.engineGain.gain,s.engineGain*(.25+.75*i.load)*(.5+.5*f)*.3),h(e.knockGain.gain,s.roughness*(.2+.8*i.load)*.4),h(e.roadGain.gain,s.roadGain*m**1.5*.8);const p=!a||o;h(e.windGain.gain,m**2*(p?.5:.06));const g=a?o?3500:700:8e3/(1+r/60);h(e.cabin.frequency,g);const M=a?.5:Math.min(1,8/Math.max(r,1));h(e.output.gain,M*n)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const s=this.context;s&&(e.output.gain.setTargetAtTime(0,s.currentTime,qd/3),setTimeout(()=>{for(const i of e.sources)try{i.stop()}catch{}for(const i of e.nodes)i.disconnect()},qd*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*jd,t.sampleRate),s=e.getChannelData(0);for(let i=0;i<s.length;i++)s[i]=Math.random()*2-1;return this.noiseBuffer=e,e}}class Hr{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(t){return Hr.BY_KIND[t??"generic"]??Hr.BY_KIND.generic}}class ns{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(t){return ns.ROAD_KINDS.includes(t)}static roadOf(t){return t&&ns.isRoad(t.kind)?t.kind:void 0}static aircraftOf(t){return t&&!ns.isRoad(t.kind)?t.kind:void 0}static transmission(t){const e=ns.insulationDb(t),s=[3,4,5].map(i=>e[i]);return 10**(-(s.reduce((i,n)=>i+n,0)/s.length)/20)}static insulationDb(t){return t?t.windowsOpen===!0?ns.WINDOWS_OPEN_DB:ns.isRoad(t.kind)?ns.ROAD_CLOSED_DB:ns.CANOPIED.includes(t.kind)?ns.CANOPY_DB:ns.FUSELAGE_DB:ns.OPEN_AIR}}class ga{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,s,i){const n=ga.SAMPLE_MS,a=[];for(let c=s;c<=i+n/2;c+=n){const h=e(c-n/2),l=e(c+n/2);if(!h||!l)return;a.push(Math.hypot(l.eastM-h.eastM,l.northM-h.northM)/(n/1e3))}const o=[];let r=1;for(let c=0;c<a.length;c++){const h=a[c],l=(a[Math.min(c+1,a.length-1)]-a[Math.max(c-1,0)])/(2*n/1e3);if(h<ga.STANDING_MPS){r=1,o.push({speedMps:h,rpm:t.idleRpm,load:.1,gear:0});continue}const d=h*3.6,f=M=>d/t.kmhPer1000Rpm[M-1]*1e3;for(;r<t.kmhPer1000Rpm.length&&f(r)>t.shiftUpRpm;)r++;for(;r>1&&f(r)<t.shiftDownRpm;)r--;const m=Math.max(f(r),t.idleRpm*(1+.3*Math.min(1,h/3))),p=.15+.5*Math.min(1,(h/35)**2),g=l>.15?Math.min(1,p+l/2.5):l<-.3?.05:p;o.push({speedMps:h,rpm:m,load:g,gear:r})}return new ga(o,s)}at(t){const e=(t-this.startMs)/ga.SAMPLE_MS,s=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),i=this.samples[s],n=this.samples[Math.min(s+1,this.samples.length-1)],a=Math.min(Math.max(e-s,0),1);return{speedMps:i.speedMps+(n.speedMps-i.speedMps)*a,rpm:i.rpm+(n.rpm-i.rpm)*a,load:i.load+(n.load-i.load)*a,gear:a<.5?i.gear:n.gear}}}class Zc{drives=new Map;at(t,e){const s=[],i=t.event.place?.[0],n=h=>{const l=t.observerTrack.getInterpolatedPoseAt(h),d=l?.lat??i?.lat,f=l?.lng??i?.lng;if(d===void 0||f===void 0||!i)return;const m=ot(d,f,i.lat,i.lng);return{eastM:m.x,northM:-m.z}},a=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),o=t.vehicle,r=ns.roadOf(o);if(o&&r){const h=Hr.of(r),l=this.drive(`observer:${r}`,Zc.trackKey(t),()=>ga.of(h,n,0,a));l&&s.push({id:"observer",profile:h,state:l.at(e),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const c=n(e);for(const h of t.decor){if(!h.engine||!c)continue;const l=Hr.of(h.engine.kind),d=g=>{const M=wi(h,g);return{eastM:M.eastM,northM:M.northM}},f=this.drive(`decor:${h.id}`,Zc.decorKey(h,a),()=>ga.of(l,d,0,a));if(!f)continue;const m=wi(h,e),p=Math.hypot(m.eastM-c.eastM,m.northM-c.northM,m.altitudeM);s.push({id:`decor:${h.id}`,profile:l,state:f.at(e),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return s}drive(t,e,s){const i=this.drives.get(t);if(i&&i.key===e)return i.drive;const n=s();return this.drives.set(t,{key:e,drive:n}),n}static trackKey(t){return t.observerTrack.allKeyframes.map(s=>`${s.t}:${s.pose.lat}:${s.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(s=>`${s.t}:${s.eastM}:${s.northM}`).join(";")}}const Jd=864e5,Qd=4e4;function p2(u){const t=Math.floor(u.getTime()/Jd);return{elapsedMs:u.getTime()-t*Jd,shiftM:{x:t0.unit(t,2654435761)*Qd,z:t0.unit(t,2246822507)*Qd}}}class t0{static unit(t,e){let s=Math.imul(t|0,e)^e;return s=Math.imul(s^s>>>15,739982445),s=Math.imul(s^s>>>12,695872825),s^=s>>>15,(s>>>0)/4294967295*2-1}}function e0(u,t,e,s,i,n,a){const o=s?.lat!==void 0&&s.lng!==void 0&&i?.lat!==void 0&&i.lng!==void 0?ot(i.lat,i.lng,s.lat,s.lng):{x:0,z:0};if(a){const h=t.getInterpolatedWeatherAt(0)??e,l=n===void 0?void 0:h.cloudLayers?.find(m=>m.id===n),d=(l?.windDirectionDeg??h.windDirectionDeg)*Math.PI/180,f=(l?.windSpeed??h.windSpeed)*a.elapsedMs/1e3;o.x+=a.shiftM.x-Math.sin(d)*f,o.z+=a.shiftM.z+Math.cos(d)*f}const r=Math.max(0,u),c=[0,...t.allKeyframes.map(h=>h.t).filter(h=>h>0&&h<r),r];for(let h=1;h<c.length;h++){const l=c[h-1],d=c[h]-l;if(d===0)continue;const f=32;for(let m=0;m<=f;m++){const p=t.getInterpolatedWeatherAt(l+d*m/f)??e,g=n===void 0?void 0:p.cloudLayers?.find(w=>w.id===n),M=(g?.windDirectionDeg??p.windDirectionDeg)*Math.PI/180,v=m===0||m===f?1:m%2===0?2:4,y=(g?.windSpeed??p.windSpeed)*d/1e3/f/3*v;o.x-=Math.sin(M)*y,o.z+=Math.cos(M)*y}}return o}const g2="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",M2=`
|
|
1633
|
+
`}class Ys{static earliestOf(t){return Date.UTC(t.year??0,(t.month??1)-1,t.day??1,t.hour??0,t.minute??0,t.second??0)}static latestOf(t){const e=t.year??9999;return t.month===void 0?Date.UTC(e+1,0,1)-1:t.day===void 0?Date.UTC(e,t.month,1)-1:t.hour===void 0?Date.UTC(e,t.month-1,t.day+1)-1:t.minute===void 0?Date.UTC(e,t.month-1,t.day,t.hour+1)-1:Date.UTC(e,t.month-1,t.day,t.hour,t.minute+1)-1}static boundsOf(t){const[e,s]=t.split("/"),i=e?ai(e):void 0,n=s?ai(s):void 0;if(!(!i||!n))return{min:Ys.timeAt(Ys.earliestOf(i)),max:Ys.timeAt(Ys.latestOf(n)-59999)}}static timeAt(t){const e=new Date(t);return{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate(),hour:e.getUTCHours(),minute:e.getUTCMinutes()}}}class pa{constructor(t){this.rateAt=t}static HISTORY_S=20;sums=[0];at(t){if(!(t>0))return 0;const e=Math.floor(t);for(;this.sums.length<=e+1;){const s=this.sums.length-1;this.sums.push(this.sums[s]+(this.rateAt(s)+this.rateAt(s+1))/2)}return this.sums[e]+(this.sums[e+1]-this.sums[e])*(t-e)}stateAt(t){return{impacts:this.at(t),history:Array.from({length:pa.HISTORY_S},(e,s)=>this.at(t-s-1))}}}class wt{static NONE={ghosts:[],blades:0,bladeAngleRad:0,scattered:0,drops:0,impacts:0,history:[],still:!1,running:0,reachDeg:30,placed:[]};static PHONE=[{scale:-1,share:5e-5,blur:.006,cause:"sensor",tint:[.41,1,.83]},{scale:-.45,share:5e-6,blur:.02,tint:[.7,1,.8]},{scale:.55,share:375e-8,blur:.035,tint:[1,.75,1]}];static CAMERA=[{scale:-1.4,share:3e-4,blur:.045,tint:[1,.8,1]},{scale:-.8,share:4e-4,blur:.02,tint:[.75,1,.8]},{scale:-.35,share:25e-5,blur:.012,tint:[1,.9,.7]},{scale:.3,share:2e-4,blur:.03,tint:[.8,.9,1]},{scale:.65,share:15e-5,blur:.06,tint:[1,.85,1]}];static FILTER={scale:-1,share:.001,blur:.004,cause:"filter"};static WINDOW={scale:1,share:.0016,blur:.002,offset:[0,.006],cause:"glass"};static WINDSCREEN={scale:1,share:.02,blur:.003,offset:[0,.025],cause:"glass"};static OFF_FRAME_REACH_DEG=30;static offFrameShare(t,e,s=wt.OFF_FRAME_REACH_DEG){const i=Math.min(Math.max((t-e)/s,0),1);return 1-i*i*(3-2*i)}static REFERENCE_F_NUMBER=4;static of(t){return t.ghosts?t.ghosts:wt.records(t)?t.category==="phone"?wt.PHONE:wt.CAMERA:[]}static records(t){return t.medium!==void 0||t.category==="camera"||t.category==="dslr"||t.category==="phone"}static optics(t,e,s,i,n=0){const a=wt.of(t);if(a.length===0)return wt.NONE;const o=t.fNumber??wt.REFERENCE_F_NUMBER,r=e??o,c=[...a,...s?.ghosts??[]].map(w=>({...w,blur:w.blur*o/r}));s?.glass==="filter"?c.push({...wt.FILTER}):s?.glass==="window"?c.push({...wt.WINDOW}):s?.glass==="windscreen"&&c.push({...wt.WINDSCREEN});const h=wt.share(s?.condensation),l=wt.share(s?.dirt),d=wt.falling(s),f=d?i?.impacts??0:0,m=d?i?.history??[]:[],p=f-(m[wt.DROP_LIFE_S-1]??0),g=s?.drops!==void 0?wt.share(s.drops):d?Math.min(1,p):0;h>0&&(c.push({scale:1,share:.25*h,blur:.03,cause:"condensation"}),c.push({scale:1,share:.15*h,blur:.12,cause:"condensation"})),l>0&&(c.push({scale:1,share:.03*l,blur:.04,cause:"dirt"}),c.push({scale:1,share:.02*l,blur:.15,cause:"dirt"})),g>0&&c.push({scale:1,share:.12*g,blur:.025,cause:"drops"});const M=c.filter(w=>wt.scatters(w)).reduce((w,b)=>w+b.share,0),v=je.bladesShowing(t,e)>=.5?t.apertureBlades??0:0,y=s?.glass==="window"||s?.glass==="windscreen"?1:.25;return{ghosts:c,blades:v,bladeAngleRad:.3,scattered:Math.min(.9,M),drops:g,impacts:f,history:m,still:s?.drops!==void 0,running:y,reachDeg:s?.reachDeg??wt.OFF_FRAME_REACH_DEG,placed:(s?.placedDrops??[]).map(w=>wt.placedAt(w,n))}}static placedAt(t,e){const s=t.track,i=s.findIndex(r=>r.t>e);if(i===0)return{x:s[0].x,y:s[0].y,radius:t.radius};if(i===-1){const r=s[s.length-1];return{x:r.x,y:r.y,radius:t.radius}}const n=s[i-1],a=s[i],o=(e-n.t)/(a.t-n.t);return{x:n.x+(a.x-n.x)*o,y:n.y+(a.y-n.y)*o,radius:t.radius}}static falling(t){return t?.drops===void 0&&!t?.sheltered}static DROP_LIFE_S=8;static impactRate(t,e,s){const i=wt.dropsFrom(t);if(i===0)return 0;const n=t.precipitationType==="snow"?1:6.5,a=((s?.windFromDeg??0)+180)*Math.PI/180,o=s?.windSpeedMS??0,r=[Math.sin(a)*o,Math.cos(a)*o,-n],c=(s?.headingDeg??0)*Math.PI/180,h=(e==="window"?0:e==="windscreen"?60:s?.pitchDeg??0)*Math.PI/180,l=[Math.sin(c)*Math.cos(h),Math.cos(c)*Math.cos(h),Math.sin(h)],d=Math.hypot(r[0],r[1],r[2]),f=Math.max(0,-(r[0]*l[0]+r[1]*l[1]+r[2]*l[2])/d);return i*.4*(.02+.98*f)}static scatters(t){return t.cause==="condensation"||t.cause==="dirt"||t.cause==="drops"}static dropsFrom(t){if(!t||t.precipitationType==="none"||t.precipitationType==="hail")return 0;const e=wt.share(t.precipitationIntensity);return e===0?0:t.precipitationType==="snow"?.5*e:Math.min(1,.3+.7*e)}static positionOf(t,e){return{x:e.x*t.scale+2*(t.offset?.[0]??0),y:e.y*t.scale+2*(t.offset?.[1]??0)}}static sourceOf(t,e){return{x:(e.x-2*(t.offset?.[0]??0))/t.scale,y:(e.y-2*(t.offset?.[1]??0))/t.scale}}static share(t){return Math.max(0,Math.min(1,t??0))}}const We=Math.PI/180;class tt{constructor(t){this.words=t}static COARSE_DEG=2;static FINE_DEG=.25;findingsOf(t,e){const s=as.strip(e).recording,i=s.interpretation?.mechanism;if(!i)return[];const n=tt.settingOf(t,i.explains);if(!n)return[];const a="interpretation.mechanism";switch(i.kind){case"fixed-in-frame":{const o=tt.missOf(n.samples,tt.fixedPoint(n.samples));return[this.finding(this.words.bestFixed,o,n,{},"established",a)]}case"driven-one-way":{const{miss:o,directionDeg:r}=tt.oneWay(n.samples);return[this.finding(this.words.bestOneWay,o,n,{direction:Math.round(r)},"established",a)]}case"lens-ghost":return this.lensGhostFindings(n,s,a);case"stated-ghost":return this.statedGhostFindings(n,s,a);case"ghost-of":return this.ghostOfFindings(n,s,i.of,a);case"real-object":return[this.realObjectFinding(n,s,i.explains,a)]}}ghostOfFindings(t,e,s,i){const n=e.interpretation?.bodies?.find(l=>l.id===s);if(!n)return[];const a=t.samples.map(l=>{const d=tt.bodyDirectionAt(n,l.t);if(!d)return;const f=d.applyQuaternion(l.frame.inverse);return f.z<0?{x:f.x/-f.z,y:f.y/-f.z}:void 0}),o=wt.of(je.byId(e.instrument)).filter(l=>!wt.scatters(l)).map(l=>l.scale);let r;for(const l of o){const d=a.map(m=>m?{x:l*m.x,y:l*m.y}:void 0),f=tt.missOfTrack(t.samples,d);(!r||f.medianDeg<r.miss.medianDeg)&&(r={miss:f,k:l,track:d})}if(!r)return[];const c=r.track.filter(l=>l!==void 0);let h=0;for(const l of c)for(const d of c)h=Math.max(h,tt.angleDeg(l,d));return[this.finding(this.words.bestGhostOf,r.miss,t,{k:this.number(r.k),ghostTravel:this.number(h)},"established",i)]}realObjectFinding(t,e,s,i){const a=e.interpretation?.bodies?.find(c=>c.explains?.includes(s))?.track[0]?.distanceM??tt.DEFAULT_DISTANCE_M,o=t.samples.map(c=>new D(c.at.x,c.at.y,-1).normalize().applyQuaternion(c.frame.rotation));let r=0;for(let c=0;c<o.length;c++){const h=t.samples.findIndex(l=>l.t>=t.samples[c].t+tt.RATE_WINDOW_MS);if(h<0)break;r=Math.max(r,o[c].angleTo(o[h])/((t.samples[h].t-t.samples[c].t)/1e3))}return{text:this.fill(this.words.bestRealObject,{medianDeg:0,maxDeg:0},t,{distance:Math.round(a),width:this.number(a*t.sizeDeg*We),speed:Math.round(a*r)}),outcome:"holds",against:"established",path:i}}static bodyDirectionAt(t,e){const s=t.track.filter(c=>c.azimuthDeg!==void 0&&c.altitudeDeg!==void 0);if(s.length===0)return;const i=s.findIndex(c=>c.t>e),n=s[i<=0?i===0?0:s.length-1:i-1],a=i<=0?n:s[i],o=a.t>n.t?(e-n.t)/(a.t-n.t):0,r=((a.azimuthDeg-n.azimuthDeg)%360+540)%360-180;return tt.direction(n.azimuthDeg+r*o,n.altitudeDeg+(a.altitudeDeg-n.altitudeDeg)*o)}static DEFAULT_DISTANCE_M=1e3;static RATE_WINDOW_MS=500;static lays(t){return t?.kind==="fixed-in-frame"||t?.kind==="driven-one-way"||t?.kind==="real-object"}bestSceneOf(t,e){const i=as.strip(e).recording.interpretation?.mechanism;if(!tt.lays(i))return;const n=tt.settingOf(t,i.explains);if(!n)return;const a=structuredClone(e);if(i.kind==="fixed-in-frame"||i.kind==="real-object"){const o=a.interpretation??{bodies:[]},r=o.bodies??[],c=r.findIndex(d=>d.explains?.includes(i.explains)),h=c>=0?r[c]:void 0,l=i.kind==="fixed-in-frame"?tt.stillBody(n,i.explains,h):tt.sightLineBody(n,i.explains,h);a.interpretation={...o,bodies:c>=0?r.map((d,f)=>f===c?l:d):[...r,l]}}else{const{track:o}=tt.oneWay(n.samples),r=a.lens?.placedDrops?.[0],c=n.samples[0],h=r?.radius??tt.round(n.sizeDeg/c.frame.fovDeg,4),l=n.samples.map((d,f)=>{const m=Math.tan(d.frame.fovDeg/2*We);return{t:d.t,x:tt.round(.5+o[f].x/(2*m*n.aspect),4),y:tt.round(.5-o[f].y/(2*m),4)}});a.lens={...a.lens,placedDrops:[{radius:h,track:l}]}}return a}static stillBody(t,e,s){const i=tt.fixedPoint(t.samples),n=t.samples[0].t,a=t.samples[t.samples.length-1].t,o=[...new Set([...t.samples.map(r=>r.t),...t.keyframes.map(r=>r.t).filter(r=>r>n&&r<a)])].sort((r,c)=>r-c);return tt.bodyAlong(t,e,s,o,()=>i)}static sightLineBody(t,e,s){return tt.bodyAlong(t,e,s,t.samples.map(i=>i.t),(i,n)=>t.samples[n].at)}static bodyAlong(t,e,s,i,n){const a=i[i.length-1],o=s?.track[0],r=o?.distanceM??tt.DEFAULT_DISTANCE_M,c=o?.sizeM??(()=>{const f=tt.round(r*t.sizeDeg*We,4);return{widthM:f,lengthM:f,heightM:f}})(),h=o?.appearance??{color:"#f4f6f5"},l=i.map((f,m)=>{const p=n(f,m),g=new D(p.x,p.y,-1).normalize().applyQuaternion(tt.frameAt(t.keyframes,f).rotation);return{t:f,...m===0?{present:!0,sizeM:c,appearance:h}:{},azimuthDeg:tt.round((Math.atan2(g.x,-g.z)/We+360)%360,3),altitudeDeg:tt.round(Math.asin(Math.min(1,Math.max(-1,g.y)))/We,3),distanceM:r}}),d=i.length>1?i[i.length-1]-i[i.length-2]:40;return{...s??{id:e,explains:[e],model:{id:"sphere"}},track:[...l,{t:a+d,present:!1}]}}static round(t,e){return Math.round(t*10**e)/10**e}lensGhostFindings(t,e,s){const i=wt.of(je.byId(e.instrument)).filter(c=>!wt.scatters(c)).map(c=>c.scale),n=e.lens?.reachDeg??wt.OFF_FRAME_REACH_DEG,a=c=>{const h=tt.sunTrack(t,c,n);if(!h)return;let l;for(const d of i){const f=tt.missOfTrack(t.samples,h.map(m=>({x:d*m.x,y:d*m.y})));(!l||f.medianDeg<l.miss.medianDeg)&&(l={miss:f,k:d})}return l},o=tt.bestSun(t,!0,a),r=[];if(o?r.push(this.finding(this.words.bestGhost,o.result.miss,t,{...this.sunWords(o.sun),k:this.number(o.result.k)},t.lightingGround,s)):r.push({text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:s}),t.lighting&&(!o||o.result.miss.medianDeg>t.sizeDeg)){const c=tt.bestSun(t,!1,a);c&&(!o||c.result.miss.medianDeg<o.result.miss.medianDeg-1e-6)&&r.push({text:this.fill(this.words.bestGhostNeeds,c.result.miss,t,{...this.sunWords(c.sun),k:this.number(c.result.k)}),outcome:"fails",against:t.lightingGround,path:"lighting"})}return r}statedGhostFindings(t,e,s){const i=e.lens?.reachDeg??wt.OFF_FRAME_REACH_DEG,n=r=>{const c=tt.sunTrack(t,r,i);if(!c)return;const h=tt.linearFit(c,t.samples.map(d=>d.at)),l=c.map(d=>({x:h.k*d.x+h.offset.x,y:h.k*d.y+h.offset.y}));return{miss:tt.missOfTrack(t.samples,l),...h}},a=tt.bestSun(t,!0,n);if(!a)return[{text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:s}];const o=Math.atan(Math.hypot(a.result.offset.x,a.result.offset.y))/We;return[this.finding(this.words.bestStatedGhost,a.result.miss,t,{...this.sunWords(a.sun),k:this.number(a.result.k),offset:this.number(o)},t.lightingGround,s)]}finding(t,e,s,i,n,a){return{text:this.fill(t,e,s,i),outcome:e.medianDeg<=s.sizeDeg?"holds":"fails",against:n,path:a}}fill(t,e,s,i){const n={median:this.number(e.medianDeg),max:this.number(e.maxDeg),size:this.number(s.sizeDeg),travel:this.number(s.travelDeg),...i};return t.replace(/\{(\w+)\}/g,(a,o)=>o in n?String(n[o]):a)}sunWords(t){return{bearing:Math.round(t.bearing),altitude:this.number(t.altitudeDeg)}}number(t){const e=Math.abs(t)<1?2:1;return t.toFixed(e).replace(".",this.words.decimal)}static settingOf(t,e){const{recording:s,provenance:i}=as.strip(t),n=s.observerTrack?.keyframes??[];if(n.length===0)return;const a=je.aspectOf(je.byId(s.instrument)),o=[],r=[];for(const d of s.timeline?.keyframes??[])for(const f of d.shapes??[]){const m=f.shape;if(f.sourceId!==e||!m.aim)continue;const p=tt.frameAt(n,d.t),g=tt.direction(m.aim.azimuthDeg,m.aim.altitudeDeg).applyQuaternion(p.inverse);g.z>=0||(o.push({t:d.t,at:{x:g.x/-g.z,y:g.y/-g.z},frame:p}),m.angular?.widthDeg&&r.push(m.angular.widthDeg))}if(o.length===0)return;r.sort((d,f)=>d-f);let c=0;for(const d of o)for(const f of o)c=Math.max(c,tt.angleDeg(d.at,f.at));const h=n[0].pose,l=h.lat??0;return{samples:o,keyframes:n,sizeDeg:r.length>0?r[Math.floor(r.length/2)]:.5,travelDeg:c,aspect:a,headingDeg:h.headingDeg??0,lighting:s.lighting,lightingGround:as.free(i.at("lighting"))?"supposed":"established",altitudes:{minDeg:-Math.acos(6371e3/(6371e3+Math.max(h.elevationM??0,0)))/We,maxDeg:tt.highestSun(s.time,i.at("time")?.range,l,h.lng??0)}}}static highestSun(t,e,s,i){const[n,a]=(typeof e=="string"?e:t??"").split("/"),o=n?ai(n):void 0,r=a?ai(a):o;if(!o||!r)return 90;const c=Ys.earliestOf(o),h=Ys.latestOf(r),l=864e5;let d=-90;for(let f=Math.floor(c/l)*l;f<=h;f+=l){const m=f+(12-i/15)*36e5;for(let p=-60;p<=60;p+=10)d=Math.max(d,Bn("Sun",new Date(m+p*6e4),{lat:s,lng:i,elevationM:0}).altitudeDeg)}return d}static frameAt(t,e){const s=t.findIndex(l=>l.t>e),i=t[s<=0?s===0?0:t.length-1:s-1],n=s<=0?i:t[s],a=n.t>i.t?(e-i.t)/(n.t-i.t):0,o=(l,d,f)=>(l??f)+((d??l??f)-(l??f))*a,r=(((n.pose.headingDeg??0)-(i.pose.headingDeg??0))%360+540)%360-180,c=(i.pose.headingDeg??0)+r*a,h=new Oa().setFromEuler(new $f(o(i.pose.pitchDeg,n.pose.pitchDeg,0)*We,-c*We,o(i.pose.rollDeg,n.pose.rollDeg,0)*We,"YXZ"));return{rotation:h,inverse:h.clone().invert(),fovDeg:o(i.pose.fovDeg,n.pose.fovDeg,50)}}static direction(t,e){const s=t*We,i=e*We;return new D(Math.sin(s)*Math.cos(i),Math.sin(i),-Math.cos(s)*Math.cos(i))}static angleDeg(t,e){const s=(t.x*e.x+t.y*e.y+1)/Math.sqrt((t.x*t.x+t.y*t.y+1)*(e.x*e.x+e.y*e.y+1));return Math.acos(Math.min(1,Math.max(-1,s)))/We}static missOf(t,e){return tt.missOfTrack(t,t.map(()=>e))}static missOfTrack(t,e){const s=t.map((i,n)=>e[n]?tt.angleDeg(i.at,e[n]):180).sort((i,n)=>i-n);return{medianDeg:s[Math.floor(s.length/2)],maxDeg:s[s.length-1]}}static fixedPoint(t){let e={x:t.reduce((s,i)=>s+i.at.x,0)/t.length,y:t.reduce((s,i)=>s+i.at.y,0)/t.length};for(let s=0;s<100;s++){let i=0,n=0,a=0;for(const o of t){const r=1/Math.max(Math.hypot(o.at.x-e.x,o.at.y-e.y),1e-9);i+=o.at.x*r,n+=o.at.y*r,a+=r}e={x:i/a,y:n/a}}return e}static oneWay(t){let e;for(let s=0;s<360;s+=5){const i={x:Math.sin(s*We),y:Math.cos(s*We)},n={x:i.y,y:-i.x},a=t.map(d=>d.at.x*i.x+d.at.y*i.y),o=t.map(d=>d.at.x*n.x+d.at.y*n.y).sort((d,f)=>d-f),r=o[Math.floor(o.length/2)],h=tt.neverBack(a).map(d=>({x:d*i.x+r*n.x,y:d*i.y+r*n.y})),l=tt.missOfTrack(t,h);(!e||l.medianDeg<e.miss.medianDeg||l.medianDeg===e.miss.medianDeg&&l.maxDeg<e.miss.maxDeg)&&(e={miss:l,directionDeg:s,track:h})}return e}static neverBack(t){const e=[];for(const s of t)for(e.push({sum:s,count:1});e.length>1&&e[e.length-2].sum/e[e.length-2].count>e[e.length-1].sum/e[e.length-1].count;){const i=e.pop();e[e.length-1].sum+=i.sum,e[e.length-1].count+=i.count}return e.flatMap(s=>new Array(s.count).fill(s.sum/s.count))}static sunTrack(t,e,s){const i=tt.direction(t.headingDeg+e.bearing,e.altitudeDeg),n=[];for(const a of t.samples){const o=i.clone().applyQuaternion(a.frame.inverse),r=Math.acos(Math.min(1,Math.max(-1,-o.z)))/We,c=Math.tan(a.frame.fovDeg/2*We),h=Math.atan(c*Math.hypot(1,t.aspect))/We;if(o.z>=0||r>=h+s)return;n.push({x:o.x/-o.z,y:o.y/-o.z})}return n}static linearFit(t,e){const s=t.length,i=h=>({x:h.reduce((l,d)=>l+d.x,0)/s,y:h.reduce((l,d)=>l+d.y,0)/s}),n=i(t),a=i(e);let o=0,r=0;for(let h=0;h<s;h++)o+=(t[h].x-n.x)*(e[h].x-a.x)+(t[h].y-n.y)*(e[h].y-a.y),r+=(t[h].x-n.x)**2+(t[h].y-n.y)**2;const c=r>1e-12?o/r:0;return{k:c,offset:{x:a.x-c*n.x,y:a.y-c*n.y}}}static bestSun(t,e,s){const i=h=>h.altitudeDeg>=t.altitudes.minDeg&&h.altitudeDeg<=t.altitudes.maxDeg&&(!e||!t.lighting||tt.lights(t.lighting,h));let n;const a=h=>{if(!i(h))return;const l=s(h);l&&(!n||l.miss.medianDeg<n.result.miss.medianDeg)&&(n={sun:h,result:l})},{minDeg:o,maxDeg:r}=t.altitudes;for(let h=0;h<360;h+=tt.COARSE_DEG){for(let l=o;l<=r;l+=tt.COARSE_DEG/2)a({bearing:h,altitudeDeg:l});a({bearing:h,altitudeDeg:r})}if(!n)return;const c=n.sun;for(let h=-2;h<=tt.COARSE_DEG;h+=tt.FINE_DEG)for(let l=-2;l<=tt.COARSE_DEG;l+=tt.FINE_DEG)a({bearing:((c.bearing+h)%360+360)%360,altitudeDeg:c.altitudeDeg+l});return n}static lights(t,e){const s=t.sunFromViewDeg,i=s?((e.bearing-s.fromDeg)%360+360)%360:0,n=s?((s.toDeg-s.fromDeg)%360+360)%360:360,a=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return i<=n&&a}}const s2=[{path:"place.locations.0.lat",what:"latitude"},{path:"place.locations.0.lng",what:"longitude"}];class pe{constructor(t){this.words=t,this.bestCases=new tt(t)}bestCases;found=new WeakMap;findingsOf(t,e){const s=as.strip(t),i=as.strip(e).recording,n=[],a=this.timeFinding(s.recording.time,s.provenance.at("time"),i.time);a&&n.push(a);for(const{path:r,what:c}of s2){const h=this.numberFinding(pe.at(s.recording,r),s.provenance.at(r),pe.at(i,r),this.words[c]);h&&n.push({...h,path:r})}const o=s.recording.lighting;if(o&&pe.movesTheSun(s.recording,i)){const r=this.lightingFinding(o,s.provenance.at("lighting"),i);r&&n.push(r)}return n.push(...this.bestCasesOf(t,e)),n}bestCasesOf(t,e){const s=JSON.stringify([e.interpretation?.mechanism,e.lens,e.instrument]),i=this.found.get(e);if(i&&i.account===t&&i.key===s)return i.findings;const n=this.bestCases.findingsOf(t,e);return this.found.set(e,{account:t,key:s,findings:n}),n}static withinInterval(t,e){const[s,i]=e.split("/"),n=s?ai(s):void 0,a=i?ai(i):void 0;if(!(!n&&!a))return!(n&&t.getTime()<Ys.earliestOf(n)||a&&t.getTime()>Ys.latestOf(a))}timeFinding(t,e,s){if(t===void 0||s===void 0||t===s)return;const i=ai(s),n=i?dn(i,0,0):void 0;if(typeof e?.range=="string"&&n){const a=pe.withinInterval(n,e.range);if(a===void 0)return;const o=a?this.words.timeWithin:this.words.timeOutside;return{text:pe.fill(o,{time:s,range:e.range}),outcome:a?"holds":"fails",against:"established",path:"time"}}if(!as.free(e))return{text:pe.fill(this.words.timeChanged,{from:t,time:s}),outcome:"fails",against:"established",path:"time"}}numberFinding(t,e,s,i){if(!(typeof t!="number"||typeof s!="number"||Math.abs(t-s)<1e-9)){if(Array.isArray(e?.range)){const[n,a]=e.range,o=(n===null||s>=n)&&(a===null||s<=a);return{text:pe.fill(o?this.words.valueWithin:this.words.valueOutside,{what:i,value:s,bounds:this.boundsOf(e.range)}),outcome:o?"holds":"fails",against:"established"}}if(!as.free(e))return{text:pe.fill(this.words.valueChanged,{what:i,from:t,value:s}),outcome:"fails",against:"established"}}}static movesTheSun(t,e){const s=a=>a.observerTrack?.keyframes?.[0]?.pose,i=s(t),n=s(e);return t.time!==e.time||t.utcOffsetHours!==e.utcOffsetHours||JSON.stringify(t.place)!==JSON.stringify(e.place)||i?.lat!==n?.lat||i?.lng!==n?.lng||i?.headingDeg!==n?.headingDeg}lightingFinding(t,e,s){const i=s.time?ai(s.time):void 0,n=i?pe.sunOf(i,s):void 0;if(!n)return;const{bearing:a}=n,{fromDeg:o,toDeg:r}=t.sunFromViewDeg??{fromDeg:0,toDeg:360},{minDeg:c,maxDeg:h}=t.sunAltitudeDeg??{minDeg:-90,maxDeg:90},l=pe.lights(t,n),d=as.free(e)?"supposed":"established",f=m=>Math.round(m);return{text:pe.fill(l?this.words.lightingHolds:this.words.lightingFails,{bearing:f(a),altitude:f(n.altitudeDeg),from:o,to:r,altitudes:t.sunAltitudeDeg?pe.fill(this.words.altitudes,{min:c,max:h}):""}),outcome:l?"holds":"fails",against:d,path:"lighting",...e?.rationale?{rationale:e.rationale}:{}}}static standOf(t){const e=as.strip(t).recording,s=e.observerTrack?.keyframes?.[0]?.pose,i=e.place?.locations?.[0],n=s?.lat??i?.lat,a=s?.lng??i?.lng;if(!(n===void 0||a===void 0||s?.headingDeg===void 0))return{lat:n,lng:a,elevationM:s.elevationM??0,headingDeg:s.headingDeg,utcOffsetHours:e.utcOffsetHours}}static sunOf(t,e){const s=pe.standOf(e);return s?pe.sunFrom(t,s):void 0}static sunFrom(t,e){if(t.hour===void 0)return;const s=dn(t,e.lng,e.utcOffsetHours);if(!s)return;const i=Bn("Sun",s,e);return{bearing:((i.azimuthDeg-e.headingDeg)%360+360)%360,altitudeDeg:i.altitudeDeg}}static lights(t,e){const s=t.sunFromViewDeg?pe.onArc(e.bearing,t.sunFromViewDeg.fromDeg,t.sunFromViewDeg.toDeg):!0,i=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return s&&i}static nearestLit(t,e,s){const i=l=>({...e,hour:Math.floor(l/60),minute:l%60,second:void 0,raw:void 0}),n=pe.standOf(s);if(!n)return;const a=l=>{const d=pe.sunFrom(i(l),n);return d!==void 0&&pe.lights(t,d)};if(e.hour===void 0)return;const o=e.hour*60+(e.minute??0);if(a(o))return e;const r=5;let c;for(let l=0;l<1440;l+=r)a(l)&&(c===void 0||Math.abs(l-o)<Math.abs(c-o))&&(c=l);if(c===void 0)return;const h=o<c?-1:1;for(;c+h>=0&&c+h<1440&&a(c+h)&&Math.abs(c+h-o)<Math.abs(c-o);)c+=h;return i(c)}static onArc(t,e,s){const i=((s-e)%360+360)%360;return((t-e)%360+360)%360<=i}static at(t,e){return e.split(".").reduce((s,i)=>s?.[i],t)}boundsOf([t,e]){return t===null?pe.fill(this.words.atMost,{max:e??""}):e===null?pe.fill(this.words.atLeast,{min:t}):pe.fill(this.words.between,{min:t,max:e})}static fill(t,e){return t.replace(/\{(\w+)\}/g,(s,i)=>i in e?String(e[i]):s)}}const jw=Sn.catalog({en:()=>H(()=>import("./ReadingCheckTexts_en-C5qzU8K7.js"),[],import.meta.url).then(u=>u.readingCheckTexts_en),fr:()=>H(()=>import("./ReadingCheckTexts_fr-COtovvqc.js"),[],import.meta.url).then(u=>u.readingCheckTexts_fr),es:()=>H(()=>import("./ReadingCheckTexts_es-DdhtmSew.js"),[],import.meta.url).then(u=>u.readingCheckTexts_es),it:()=>H(()=>import("./ReadingCheckTexts_it-Bz32XGh6.js"),[],import.meta.url).then(u=>u.readingCheckTexts_it)});class Zw{static of(t){if(!(!t||t.length===0))return t.some(e=>e.outcome==="fails"&&e.against!=="supposed")?"incompatible":t.some(e=>e.outcome!=="holds")?"unsettled":"compatible"}}class vs{constructor(t,e,s,i="en"){this.parts=t,this.messages=e,this.onChange=s,this.locale=i,e&&this.setMessages(e),t.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),t.picker.addEventListener("change",()=>this.writeFromPicker()),t.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),t.text.addEventListener("blur",()=>this.validate()),t.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";setBounds(t){this.bounds=t;const{picker:e}=this.parts;e.min=t?vs.pickerValueOf(t.min):"",e.max=t?vs.pickerValueOf(t.max):""}bounds;bounded(t){if(!this.bounds)return t;const e=Ys.latestOf(t)<Ys.earliestOf(this.bounds.min)?this.bounds.min:Ys.earliestOf(t)>Ys.earliestOf(this.bounds.max)?this.bounds.max:t;return this.bounds.adjust?.(e)??e}get isPrecise(){return this.precise}setMessages(t,e=this.locale){this.messages=t,this.locale=e,t.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=t.edtfPlaceholder),this.parts.mode.title=t.edtfModeTitle,this.parts.mode.setAttribute("aria-label",t.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(t){this.precise=t,this.parts.picker.hidden=!t,this.parts.text.hidden=t,this.parts.mode.textContent=(t?this.messages?.datePrecise:this.messages?.dateEdtf)??"",this.parts.mode.setAttribute("aria-pressed",String(!t)),this.parts.help&&(this.parts.help.hidden=t),this.showDeduction()}set(t){const{text:e,picker:s}=this.parts;e.value=t?oo(t):"",s.type!=="date"&&(s.step=vs.stepFor(t)),s.value=s.type==="date"?vs.pickerDateOf(t):vs.pickerValueOf(t),e.setCustomValidity(""),e.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...t){return t.every(e=>e===void 0||vs.isPickable(e)&&vs.qualifierOf(oo(e))==="")}static opensPreciseDate(...t){return t.every(e=>e===void 0||vs.isFullDate(e)&&vs.qualifierOf(oo(e))==="")}static isFullDate(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0}static pickerDateOf(t){if(!vs.isFullDate(t))return"";const e=(s,i=2)=>String(s).padStart(i,"0");return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}`}static isPickable(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0&&t.hour!==void 0&&t.minute!==void 0}static pickerValueOf(t){if(!vs.isPickable(t))return"";const e=(i,n=2)=>String(i).padStart(n,"0"),s=t.second?`:${e(t.second)}`:"";return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}T${e(t.hour)}:${e(t.minute)}${s}`}static stepFor(t){return t?.second?"1":"60"}static qualifierOf(t){const e=/[?%]/.test(t),s=/[~%]/.test(t);return e&&s?"%":e?"?":s?"~":""}describe(t){return this.messages?vs.describeTime(t,this.messages,this.locale):""}static describeTime(t,e,s){const i=oo(t),n=vs.qualifierOf(i),a=h=>String(h).padStart(2,"0"),o=[];if(t.season!==void 0){const h={spring:e.timeSeasonSpring,summer:e.timeSeasonSummer,autumn:e.timeSeasonAutumn,winter:e.timeSeasonWinter}[t.season];o.push(t.year!==void 0?`${h} ${t.year}`:h)}else if(t.year!==void 0){const h=t.day!==void 0?{...t.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:t.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},l=new Date(Date.UTC(t.year,(t.month??1)-1,t.day??1));o.push(new Intl.DateTimeFormat(s,{...h,timeZone:"UTC"}).format(l))}t.hour!==void 0&&o.push(`${a(t.hour)}:${a(t.minute??0)}${t.second!==void 0?`:${a(t.second)}`:""}`);const r=o.join(", "),c=n==="~"?e.timeQualifierApproximate:n==="?"?e.timeQualifierUncertain:n==="%"?e.timeQualifierBoth:"";return c?`${r} — ${c.toLowerCase()}`:r}setHint(t){this.hint=t,this.showDeduction()}showDeduction(){const{text:t}=this.parts,e=t.value.trim();if(this.precise||e===""){t.title=this.hint;return}const s=ai(e);t.title=s?`→ ${this.describe(s)}`:this.messages?.edtfInvalid??""}readText(){const t=this.parts.text.value.trim();if(t===""){this.clean(),this.onChange(void 0);return}const e=ai(t);if(!e)return;this.clean();const s=this.bounded(e);s!==e&&this.set(s),this.onChange(s)}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:t,text:e}=this.parts;t.value===""&&t.validity.badInput||(e.value=t.value===""?"":t.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:t}=this.parts,e=t.value.trim();e===""||ai(e)||(t.setCustomValidity(this.messages?.edtfInvalid??""),t.classList.add("invalid"))}}const $d="#ff2200",Xd="#00ff44",ta="#ffffff",tc="#ffa500",Ua="#ff0000",i2="#2244ff",ou=[{id:"airliner",name:"Airliner",kinds:["aircraft"],referenceSizeM:{widthM:34,heightM:12,lengthM:36},create:()=>[{id:"nav-port",offsetM:{x:-17,y:0,z:0},color:$d,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:Xd,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:ta,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:Ua,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:Ua,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:ta,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:ta,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01,phase:.08}}]},{id:"helicopter",name:"Helicopter",kinds:["aircraft"],referenceSizeM:{widthM:10,heightM:4,lengthM:14},create:()=>[{id:"nav-port",offsetM:{x:-5,y:0,z:0},color:$d,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:Xd,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:ta,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:Ua,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:ta,intensity:15,pattern:{kind:"flash",perMinute:75,dutyCycle:.015}}]},{id:"car-headlights",name:"Car, headlights on",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"head-left",offsetM:{x:-.7,y:.6,z:2},color:ta,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:ta,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:Ua,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:Ua,pattern:{kind:"steady"}}]},{id:"car-hazards",name:"Car, hazard flashers",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"hazard-front-left",offsetM:{x:-.8,y:.6,z:2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:tc,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}}]},{id:"emergency-beacons",name:"Emergency vehicle beacons",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"beacon-blue",offsetM:{x:-.4,y:1.6,z:0},color:i2,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:Ua,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>at.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>at.pedestrianLights(0)},{id:"streetlamp",name:"Streetlamp",kinds:["streetlight"],referenceSizeM:{widthM:1,heightM:5,lengthM:1},create:()=>[{id:"lamp",offsetM:{x:0,y:5,z:0},color:"#ffd9a0",intensity:2,pattern:{kind:"steady"}}]}];class jc{static forKind(t){return ou.filter(e=>e.kinds.includes(t))}static byId(t){return ou.find(e=>e.id===t)}}class at{static CYCLE_S=90;static GREEN_S=41;static AMBER_S=3;static PEDESTRIAN_DELAY_S=2;static PEDESTRIAN_GREEN_S=30;static VEHICLE_INTENSITY=3;static PEDESTRIAN_INTENSITY=1.5;static LENS_RADIUS_M=.1;static BEAM_DEG=30;static VEHICLE_HEAD_Y_M=2.9;static PEDESTRIAN_HEAD_Y_M=2.6;static LENS_SPACING_M=.3;static LENS_FRONT_M=.13;static RED="#ff1e00";static AMBER="#ffa200";static GREEN="#00ff8c";static phaseOf(t){const e=(t%180+180)%180;return e>=45&&e<135?1:0}static vehicleLights(t){const e=t*at.CYCLE_S/2,s=at.VEHICLE_HEAD_Y_M,i=at.LENS_SPACING_M;return[at.lamp("red",at.RED,s+i,e+at.GREEN_S+at.AMBER_S,at.CYCLE_S-at.GREEN_S-at.AMBER_S,at.VEHICLE_INTENSITY),at.lamp("amber",at.AMBER,s,e+at.GREEN_S,at.AMBER_S,at.VEHICLE_INTENSITY),at.lamp("green",at.GREEN,s-i,e,at.GREEN_S,at.VEHICLE_INTENSITY)]}static pedestrianLights(t){const e=t*at.CYCLE_S/2+at.GREEN_S+at.AMBER_S+at.PEDESTRIAN_DELAY_S,s=at.PEDESTRIAN_HEAD_Y_M,i=at.LENS_SPACING_M/2;return[at.lamp("ped-red",at.RED,s+i,e+at.PEDESTRIAN_GREEN_S,at.CYCLE_S-at.PEDESTRIAN_GREEN_S,at.PEDESTRIAN_INTENSITY),at.lamp("ped-green",at.GREEN,s-i,e,at.PEDESTRIAN_GREEN_S,at.PEDESTRIAN_INTENSITY)]}static isPedestrian(t){return t?.some(e=>e.id==="ped-green")??!1}static figureOf(t){return t.id==="ped-red"?"standing":t.id==="ped-green"?"walking":void 0}static lamp(t,e,s,i,n,a){const o=at.CYCLE_S,r=Math.round(((1-i/o)%1+1)%1*1e6)/1e6;return{id:t,color:e,intensity:a,radiusM:at.LENS_RADIUS_M,beamDeg:at.BEAM_DEG,offsetM:{x:0,y:s,z:-.13},pattern:{kind:"flash",perMinute:60/o,dutyCycle:Math.round(n/o*1e6)/1e6,...r?{phase:r}:{}}}}}class yr{static of(t,e){const s=yr.drawnAsModel(t);return{color:e?.color??!s,lit:e?.lit??yr.litByDefault(t.kind,s),headlights:t.kind==="vehicle",lights:(e?.lights??!0)&&yr.rigsFor(t.kind,e).length>0,windows:!s&&am(t.kind),floors:!s&&t.kind==="building",observerSide:Bo(t.kind)}}static rigsFor(t,e){return jc.forKind(t).filter(s=>e?.lightRigs===void 0||e.lightRigs.includes(s.id))}static drawnAsModel(t){return Bc(t)!==void 0&&!(t.observerSide!==void 0&&Bo(t.kind))}static litByDefault(t,e){return t==="streetlight"||t==="vehicle"&&!e}}class qt{static sideLabel(t){return qt.SIDE_LABELS[t]}static SIDE_LABELS={front:"front",behind:"behind",left:"left",right:"right","front-left":"frontLeft","front-right":"frontRight","behind-left":"behindLeft","behind-right":"behindRight"};static WINDOWS="windows";static BUILDING="building";static BRIDGE="bridge";static RAILING="railing";static WIRE="overheadLine";static together(t,e){return`${t} ${e}`}static of(t,e){const s=[],i=yr.drawnAsModel(t);if(!i&&t.kind==="building"&&s.push(...qt.floors(),...qt.walls(),...qt.roof()),!i&&am(t.kind)&&s.push(...qt.windows(t.kind)),t.kind==="vehicle"&&s.push(...qt.engine()),t.kind==="observer"&&s.push(...qt.observerRecording()),t.kind==="aircraft"&&s.push(...qt.aircraftSound(e)),t.kind==="bridge"&&s.push(...qt.bridge()),t.kind==="wire"&&s.push(...qt.wire()),e?.parameters&&s.push(...e.parameters.map(n=>({...n,key:`modelParameters.${n.key}`}))),s.length!==0)return{kind:`decor-${t.kind}`,title:"properties",parameters:s}}static floors(){const t=e=>ur.read(e,"floors")??Vc;return[{type:"number",key:"floors",min:0,max:20,step:1,effective:()=>Vc,label:"floors",hint:"upperStoriesAboveTheGround",group:qt.BUILDING},{type:"number",key:"occupiedFloor",min:0,max:20,step:1,effective:()=>0,bounds:e=>({max:t(e)}),label:"occupiedFloor",hint:"theFloorTheWitnessIs",group:qt.BUILDING}]}static walls(){const t="walls";return[{type:"colour",key:"facade.color",group:t,fallback:"#d3cab8",label:"wallColour",hint:"theColourOfTheWalls"},{type:"choice",key:"facade.openings",group:t,label:"facade",empty:"aHouseS",hint:"aHouseSAWindowEvery",choices:[{value:"tall",label:"oldBuilding"},{value:"lancet",label:"church"},{value:"plain",label:"bareWall"},{value:"none",label:"noFacade"}]}]}static roof(){const t="roof";return[{type:"choice",key:"roof.shape",group:t,label:"roof",empty:"flat",hint:"flatTheBoxTwoSlopes",choices:[{value:"flat",label:"flat"},{value:"gable",label:"twoSlopes"},{value:"hip",label:"fourSlopes"},{value:"dome",label:"dome"}]},{type:"number",key:"roof.riseM",min:0,max:15,step:.1,unit:"m",group:t,effective:()=>3,label:"rise",hint:"howFarTheRidgeStands",visibleWhen:s=>["gable","hip","dome"].includes(String(ur.read(s,"roof.shape")))},{type:"choice",key:"roof.ridge",group:t,required:!1,label:"ridgeAlong",empty:"theWidth",choices:[{value:"width",label:"theWidth"},{value:"depth",label:"theDepth"}],visibleWhen:s=>ur.read(s,"roof.shape")==="gable"},{type:"colour",key:"roof.color",group:t,fallback:"#7a5a4a",label:"roofColour"}]}static windows(t){return ag(t).map(e=>({type:"number",key:`windows.${e}`,step:5,unit:"%",min:rg(t,e)?0:og,max:100,label:qt.SIDE_LABELS[e],summary:qt.together(qt.WINDOWS,qt.SIDE_LABELS[e]),hint:"opacityOfTheWindowOn",group:qt.WINDOWS}))}static engine(){const t="engineSound";return[{type:"choice",key:"engine.kind",group:t,label:"engine",hint:"whetherTheVehicleIsHeard",empty:"silentParked",choices:[{value:"car",label:"car"},{value:"van",label:"van"},{value:"truck",label:"truck"},{value:"motorcycle",label:"motorcycle"},{value:"generic",label:"unknown"}]},{type:"number",key:"engine.noise",min:.1,max:3,step:.1,group:t,effective:()=>1,label:"loudness",hint:"againstAnOrdinaryOneOf",visibleWhen:e=>ur.read(e,"engine.kind")!==void 0||e.engine!==void 0}]}static observerRecording(){return[{type:"text",key:"sightingUrl",placeholder:"https://…/sighting.json",label:"theirOwnRecordingURL"}]}static aircraftSound(t){return[{type:"choice",key:"aircraftSound",group:"sound",label:"noiseInFlight",hint:"whatItSoundsLikeWhile",empty:t?.sound==="silent"?"silentAsTheModel":"asTheModel",choices:[{value:"airliner-narrow",label:"aircraftNarrowBodyAirliner"},{value:"airliner-wide",label:"aircraftWideBodyAirliner"},{value:"airliner-supersonic",label:"aircraftSupersonicAirliner"},{value:"regional-jet",label:"aircraftRegionalJet"},{value:"regional-turboprop",label:"aircraftTurboprop"},{value:"business-jet",label:"aircraftBusinessJet"},{value:"light-piston",label:"aircraftLightPistonAircraft"},{value:"piston-heavy",label:"aircraftHeavyPistonAircraft"},{value:"helicopter-light",label:"aircraftLightHelicopter"},{value:"helicopter-medium",label:"aircraftMediumHelicopter"},{value:"helicopter-heavy",label:"aircraftHeavyHelicopter"},{value:"military-jet",label:"aircraftMilitaryJet"},{value:"ultralight",label:"aircraftUltralight"},{value:"unmanned",label:"aircraftDrone"},{value:"glider",label:"aircraftGlider"},{value:"silent",label:"aircraftSilent"}]}]}static bridge(){const t=(e,s,i,n,a,o,r,c,h)=>({type:"number",key:e,label:s,min:i,max:n,step:a,unit:o,group:c,hint:h,effective:r===void 0?void 0:()=>r});return[t("bridge.spanM","span",.1,5e3,.1,"m",void 0,qt.BRIDGE,"metresOfOpenSpanUnder"),t("bridge.deckThicknessM","deckThickness",.1,20,.1,"m",1.2,qt.BRIDGE),t("bridge.railing.heightM","height",.1,5,.05,"m",1.05,qt.RAILING),t("bridge.railing.postSpacingM","postSpacing",.2,20,.1,"m",1.5,qt.RAILING),t("bridge.railing.rails","rails",0,8,1,"",2,qt.RAILING)]}static wire(){return[{type:"choice",key:"wire.poles",group:qt.WIRE,label:"poles",hint:"whichEndsStandOnA",choices:[{value:"both",label:"both"},{value:"start",label:"start"},{value:"end",label:"end"},{value:"none",label:"noPoles"}],effective:()=>"both"},{type:"number",key:"wire.diameterM",min:.001,max:.2,step:.001,unit:"m",effective:()=>.008,group:qt.WIRE,label:"strandThickness"},{type:"number",key:"wire.poleHeightM",min:.5,max:100,step:.1,unit:"m",group:qt.WIRE,label:"poleHeight",hint:"emptyHalfAMetreOver"}]}}class vi{static NONE={id:"none",name:"No filter",opticalDensity:0};static SOLAR_VISUAL={id:"solar-visual",name:"Solar filter for the eye (OD 5)",opticalDensity:5,usableWith:["eye","binoculars","telescope"]};static SOLAR_PHOTO={id:"solar-photo",name:"Solar film for a camera (OD 3.8)",opticalDensity:3.8,usableWith:["camera","dslr","phone","telescope"]};static ALL=[vi.NONE,vi.SOLAR_VISUAL,vi.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return vi.ALL.find(e=>e.id===t)??vi.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class n2{constructor(t){this.names=t}name(t){return this.names[t.toLowerCase()]??t}stored(t){const e=t.trim().toLowerCase();for(const[s,i]of Object.entries(this.names))if(i.toLowerCase()===e)return s;return t.trim()}}class io{constructor(t,e,s,i=new n2({}),n,a={}){this.labels=t,this.naming=e,this.said=s,this.tags=i,this.timeWords=n,this.decorParameterTexts=a}entriesFor(t,e,s={}){const i=[];return this.addSummary(i,t),this.addObservation(i,t),this.addObserver(i,t,e),this.addLocation(i,t,e,s.groundElevationM,s.roadGradeDeg??0),this.addDecor(i,t,e,s),s.phenomena===!0&&this.addPhenomena(i,t,e),this.addTemporal(i,t),this.addWeather(i,t,e),this.addSound(i,t,e),i}push(t,e,s,i,n,a="",o={}){n===void 0||n===""||t.push({group:e,field:s,label:i,value:String(n),unit:a,color:o.color,fromSource:o.fromSource===!0})}percent(t){return t===void 0?void 0:`${Math.round(t*100)} %`}rounded(t,e=0){return t===void 0?void 0:String(Number(t.toFixed(e)))}shows(t,e=0){return t!==void 0&&Number(t.toFixed(e))!==0}showsPercent(t){return this.shows(t===void 0?void 0:t*100)}percentShown(t){return this.showsPercent(t)?this.percent(t):void 0}roundedShown(t,e=0){return this.shows(t,e)?this.rounded(t,e):void 0}static DESCRIPTION_WORDS=3;addSummary(t,e){const s=this.said.read(e.event.description)?.trim();if(!s)return;const i=s.split(/\s+/),n=i.length>io.DESCRIPTION_WORDS?`${i.slice(0,io.DESCRIPTION_WORDS).join(" ")}…`:s;this.push(t,"summary","description",this.labels.summaryDescription,n),t[t.length-1].full=s}addObservation(t,e){const s=e.event.tags;this.push(t,"observation","tags",this.labels.tags,s&&s.length>0?s.map(i=>this.tags.name(i)).join(", "):void 0)}filterName(t){return t===vi.SOLAR_VISUAL?this.labels.filterSolarVisual:t===vi.SOLAR_PHOTO?this.labels.filterSolarPhoto:t.name}addObserver(t,e,s){const i=e.observer;this.push(t,"observer","observerId",this.labels.observerId,i?.id),this.push(t,"observer","observerTitle",this.labels.observerTitle,this.said.read(i?.title)),this.push(t,"observer","observerLastName",this.labels.observerLastName,i?.lastName);const n=i?.firstNames;this.push(t,"observer","observerFirstNames",this.labels.observerFirstNames,n&&n.length>0?n.join(", "):void 0);const a=e.instrument;this.push(t,"observer","instrument",this.labels.instrument,this.naming.instrument(a));const o=e.exposure;this.push(t,"observer","exposureSeconds",this.labels.exposure,o===void 0?void 0:o<1?`1/${Math.round(1/o)}`:this.rounded(o,2),"s");const r=pt(e,s);if(r){const c=je.focalLengthMmFor(a,r.fovDeg);c===void 0?this.push(t,"observer","focalLength",this.labels.fieldOfView,this.rounded(r.fovDeg,1),"°"):this.push(t,"observer","focalLength",this.labels.focalLength,this.rounded(c,1),"mm"),this.push(t,"observer","fNumber",this.labels.aperture,this.rounded(r.fNumber??a.fNumber,1)),this.push(t,"observer","focusDistance",this.labels.focusDistance,this.rounded(r.focusDistanceM,1),"m"),this.push(t,"observer","roll",this.labels.roll,this.roundedShown(r.rollDeg),"°");const h=vi.byId(r.filter);h!==vi.NONE&&this.push(t,"observer","filter",this.labels.filter,this.filterName(h))}}degreesMinutesSeconds(t,e,s){if(t===void 0||!Number.isFinite(t))return;const i=Math.round(Math.abs(t)*3600),n=Math.floor(i/3600),a=Math.floor(i%3600/60),o=i%60;return`${n}°${String(a).padStart(2,"0")}′${String(o).padStart(2,"0")}″ ${this.naming.point(t<0?s:e)}`}static WALK_KMH=7;static SPEED_SPAN_MS=1e3;static speedKmhAt(t,e){const s=io.SPEED_SPAN_MS/2,i=Math.max(0,e-s),n=pt(t,i),a=pt(t,i+2*s);if(n?.lat===void 0||n.lng===void 0||a?.lat===void 0||a.lng===void 0)return;const o=(a.lat-n.lat)*111320,r=(a.lng-n.lng)*111320*Math.cos(n.lat*Math.PI/180);return Math.hypot(o,r)/(2*s/1e3)*3.6}addLocation(t,e,s,i,n){const a=e.event.place?.[0];this.push(t,"location","placeName",this.labels.placeName,a?.name);const o=pt(e,s);if(!o)return;this.push(t,"location","lat",this.labels.latitude,this.degreesMinutesSeconds(o.lat,0,180)),this.push(t,"location","lng",this.labels.longitude,this.degreesMinutesSeconds(o.lng,90,270));const r=this.rounded(o.headingDeg);this.push(t,"location","heading",this.labels.heading,r,o.headingDeg===void 0?"°":`° (${this.naming.point(o.headingDeg)})`),this.push(t,"location","pitch",this.labels.pitch,o.pitchDeg===void 0?void 0:this.rounded(o.pitchDeg+n),"°");const c=io.speedKmhAt(e,s);c!==void 0&&c>io.WALK_KMH&&this.push(t,"location","speed",this.labels.speed,Math.round(c),"km/h"),i===void 0?this.push(t,"location","elevation",this.labels.heightAboveGround,this.roundedShown(o.elevationM),"m"):this.push(t,"location","elevation",this.labels.elevation,this.rounded(i+o.elevationM),"m")}addDecor(t,e,s,i){const n=e.decor.find(h=>h.id===i.decorId);if(!n){if(i.decorPicker===!0)for(const h of e.decor)this.push(t,"decor",`decor:${h.id}`,this.decorLabel(h),this.decorKindName(h.kind));return}this.push(t,"decor","decorBase.title",this.labels.decorTitle,this.said.read(n.title));const a=wi(n,s);this.push(t,"decor","decorBase.eastM",this.labels.decorEast,this.rounded(a.eastM,1),"m"),this.push(t,"decor","decorBase.northM",this.labels.decorNorth,this.rounded(a.northM,1),"m"),this.push(t,"decor","decorBase.altitudeM",this.labels.decorAltitude,this.roundedShown(a.altitudeM),"m"),this.push(t,"decor","decorBase.headingDeg",this.labels.decorHeading,this.rounded(a.headingDeg),"°"),Lu(n,s)&&this.push(t,"decor","decorState.lit",this.labels.decorLit,"✓");const o=n.lights?.map(h=>h.id).join()??"",r=o===""?void 0:ou.find(h=>h.create().map(l=>l.id).join()===o);this.push(t,"decor","decorState.lightRig",this.labels.decorLights,r&&this.naming.lightRig(r)),this.push(t,"decor","decorState.observerSide",this.labels.decorObserverSide,this.decorSideName(n.observerSide));const c=qt.of(n);for(const h of(c&&ng.resolve(c,this.decorParameterTexts))?.parameters??[]){const l=ur.read(n,h.key);if(l==null)continue;const d=h.type==="choice"?this.said.read(h.choices.find(f=>f.value===l)?.label)??String(l):l;this.push(t,"decor",`decorParam.${h.key}`,this.said.read(h.summary??h.label)??h.key,typeof d=="boolean"?d?"✓":"":d,h.type==="number"?h.unit:void 0)}}timeText(t){return this.timeWords?vs.describeTime(t,this.timeWords.messages,this.timeWords.locale):oo(t)}addTemporal(t,e){const s=e.event;this.push(t,"temporal","obs-time",this.labels.observationTime,s.time&&this.timeText(s.time)),this.push(t,"temporal","obs-end-time",this.labels.observationEndTime,s.endTime&&this.timeText(s.endTime));const i=Wf(s);this.push(t,"temporal","durationSeconds",this.labels.duration,this.roundedShown(i&&i/1e3,1),"s"),this.push(t,"temporal","timeZone",this.labels.utcOffset,s.timeZone),this.push(t,"temporal","utcOffsetHours",this.labels.utcOffset,this.rounded(s.utcOffsetHours,1),"UTC±h")}addWeather(t,e,s){const i=Qa(e,s),a={fromSource:e.weatherSource!==void 0},o=this.showsPercent(i.cloudCover)||this.showsPercent(i.lowerCloudCover)||this.showsPercent(i.highCloudCover);this.push(t,"weather","cloudCover",this.labels.cloudCover,this.percentShown(i.cloudCover),"",a),this.push(t,"weather","highCloudCover",this.labels.highCloudCover,this.percentShown(i.highCloudCover),"",a),this.push(t,"weather","iceCrystalAlignment",this.labels.iceCrystalAlignment,this.showsPercent(i.highCloudCover)?this.percent(i.iceCrystalAlignment):void 0),this.push(t,"weather","rareIceCrystals",this.labels.rareIceCrystals,this.showsPercent(i.highCloudCover)?this.percent(i.rareIceCrystals):void 0),this.push(t,"weather","cloudDarkness",this.labels.cloudDarkness,o?this.percent(i.cloudDarkness):void 0,"",a),this.push(t,"weather","cloudBase",this.labels.cloudBase,o?this.rounded(i.cloudBaseM):void 0,"m",a);const r=i.precipitationType!=="none"&&this.showsPercent(i.precipitationIntensity);this.push(t,"weather","precipitationType",this.labels.precipitationType,r?this.precipitationName(i.precipitationType):void 0,"",a),this.push(t,"weather","precipitationIntensity",this.labels.precipitationIntensity,r?this.percent(i.precipitationIntensity):void 0,"",a),this.push(t,"weather","windDirection",this.labels.windDirection,this.shows(i.windSpeed,2)?this.rounded(i.windDirectionDeg):void 0,"°",a),this.push(t,"weather","windSpeed",this.labels.windSpeed,this.roundedShown(i.windSpeed,2),"m/s",a),i.storm&&this.push(t,"weather","storm",this.labels.storm,"✓","",a)}addSound(t,e,s){const i=Vf(e,s);i.kind!=="none"&&(this.push(t,"sound","soundKind",this.labels.soundKind,this.soundKindName(i.kind)),this.push(t,"sound","soundVolume",this.labels.soundVolume,this.percentShown(i.volume)),this.push(t,"sound","soundPitch",this.labels.soundPitch,this.roundedShown(i.pitchHz),"Hz"),this.push(t,"sound","soundSrc",this.labels.soundSrc,i.src))}addPhenomena(t,e,s){for(const i of e.timeline.sourceIds){const n=e.timeline.getInterpolatedShapeAt(s,i),a=n?.angular,o=a?`${this.rounded(a.widthDeg,2)} × ${this.rounded(a.heightDeg,2)}°`:void 0;this.push(t,"phenomenon",`shape:${i}`,this.said.read(n?.title)??i,o)}for(const i of e.interpretation?.bodies??[]){const n=i.track.find(o=>o.sizeM?.widthM!==void 0)?.sizeM?.widthM,a=i.model.id??i.model.url?.replace(/^.*\//,"");this.push(t,"phenomenon",`body:${i.id}`,this.said.read(i.title)??i.id,[a,n!==void 0?`${this.rounded(n,2)} m`:void 0].filter(Boolean).join(", "))}}decorLabel(t){return this.said.read(t.title)??this.decorKindName(t.kind)}decorKindName(t){switch(t){case"building":return this.labels.decorBuilding;case"tree":return this.labels.decorTree;case"shrub":return this.labels.decorShrub;case"bridge":return this.labels.decorBridge;case"wire":return this.labels.decorWire;case"crop":return this.labels.decorCrop;case"terrace":return this.labels.decorTerrace;case"mound":return this.labels.decorMound;case"wall":return this.labels.decorWall;case"streetlight":return this.labels.decorStreetlight;case"trafficlight":return this.labels.decorTrafficLight;case"peak":return this.labels.decorPeak;case"crossing":return this.labels.decorCrossing;case"roadsign":return this.labels.decorRoadSign;case"vehicle":return this.labels.decorVehicle;case"aircraft":return this.labels.decorAircraft;default:return this.labels.decorObserver}}decorSideName(t){switch(t){case"front":return this.labels.decorSideFront;case"behind":return this.labels.decorSideBehind;case"left":return this.labels.decorSideLeft;case"right":return this.labels.decorSideRight;case"front-left":return this.labels.decorSideFrontLeft;case"front-right":return this.labels.decorSideFrontRight;case"behind-left":return this.labels.decorSideBehindLeft;case"behind-right":return this.labels.decorSideBehindRight;default:return}}precipitationName(t){switch(t){case"rain":return this.labels.precipitationRain;case"snow":return this.labels.precipitationSnow;case"hail":return this.labels.precipitationHail;default:return this.labels.precipitationNone}}soundKindName(t){switch(t){case"hum":return this.labels.soundHum;case"whistle":return this.labels.soundWhistle;case"rumble":return this.labels.soundRumble;case"crackle":return this.labels.soundCrackle;default:return this.labels.soundNone}}}const a2="Global Meteor Network",o2="https://globalmeteornetwork.org/data/",r2="GFZ, Kp and Hp60 indices",c2="https://kp.gfz.de/",h2="“Thunder” by Jerimee",l2="https://creativecommons.org/licenses/by/3.0/",u2="CC BY 3.0";class Qe{static fill(t,e){t.innerHTML="";const s=d=>t.appendChild(d),i=e.currentTerrainAttribution;i&&s(Qe.text(i));const n=e.currentRoadAttribution;n&&s(Qe.text(n));const a=e.currentWaterAttribution;a&&s(Qe.text(a));const o=e.currentRailwayAttribution;o&&s(Qe.text(o));const r=e.ufoElement.observerMapCredit;r&&!i?.includes(r)&&s(Qe.text(r));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",m=document.createElement("li");d.sourceUrl?m.append(Qe.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):m.textContent=`${d.title}${f} (${d.license})`,s(m)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(Qe.link(d.creditUrl,d.credit)):f.textContent=d.credit,s(f)}if(e.ufoElement.sighting.traces.length>0){const d=new Nr(pn.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(m=>d.read(m.source)).filter(m=>!!m));for(const m of f)s(Qe.text(m))}const c=e.satelliteState;if(c.status==="ready"&&c.credit){const d=document.createElement("li");d.appendChild(Qe.link(c.creditUrl??"",c.credit)),s(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(Qe.link(o2,a2),document.createTextNode(" (CC BY 4.0)")),s(d)}if(e.archivedAuroraShown){const d=document.createElement("li");d.append(Qe.link(c2,r2),document.createTextNode(" (CC BY 4.0)")),s(d)}const h=e.aircraftState;if(h.status==="ready"&&h.shown>0){const d=document.createElement("li");if(d.appendChild(Qe.link(h.creditUrl,h.credit)),s(d),h.trailCredit){const f=document.createElement("li");f.appendChild(Qe.link(h.trailCredit.creditUrl,h.trailCredit.credit)),s(f)}}const l=Qe.text(`${h2} (`);l.append(Qe.link(l2,u2),document.createTextNode(")")),s(l)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const s=document.createElement("a");return s.href=t,s.target="_blank",s.rel="noopener",s.textContent=e,s}}const d2=ke.point("assessment").provide(ke.BUILT_IN,[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async u=>{const{CoverageAssessor:t}=await H(async()=>{const{CoverageAssessor:e}=await import("./CoverageAssessor-UyH_dVvr.js");return{CoverageAssessor:e}},__vite__mapDeps([13,1,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async u=>{const{HynekAssessor:t}=await H(async()=>{const{HynekAssessor:e}=await import("./HynekAssessor-D5zxfJ44.js");return{HynekAssessor:e}},__vite__mapDeps([14,15,1,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})},{id:"ballester-guasp",name:"Ballester-Guasp",credit:"V.-J. Ballester-Olmos & M. Guasp",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Ballester-Guasp.html",create:()=>({about:"observer",assess:async u=>{const{BallesterGuaspAssessor:t}=await H(async()=>{const{BallesterGuaspAssessor:e}=await import("./BallesterGuaspAssessor-DZ5guaNx.js");return{BallesterGuaspAssessor:e}},__vite__mapDeps([16,17,1,15,13,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async u=>{const{PoherAssessor:t}=await H(async()=>{const{PoherAssessor:e}=await import("./PoherAssessor-Cmw5u2Nv.js");return{PoherAssessor:e}},__vite__mapDeps([18,1,2,3,4,5,6,7,8,9,10]),import.meta.url);return new t().assess(u)}})}]);class Ym{constructor(t){this.labels=t}async read(t){const e=[],s=new Set;for(const i of d2){let n;try{n=await i.create().assess(t)}catch{continue}for(const o of n.criteria)o.basis===void 0&&!o.unsupported&&s.add(o.id);const a=n.score===void 0?n.verdict===void 0?"":this.verdictName(i.id,n.verdict):`${Math.round(n.score*100)}%`;a!==""&&e.push({group:"assessment",field:i.id,label:this.labels.assessmentNames[i.id]??i.name,value:a,unit:"",fromSource:!1,about:i.create().about,...n.factors?{detail:Ym.factorsText(n.factors)}:{}})}return{entries:e,unanswered:s}}static factorsText(t){const e={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(t).map(([s,i])=>`${e[s]??s} ${i.toFixed(2)}`).join(" × ")}verdictName(t,e){return this.labels.assessmentVerdicts[`${t}.${e}`]??e.toUpperCase()}}class Mo{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,s){const i=t.event.place?.[0],n=t.observerTrack;if(!i)return 0;const a=p=>{const g=n.getInterpolatedPoseAt(Math.max(0,p));if(!g||g.lat===void 0||g.lng===void 0)return;const M=ot(g.lat,g.lng,i.lat,i.lng);return{eastM:M.x,northM:-M.z,heading:g.headingDeg,aboveM:g.elevationM??0,altitudeM:g.altitudeM}},o=a(e-Mo.HALF_SPAN_MS),r=a(e+Mo.HALF_SPAN_MS),c=a(e);if(!o||!r||!c)return 0;const h=Math.hypot(r.eastM-o.eastM,r.northM-o.northM),l=2*Mo.HALF_SPAN_MS/1e3;if(h/l<Mo.MIN_SPEED_MS)return 0;const d=r.altitudeM!==void 0&&o.altitudeM!==void 0?r.altitudeM-o.altitudeM:s.heightAt(r.eastM,r.northM)+r.aboveM-s.heightAt(o.eastM,o.northM)-o.aboveM,f=Math.atan2(d,h)*180/Math.PI;if(c.heading===void 0)return f;const m=Math.atan2(r.eastM-o.eastM,r.northM-o.northM)*180/Math.PI;return f*Math.max(0,Math.cos((c.heading-m)*Math.PI/180))}}const f2=.08,qd=.15,jd=2,m2=2e3;class Zd{context;constructor(t){this.context=t}noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}qs.isLive(this.context)&&qs.unlock(this.context),this.apply()}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}setPaused(t){t!==this.paused&&(this.paused=t,this.apply())}setVoices(t){this.requested=t,this.apply()}dispose(){for(const t of[...this.voices.keys()])this.release(t);qs.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}apply(){const t=this.context;if(!t)return;const e=this.paused?[]:this.requested.filter(i=>i.inside||i.distanceM<m2),s=new Set(e.map(i=>i.id));for(const i of[...this.voices.keys()])s.has(i)||this.release(i);for(const i of e){const n=this.voices.get(i.id)??this.build(t,i.id);this.retarget(t,n,i)}}build(t,e){const s=t.createGain();s.gain.value=0;const i=t.createBiquadFilter();i.type="lowpass",i.connect(s).connect(this.masterOf(t));const n=t.createOscillator();n.type="sawtooth";const a=t.createOscillator();a.type="sine";const o=t.createGain(),r=t.createBiquadFilter();r.type="lowpass",r.frequency.value=900,n.connect(r),a.connect(r),r.connect(o).connect(i);const c=()=>{const b=t.createBufferSource();return b.buffer=this.noise(t),b.loop=!0,b.loopStart=Math.random()*jd*.5,b},h=c(),l=t.createBiquadFilter();l.type="bandpass",l.Q.value=4;const d=t.createGain();h.connect(l).connect(d).connect(i);const f=c(),m=t.createBiquadFilter();m.type="lowpass",m.frequency.value=600;const p=t.createGain();f.connect(m).connect(p).connect(i);const g=c(),M=t.createBiquadFilter();M.type="bandpass",M.frequency.value=1400,M.Q.value=.7;const v=t.createGain();g.connect(M).connect(v).connect(i);const y=[n,a,h,f,g];for(const b of y)b.start();const w={nodes:[s,i,o,r,l,d,m,p,M,v,...y],sources:y,firing:n,crank:a,knock:l,engineGain:o,knockGain:d,roadGain:p,windGain:v,cabin:i,output:s};return this.voices.set(e,w),w}retarget(t,e,{profile:s,state:i,noise:n,inside:a,windowsOpen:o,distanceM:r}){const c=t.currentTime,h=(v,y)=>v.setTargetAtTime(y,c,f2),l=i.rpm/60,d=l*s.cylinders/2,f=Math.min(1,i.rpm/s.shiftUpRpm),m=Math.min(1.5,i.speedMps/30);h(e.firing.frequency,d),h(e.crank.frequency,l),h(e.knock.frequency,d*3),h(e.engineGain.gain,s.engineGain*(.25+.75*i.load)*(.5+.5*f)*.3),h(e.knockGain.gain,s.roughness*(.2+.8*i.load)*.4),h(e.roadGain.gain,s.roadGain*m**1.5*.8);const p=!a||o;h(e.windGain.gain,m**2*(p?.5:.06));const g=a?o?3500:700:8e3/(1+r/60);h(e.cabin.frequency,g);const M=a?.5:Math.min(1,8/Math.max(r,1));h(e.output.gain,M*n)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const s=this.context;s&&(e.output.gain.setTargetAtTime(0,s.currentTime,qd/3),setTimeout(()=>{for(const i of e.sources)try{i.stop()}catch{}for(const i of e.nodes)i.disconnect()},qd*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*jd,t.sampleRate),s=e.getChannelData(0);for(let i=0;i<s.length;i++)s[i]=Math.random()*2-1;return this.noiseBuffer=e,e}}class Hr{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(t){return Hr.BY_KIND[t??"generic"]??Hr.BY_KIND.generic}}class ns{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(t){return ns.ROAD_KINDS.includes(t)}static roadOf(t){return t&&ns.isRoad(t.kind)?t.kind:void 0}static aircraftOf(t){return t&&!ns.isRoad(t.kind)?t.kind:void 0}static transmission(t){const e=ns.insulationDb(t),s=[3,4,5].map(i=>e[i]);return 10**(-(s.reduce((i,n)=>i+n,0)/s.length)/20)}static insulationDb(t){return t?t.windowsOpen===!0?ns.WINDOWS_OPEN_DB:ns.isRoad(t.kind)?ns.ROAD_CLOSED_DB:ns.CANOPIED.includes(t.kind)?ns.CANOPY_DB:ns.FUSELAGE_DB:ns.OPEN_AIR}}class ga{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,s,i){const n=ga.SAMPLE_MS,a=[];for(let c=s;c<=i+n/2;c+=n){const h=e(c-n/2),l=e(c+n/2);if(!h||!l)return;a.push(Math.hypot(l.eastM-h.eastM,l.northM-h.northM)/(n/1e3))}const o=[];let r=1;for(let c=0;c<a.length;c++){const h=a[c],l=(a[Math.min(c+1,a.length-1)]-a[Math.max(c-1,0)])/(2*n/1e3);if(h<ga.STANDING_MPS){r=1,o.push({speedMps:h,rpm:t.idleRpm,load:.1,gear:0});continue}const d=h*3.6,f=M=>d/t.kmhPer1000Rpm[M-1]*1e3;for(;r<t.kmhPer1000Rpm.length&&f(r)>t.shiftUpRpm;)r++;for(;r>1&&f(r)<t.shiftDownRpm;)r--;const m=Math.max(f(r),t.idleRpm*(1+.3*Math.min(1,h/3))),p=.15+.5*Math.min(1,(h/35)**2),g=l>.15?Math.min(1,p+l/2.5):l<-.3?.05:p;o.push({speedMps:h,rpm:m,load:g,gear:r})}return new ga(o,s)}at(t){const e=(t-this.startMs)/ga.SAMPLE_MS,s=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),i=this.samples[s],n=this.samples[Math.min(s+1,this.samples.length-1)],a=Math.min(Math.max(e-s,0),1);return{speedMps:i.speedMps+(n.speedMps-i.speedMps)*a,rpm:i.rpm+(n.rpm-i.rpm)*a,load:i.load+(n.load-i.load)*a,gear:a<.5?i.gear:n.gear}}}class Zc{drives=new Map;at(t,e){const s=[],i=t.event.place?.[0],n=h=>{const l=t.observerTrack.getInterpolatedPoseAt(h),d=l?.lat??i?.lat,f=l?.lng??i?.lng;if(d===void 0||f===void 0||!i)return;const m=ot(d,f,i.lat,i.lng);return{eastM:m.x,northM:-m.z}},a=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),o=t.vehicle,r=ns.roadOf(o);if(o&&r){const h=Hr.of(r),l=this.drive(`observer:${r}`,Zc.trackKey(t),()=>ga.of(h,n,0,a));l&&s.push({id:"observer",profile:h,state:l.at(e),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const c=n(e);for(const h of t.decor){if(!h.engine||!c)continue;const l=Hr.of(h.engine.kind),d=g=>{const M=wi(h,g);return{eastM:M.eastM,northM:M.northM}},f=this.drive(`decor:${h.id}`,Zc.decorKey(h,a),()=>ga.of(l,d,0,a));if(!f)continue;const m=wi(h,e),p=Math.hypot(m.eastM-c.eastM,m.northM-c.northM,m.altitudeM);s.push({id:`decor:${h.id}`,profile:l,state:f.at(e),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return s}drive(t,e,s){const i=this.drives.get(t);if(i&&i.key===e)return i.drive;const n=s();return this.drives.set(t,{key:e,drive:n}),n}static trackKey(t){return t.observerTrack.allKeyframes.map(s=>`${s.t}:${s.pose.lat}:${s.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(s=>`${s.t}:${s.eastM}:${s.northM}`).join(";")}}const Jd=864e5,Qd=4e4;function p2(u){const t=Math.floor(u.getTime()/Jd);return{elapsedMs:u.getTime()-t*Jd,shiftM:{x:t0.unit(t,2654435761)*Qd,z:t0.unit(t,2246822507)*Qd}}}class t0{static unit(t,e){let s=Math.imul(t|0,e)^e;return s=Math.imul(s^s>>>15,739982445),s=Math.imul(s^s>>>12,695872825),s^=s>>>15,(s>>>0)/4294967295*2-1}}function e0(u,t,e,s,i,n,a){const o=s?.lat!==void 0&&s.lng!==void 0&&i?.lat!==void 0&&i.lng!==void 0?ot(i.lat,i.lng,s.lat,s.lng):{x:0,z:0};if(a){const h=t.getInterpolatedWeatherAt(0)??e,l=n===void 0?void 0:h.cloudLayers?.find(m=>m.id===n),d=(l?.windDirectionDeg??h.windDirectionDeg)*Math.PI/180,f=(l?.windSpeed??h.windSpeed)*a.elapsedMs/1e3;o.x+=a.shiftM.x-Math.sin(d)*f,o.z+=a.shiftM.z+Math.cos(d)*f}const r=Math.max(0,u),c=[0,...t.allKeyframes.map(h=>h.t).filter(h=>h>0&&h<r),r];for(let h=1;h<c.length;h++){const l=c[h-1],d=c[h]-l;if(d===0)continue;const f=32;for(let m=0;m<=f;m++){const p=t.getInterpolatedWeatherAt(l+d*m/f)??e,g=n===void 0?void 0:p.cloudLayers?.find(w=>w.id===n),M=(g?.windDirectionDeg??p.windDirectionDeg)*Math.PI/180,v=m===0||m===f?1:m%2===0?2:4,y=(g?.windSpeed??p.windSpeed)*d/1e3/f/3*v;o.x-=Math.sin(M)*y,o.z+=Math.cos(M)*y}}return o}const g2="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",M2=`
|
|
1630
1634
|
<div class="stage" id="stage">
|
|
1631
1635
|
<div class="frame" id="frame">
|
|
1632
1636
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -3284,7 +3288,7 @@ float roadNoise(vec2 p) {
|
|
|
3284
3288
|
if (fromEdge < reach) discard;
|
|
3285
3289
|
}
|
|
3286
3290
|
#endif
|
|
3287
|
-
}`)},t.customProgramCacheKey=()=>s?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let i=0;i<t.length-1;i++){const n=t[i],a=t[i+1],o=Math.hypot(a.x-n.x,a.z-n.z),r=Math.max(1,Math.ceil(o/this.stepM));for(let c=0;c<r;c++){const h=c/r;e.push({x:n.x+(a.x-n.x)*h,z:n.z+(a.z-n.z)*h})}}const s=t[t.length-1];return s&&e.push({x:s.x,z:s.z}),e}}class Ii{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((s,i)=>{const n=t[i].widthM/2+.3;for(let a=1;a<s.length;a++){const o=s[a-1].x,r=s[a-1].z,c=s[a].x-o,h=s[a].z-r,l={way:i,ax:o,az:r,dx:c,dz:h,length2:c*c+h*h,reach:n},d=Math.floor((Math.min(o,s[a].x)-n)/Ii.CELL_M),f=Math.floor((Math.max(o,s[a].x)+n)/Ii.CELL_M),m=Math.floor((Math.min(r,s[a].z)-n)/Ii.CELL_M),p=Math.floor((Math.max(r,s[a].z)+n)/Ii.CELL_M);for(let g=d;g<=f;g++)for(let M=m;M<=p;M++){const v=Ii.key(g,M),y=this.cells.get(v);y?y.push(l):this.cells.set(v,[l])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,s){const i=this.cells.get(Ii.key(Math.floor(t/Ii.CELL_M),Math.floor(e/Ii.CELL_M)));if(!i)return!1;for(const n of i){if(n.way===s)continue;const a=n.length2===0?0:Math.max(0,Math.min(1,((t-n.ax)*n.dx+(e-n.az)*n.dz)/n.length2));if(Math.hypot(t-(n.ax+n.dx*a),e-(n.az+n.dz*a))<n.reach)return!0}return!1}}class Jt{constructor(t,e=[]){this.lamps=e;for(const s of t){const i=Math.hypot(s.halfAlongM,s.halfAcrossM),n=Math.floor((s.x-i)/Jt.CELL_M),a=Math.floor((s.x+i)/Jt.CELL_M),o=Math.floor((s.z-i)/Jt.CELL_M),r=Math.floor((s.z+i)/Jt.CELL_M);for(let c=n;c<=a;c++)for(let h=o;h<=r;h++){const l=Jt.key(c,h),d=this.cells.get(l);d?d.push(s):this.cells.set(l,[s])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,s,i){const n=[],a=[];for(const o of Jt.SAMPLES_M){const r=t+s*o,c=e+i*o,h=this.wall(r,c,-i,s),l=this.wall(r,c,i,-s);h!==void 0&&n.push(h),l!==void 0&&a.push(l)}return{leftM:Jt.agreed(n),rightM:Jt.agreed(a)}}lampsAlong(t){const e=[];for(const s of this.lamps){let i;for(let n=1;n<t.length;n++){const a=t[n-1].x,o=t[n-1].z,r=t[n].x-a,c=t[n].z-o,h=r*r+c*c;if(h===0)continue;const l=((s.x-a)*r+(s.z-o)*c)/h;if(l<0||l>1)continue;const d=Math.sqrt(h),f=((s.x-a)*-c+(s.z-o)*r)/d;(!i||Math.abs(f)<i.distance)&&(i={distance:Math.abs(f),lateral:f})}i&&i.distance<=Jt.REACH_M&&e.push(i.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=Jt.REACH_M+Math.max(...Jt.SAMPLES_M.map(Math.abs)),s=t.map(n=>n.x),i=t.map(n=>n.z);for(let n=Math.floor((Math.min(...s)-e)/Jt.CELL_M);n<=Math.floor((Math.max(...s)+e)/Jt.CELL_M);n++)for(let a=Math.floor((Math.min(...i)-e)/Jt.CELL_M);a<=Math.floor((Math.max(...i)+e)/Jt.CELL_M);a++)if(this.cells.has(Jt.key(n,a)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,s)=>e-s),t[Math.floor((t.length-1)/2)]}wall(t,e,s,i){let n;const a=new Set,o=Jt.CELL_M/2;for(let r=0;r<=Jt.REACH_M+o;r+=o){const c=this.cells.get(Jt.key(Math.floor((t+s*r)/Jt.CELL_M),Math.floor((e+i*r)/Jt.CELL_M)));for(const h of c??[]){if(a.has(h))continue;a.add(h);const l=Jt.hit(h,t,e,s,i);l!==void 0&&l<=Jt.REACH_M&&(n===void 0||l<n)&&(n=l)}}return n!==void 0&&n>=Jt.NEAREST_M?n:void 0}static hit(t,e,s,i,n){const a=e-t.x,o=s-t.z,r=[a*t.alongX+o*t.alongZ,-a*t.alongZ+o*t.alongX],c=[i*t.alongX+n*t.alongZ,-i*t.alongZ+n*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let l=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(c[f])<1e-9){if(Math.abs(r[f])>h[f])return;continue}const m=(-h[f]-r[f])/c[f],p=(h[f]-r[f])/c[f];l=Math.max(l,Math.min(m,p)),d=Math.min(d,Math.max(m,p))}if(!(d<l||d<0||l<0))return l}static key(t,e){return(t+5e4)*100003+(e+5e4)}}const oM=Sn.catalog({en:()=>H(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(u=>u.beamKindMessages_en),fr:()=>H(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(u=>u.beamKindMessages_fr),es:()=>H(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(u=>u.beamKindMessages_es),it:()=>H(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(u=>u.beamKindMessages_it)}),h0={key:"beams",messages:oM,pickKind:"beam",simulation:()=>H(async()=>{const{BeamSystem:u}=await import("./BeamSystem-C8jjTJtB.js");return{BeamSystem:u}},__vite__mapDeps([20,4,21,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({BeamSystem:u})=>()=>new u),editor:()=>H(async()=>{const{BeamEditor:u}=await import("./BeamEditor-gxTjO6Pr.js");return{BeamEditor:u}},__vite__mapDeps([22,1,5,6,21,23,24,25,2,3,4,7,8,9,10]),import.meta.url).then(({BeamEditor:u})=>(t,e,s)=>new u(t,e,s)),reachM:(u,t)=>it.beamReachFor(u,t),describe:(u,t,{texts:e,name:s,distance:i})=>({name:s,detail:e.detail.replace("{name}",s).replace("{wavelength}",String(u.wavelengthNm)).replace("{power}",u.powerW.toLocaleString()).replace("{distance}",i(t.distanceM??0))})},rM=Sn.catalog({en:()=>H(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(u=>u.launchKindMessages_en),fr:()=>H(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(u=>u.launchKindMessages_fr),es:()=>H(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(u=>u.launchKindMessages_es),it:()=>H(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(u=>u.launchKindMessages_it)}),l0={key:"launches",messages:rM,pickKind:"plume",simulation:()=>H(async()=>{const{LaunchSimulation:u}=await import("./LaunchSimulation-RROdYccW.js");return{LaunchSimulation:u}},__vite__mapDeps([26,27,4,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({LaunchSimulation:u})=>()=>new u),editor:()=>H(async()=>{const{LaunchEditor:u}=await import("./LaunchEditor-CM2Wcjv2.js");return{LaunchEditor:u}},__vite__mapDeps([28,1,5,6,23,27,24,25,2,3,4,7,8,9,10]),import.meta.url).then(({LaunchEditor:u})=>(t,e,s)=>new u(t,e,s)),describe:(u,t,{said:e,texts:s,distance:i})=>{const n=t.detail,a=e.read(u.title)||u.vehicle?.mission||s.name,o=n.release===void 0||n.release==="burn"?void 0:u.jets?.find((c,h)=>`jet:${c.id??h}`===n.release),r=n.release===void 0||n.release==="burn"?s.ascent:o?.kind==="vent"?s.vent:s.burn;return{name:a,detail:s.detail.replace("{name}",a).replace("{part}",r).replace("{distance}",i(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}},cM=Sn.catalog({en:()=>H(()=>import("./ReentryKindMessages_en-BGZgya17.js"),[],import.meta.url).then(u=>u.reentryKindMessages_en),fr:()=>H(()=>import("./ReentryKindMessages_fr-7mer-cdj.js"),[],import.meta.url).then(u=>u.reentryKindMessages_fr),es:()=>H(()=>import("./ReentryKindMessages_es--UxzPNfj.js"),[],import.meta.url).then(u=>u.reentryKindMessages_es),it:()=>H(()=>import("./ReentryKindMessages_it-BBVQXE1M.js"),[],import.meta.url).then(u=>u.reentryKindMessages_it)}),hM=Sn.catalog({en:()=>H(()=>import("./ReentryTypeNames_en-CBu890Bd.js"),[],import.meta.url).then(u=>u.reentryTypeNames_en),fr:()=>H(()=>import("./ReentryTypeNames_fr-BXq89mrz.js"),[],import.meta.url).then(u=>u.reentryTypeNames_fr),es:()=>H(()=>import("./ReentryTypeNames_es-_LnketjJ.js"),[],import.meta.url).then(u=>u.reentryTypeNames_es),it:()=>H(()=>import("./ReentryTypeNames_it-Yfq-TDip.js"),[],import.meta.url).then(u=>u.reentryTypeNames_it)}),lM=u=>({load:t=>hM.load(t).then(e=>({name:e[u]}))}),Zo=(u,t,e,s)=>({id:u,name:u,credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>({key:u,nature:e,messages:lM(t),template:s})}),uM=ke.point("reentryTypes").provide(ke.BUILT_IN,[Zo("meteor","meteor","natural",{distanceKm:150,speedKmS:40,durationS:1,fromAltitudeKm:100,toAltitudeKm:85,fragments:[{id:"main",absoluteMagnitude:0,trainS:.3,sheds:[]}]}),Zo("fireball","fireball","natural",{distanceKm:150,speedKmS:30,durationS:3,fromAltitudeKm:100,toAltitudeKm:60,fragments:[{id:"main",absoluteMagnitude:-6}]}),Zo("satellite","satellite","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-3},{id:"piece-2",lagS:2,absoluteMagnitude:-1.5}]}),Zo("rocket-stage","rocketStage","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-4},{id:"piece-2",lagS:1.5,absoluteMagnitude:-2.5},{id:"piece-3",lagS:3,absoluteMagnitude:-1.5}]}),Zo("capsule","capsule","artificial",{distanceKm:300,speedKmS:7.5,durationS:40,fromAltitudeKm:80,toAltitudeKm:55,fragments:[{id:"main",absoluteMagnitude:-5,sheds:[]}]})]);class mi{static built=new WeakMap;static names=new Map;static namesLanguage;static all(){return uM.map(t=>{let e=mi.built.get(t);return e||mi.built.set(t,e=t.create()),e})}static of(t){return t===void 0?void 0:mi.all().find(e=>e.key===t)}static async load(t){const e=mi.all(),s=await Promise.all(e.map(i=>i.messages.load(t).then(n=>n.name,()=>i.key)));mi.names=new Map(e.map((i,n)=>[i.key,s[n]])),mi.namesLanguage=t}static nameOf(t){return mi.names.get(t)??t}static get language(){return mi.namesLanguage}}const u0={key:"reentries",messages:cM,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>H(async()=>{const{ReentrySimulation:u}=await import("./ReentrySimulation-HhdlSVkR.js");return{ReentrySimulation:u}},__vite__mapDeps([29,4,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({ReentrySimulation:u})=>()=>new u),editor:()=>H(async()=>{const{ReentryEditor:u}=await import("./ReentryEditor-Di0KzYeZ.js");return{ReentryEditor:u}},__vite__mapDeps([30,1,5,6,23,2,3,24,25,31,4,7,8,9,10]),import.meta.url).then(({ReentryEditor:u})=>(t,e,s)=>new u(t,e,s)),describe:(u,t,{said:e,texts:s})=>{const i=t.detail,n=u.type!==void 0&&mi.language!==void 0?mi.nameOf(u.type):"",a=(u.title?e.read(u.title):"")||u.object?.name||n||s.name,o=i.view.head,r=6371,c=Math.sqrt(r**2+o.distanceKm**2+2*r*o.distanceKm*Math.sin(o.altitudeDeg*Math.PI/180))-r;return{name:(i.view.fragmentId.includes(".")?s.fragment:s.piece).replace("{name}",a).replace("{mag}",i.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(c).toLocaleString()).replace("{distance}",Math.round(o.distanceKm).toLocaleString())}}},dM=Sn.catalog({en:()=>H(()=>import("./AuroraKindMessages_en-D_W4giJa.js"),[],import.meta.url).then(u=>u.auroraKindMessages_en),fr:()=>H(()=>import("./AuroraKindMessages_fr-6IzUVbRH.js"),[],import.meta.url).then(u=>u.auroraKindMessages_fr),es:()=>H(()=>import("./AuroraKindMessages_es-jJ5_ltZq.js"),[],import.meta.url).then(u=>u.auroraKindMessages_es),it:()=>H(()=>import("./AuroraKindMessages_it-DcwuoMkp.js"),[],import.meta.url).then(u=>u.auroraKindMessages_it)}),d0={key:"auroras",messages:dM,pickKind:"aurora",simulation:()=>H(async()=>{const{AuroraSimulation:u}=await import("./AuroraSimulation-DqfSBul6.js");return{AuroraSimulation:u}},__vite__mapDeps([32,33,4,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({AuroraSimulation:u})=>()=>new u),editor:()=>H(async()=>{const{AuroraEditor:u}=await import("./AuroraEditor-CDZgVOlI.js");return{AuroraEditor:u}},__vite__mapDeps([34,1,5,6,23,24,33,2,3,4,7,8,9,10]),import.meta.url).then(({AuroraEditor:u})=>(t,e,s)=>new u(t,e,s)),describe:(u,t,{texts:e,name:s})=>{const i=t.detail,n=a=>a.toLocaleString(void 0,{maximumFractionDigits:1});return{name:s,detail:e.detail.replace("{name}",s).replace("{kp}",n(i.kp)).replace("{green}",n(i.green)).replace("{red}",n(i.red))}}};class Hs{static DEFAULT_HEIGHT_M=2;static DEFAULT_INTENSITY_CD=3e8;static DEFAULT_DIVERGENCE_DEG=1;static DEFAULT_TEMPERATURE_K=5600;static DEFAULT_TILT_DEG=25;static DEFAULT_SPREAD_DEG=60;static DEFAULT_PERIOD_S=12;static RANGE_M=25e3;static CEILING_M=15e3;static MAX_BEAMS=16;static onAt(t,e){return t.filter(s=>(s.fromT===void 0||e>=s.fromT)&&(s.untilT===void 0||e<=s.untilT))}static beamsOf(t){return Math.max(1,Math.min(Hs.MAX_BEAMS,Math.round(t.beams??1)))}static motionOf(t){if(t.motion)return t.motion;const e=Hs.beamsOf(t);return e===4?"cloverleaf":e===1?"sweep":"rotate"}static aimsAt(t,e){const s=Hs.beamsOf(t),i=t.tiltDeg??Hs.DEFAULT_TILT_DEG,n=t.spreadDeg??Hs.DEFAULT_SPREAD_DEG,a=t.azimuthDeg??0,o=Math.max(.1,t.periodS??Hs.DEFAULT_PERIOD_S),r=2*Math.PI*(e/1e3)/o,c=[];for(let h=0;h<s;h++){const l=360*h/s;switch(Hs.motionOf(t)){case"fixed":c.push({tiltDeg:i,azimuthDeg:a+l});break;case"sweep":c.push({tiltDeg:i,azimuthDeg:a+n/2*Math.sin(r-2*Math.PI*h/s)});break;case"rotate":c.push({tiltDeg:i,azimuthDeg:a+l+r*180/Math.PI});break;case"cloverleaf":{const d=r+2*Math.PI*h/s;c.push({tiltDeg:i*Math.abs(Math.cos(2*d)),azimuthDeg:a+d*180/Math.PI});break}}}return c.map(h=>({tiltDeg:h.tiltDeg,azimuthDeg:(h.azimuthDeg%360+360)%360}))}static axisOf(t){const e=t.tiltDeg*Math.PI/180,s=t.azimuthDeg*Math.PI/180;return{east:Math.sin(e)*Math.sin(s),north:Math.sin(e)*Math.cos(s),up:Math.cos(e)}}static fluxLm(t,e){const s=e*Math.PI/180;return t*Math.PI*s*s/(4*Math.LN2)}static illuminanceLux(t,e,s,i=0){const n=e*Math.PI/180;return t*Math.exp(-4*Math.LN2*i*i/(n*n))/Math.max(1,s*s)}static reachM(t,e){let s=0;for(const i of t){const n=ot(i.lat,i.lng,e.lat,e.lng);s=Math.max(s,Math.hypot(n.x,n.z)+Hs.RANGE_M)}return s}static patchOn(t,e){const s=Hs.axisOf(t);if(s.up<=1e-6)return;const i=e/s.up;return{eastM:s.east*i,northM:s.north*i}}}const fM=Sn.catalog({en:()=>H(()=>import("./SearchlightKindMessages_en-CwJDAjsc.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_en),fr:()=>H(()=>import("./SearchlightKindMessages_fr-DsxiUhmK.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_fr),es:()=>H(()=>import("./SearchlightKindMessages_es-CCCgZyTQ.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_es),it:()=>H(()=>import("./SearchlightKindMessages_it-CyWpJL5c.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_it)}),f0={key:"searchlights",messages:fM,pickKind:"searchlight",simulation:()=>H(async()=>{const{SearchlightSystem:u}=await import("./SearchlightSystem-D_DTpDNC.js");return{SearchlightSystem:u}},__vite__mapDeps([35,20,4,21,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({SearchlightSystem:u})=>()=>new u),editor:()=>H(async()=>{const{SearchlightEditor:u}=await import("./SearchlightEditor-B6_BW8FD.js");return{SearchlightEditor:u}},__vite__mapDeps([36,1,5,6,23,24,2,3,4,7,8,9,10]),import.meta.url).then(({SearchlightEditor:u})=>(t,e,s)=>new u(t,e,s)),reachM:(u,t)=>Hs.reachM(u,t),describe:(u,t,{texts:e,name:s,distance:i})=>{const n=t.detail?.beam??1;return{name:s,detail:e.detail.replace("{name}",s).replace("{beam}",String(n)).replace("{beams}",String(Hs.beamsOf(u))).replace("{intensity}",(u.intensityCd??Hs.DEFAULT_INTENSITY_CD).toExponential(1)).replace("{distance}",i(t.distanceM??0))}}},fu=ke.point("skyEvents").provide(ke.BUILT_IN,[{id:l0.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>l0},{id:h0.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>h0},{id:f0.key,name:"Searchlights",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>f0},{id:u0.key,name:"Re-entries",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>u0},{id:d0.key,name:"Aurorae",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>d0}]);class vn{static built=new WeakMap;static of(t){let e=vn.built.get(t);return e||(e=t.create(),vn.built.set(t,e)),e}static eventsOf(t,e){const s=t?.[e.key];return Array.isArray(s)?s:[]}}class nh{static KEY="cloudDimming";static apply(t,e){const s=e.map(i=>i.mesh.uuid).join(",");t.userData[nh.KEY]!==s&&(t.userData[nh.KEY]=s,t.customProgramCacheKey=()=>`cloud-dimming|${s}`,t.onBeforeCompile=i=>{if(e.length===0)return;i.vertexShader=`varying vec3 dimmedPoint;
|
|
3291
|
+
}`)},t.customProgramCacheKey=()=>s?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let i=0;i<t.length-1;i++){const n=t[i],a=t[i+1],o=Math.hypot(a.x-n.x,a.z-n.z),r=Math.max(1,Math.ceil(o/this.stepM));for(let c=0;c<r;c++){const h=c/r;e.push({x:n.x+(a.x-n.x)*h,z:n.z+(a.z-n.z)*h})}}const s=t[t.length-1];return s&&e.push({x:s.x,z:s.z}),e}}class Ii{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((s,i)=>{const n=t[i].widthM/2+.3;for(let a=1;a<s.length;a++){const o=s[a-1].x,r=s[a-1].z,c=s[a].x-o,h=s[a].z-r,l={way:i,ax:o,az:r,dx:c,dz:h,length2:c*c+h*h,reach:n},d=Math.floor((Math.min(o,s[a].x)-n)/Ii.CELL_M),f=Math.floor((Math.max(o,s[a].x)+n)/Ii.CELL_M),m=Math.floor((Math.min(r,s[a].z)-n)/Ii.CELL_M),p=Math.floor((Math.max(r,s[a].z)+n)/Ii.CELL_M);for(let g=d;g<=f;g++)for(let M=m;M<=p;M++){const v=Ii.key(g,M),y=this.cells.get(v);y?y.push(l):this.cells.set(v,[l])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,s){const i=this.cells.get(Ii.key(Math.floor(t/Ii.CELL_M),Math.floor(e/Ii.CELL_M)));if(!i)return!1;for(const n of i){if(n.way===s)continue;const a=n.length2===0?0:Math.max(0,Math.min(1,((t-n.ax)*n.dx+(e-n.az)*n.dz)/n.length2));if(Math.hypot(t-(n.ax+n.dx*a),e-(n.az+n.dz*a))<n.reach)return!0}return!1}}class Jt{constructor(t,e=[]){this.lamps=e;for(const s of t){const i=Math.hypot(s.halfAlongM,s.halfAcrossM),n=Math.floor((s.x-i)/Jt.CELL_M),a=Math.floor((s.x+i)/Jt.CELL_M),o=Math.floor((s.z-i)/Jt.CELL_M),r=Math.floor((s.z+i)/Jt.CELL_M);for(let c=n;c<=a;c++)for(let h=o;h<=r;h++){const l=Jt.key(c,h),d=this.cells.get(l);d?d.push(s):this.cells.set(l,[s])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,s,i){const n=[],a=[];for(const o of Jt.SAMPLES_M){const r=t+s*o,c=e+i*o,h=this.wall(r,c,-i,s),l=this.wall(r,c,i,-s);h!==void 0&&n.push(h),l!==void 0&&a.push(l)}return{leftM:Jt.agreed(n),rightM:Jt.agreed(a)}}lampsAlong(t){const e=[];for(const s of this.lamps){let i;for(let n=1;n<t.length;n++){const a=t[n-1].x,o=t[n-1].z,r=t[n].x-a,c=t[n].z-o,h=r*r+c*c;if(h===0)continue;const l=((s.x-a)*r+(s.z-o)*c)/h;if(l<0||l>1)continue;const d=Math.sqrt(h),f=((s.x-a)*-c+(s.z-o)*r)/d;(!i||Math.abs(f)<i.distance)&&(i={distance:Math.abs(f),lateral:f})}i&&i.distance<=Jt.REACH_M&&e.push(i.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=Jt.REACH_M+Math.max(...Jt.SAMPLES_M.map(Math.abs)),s=t.map(n=>n.x),i=t.map(n=>n.z);for(let n=Math.floor((Math.min(...s)-e)/Jt.CELL_M);n<=Math.floor((Math.max(...s)+e)/Jt.CELL_M);n++)for(let a=Math.floor((Math.min(...i)-e)/Jt.CELL_M);a<=Math.floor((Math.max(...i)+e)/Jt.CELL_M);a++)if(this.cells.has(Jt.key(n,a)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,s)=>e-s),t[Math.floor((t.length-1)/2)]}wall(t,e,s,i){let n;const a=new Set,o=Jt.CELL_M/2;for(let r=0;r<=Jt.REACH_M+o;r+=o){const c=this.cells.get(Jt.key(Math.floor((t+s*r)/Jt.CELL_M),Math.floor((e+i*r)/Jt.CELL_M)));for(const h of c??[]){if(a.has(h))continue;a.add(h);const l=Jt.hit(h,t,e,s,i);l!==void 0&&l<=Jt.REACH_M&&(n===void 0||l<n)&&(n=l)}}return n!==void 0&&n>=Jt.NEAREST_M?n:void 0}static hit(t,e,s,i,n){const a=e-t.x,o=s-t.z,r=[a*t.alongX+o*t.alongZ,-a*t.alongZ+o*t.alongX],c=[i*t.alongX+n*t.alongZ,-i*t.alongZ+n*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let l=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(c[f])<1e-9){if(Math.abs(r[f])>h[f])return;continue}const m=(-h[f]-r[f])/c[f],p=(h[f]-r[f])/c[f];l=Math.max(l,Math.min(m,p)),d=Math.min(d,Math.max(m,p))}if(!(d<l||d<0||l<0))return l}static key(t,e){return(t+5e4)*100003+(e+5e4)}}const oM=Sn.catalog({en:()=>H(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(u=>u.beamKindMessages_en),fr:()=>H(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(u=>u.beamKindMessages_fr),es:()=>H(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(u=>u.beamKindMessages_es),it:()=>H(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(u=>u.beamKindMessages_it)}),h0={key:"beams",messages:oM,pickKind:"beam",simulation:()=>H(async()=>{const{BeamSystem:u}=await import("./BeamSystem-BbSsBbZk.js");return{BeamSystem:u}},__vite__mapDeps([20,4,21,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({BeamSystem:u})=>()=>new u),editor:()=>H(async()=>{const{BeamEditor:u}=await import("./BeamEditor-Dgo8WSF9.js");return{BeamEditor:u}},__vite__mapDeps([22,1,5,6,21,23,24,25,2,3,4,7,8,9,10]),import.meta.url).then(({BeamEditor:u})=>(t,e,s)=>new u(t,e,s)),reachM:(u,t)=>it.beamReachFor(u,t),describe:(u,t,{texts:e,name:s,distance:i})=>({name:s,detail:e.detail.replace("{name}",s).replace("{wavelength}",String(u.wavelengthNm)).replace("{power}",u.powerW.toLocaleString()).replace("{distance}",i(t.distanceM??0))})},rM=Sn.catalog({en:()=>H(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(u=>u.launchKindMessages_en),fr:()=>H(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(u=>u.launchKindMessages_fr),es:()=>H(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(u=>u.launchKindMessages_es),it:()=>H(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(u=>u.launchKindMessages_it)}),l0={key:"launches",messages:rM,pickKind:"plume",simulation:()=>H(async()=>{const{LaunchSimulation:u}=await import("./LaunchSimulation-BsCQGsdb.js");return{LaunchSimulation:u}},__vite__mapDeps([26,27,4,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({LaunchSimulation:u})=>()=>new u),editor:()=>H(async()=>{const{LaunchEditor:u}=await import("./LaunchEditor-C91_y6bJ.js");return{LaunchEditor:u}},__vite__mapDeps([28,1,5,6,23,27,24,25,2,3,4,7,8,9,10]),import.meta.url).then(({LaunchEditor:u})=>(t,e,s)=>new u(t,e,s)),describe:(u,t,{said:e,texts:s,distance:i})=>{const n=t.detail,a=e.read(u.title)||u.vehicle?.mission||s.name,o=n.release===void 0||n.release==="burn"?void 0:u.jets?.find((c,h)=>`jet:${c.id??h}`===n.release),r=n.release===void 0||n.release==="burn"?s.ascent:o?.kind==="vent"?s.vent:s.burn;return{name:a,detail:s.detail.replace("{name}",a).replace("{part}",r).replace("{distance}",i(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}},cM=Sn.catalog({en:()=>H(()=>import("./ReentryKindMessages_en-BGZgya17.js"),[],import.meta.url).then(u=>u.reentryKindMessages_en),fr:()=>H(()=>import("./ReentryKindMessages_fr-7mer-cdj.js"),[],import.meta.url).then(u=>u.reentryKindMessages_fr),es:()=>H(()=>import("./ReentryKindMessages_es--UxzPNfj.js"),[],import.meta.url).then(u=>u.reentryKindMessages_es),it:()=>H(()=>import("./ReentryKindMessages_it-BBVQXE1M.js"),[],import.meta.url).then(u=>u.reentryKindMessages_it)}),hM=Sn.catalog({en:()=>H(()=>import("./ReentryTypeNames_en-CBu890Bd.js"),[],import.meta.url).then(u=>u.reentryTypeNames_en),fr:()=>H(()=>import("./ReentryTypeNames_fr-BXq89mrz.js"),[],import.meta.url).then(u=>u.reentryTypeNames_fr),es:()=>H(()=>import("./ReentryTypeNames_es-_LnketjJ.js"),[],import.meta.url).then(u=>u.reentryTypeNames_es),it:()=>H(()=>import("./ReentryTypeNames_it-Yfq-TDip.js"),[],import.meta.url).then(u=>u.reentryTypeNames_it)}),lM=u=>({load:t=>hM.load(t).then(e=>({name:e[u]}))}),Zo=(u,t,e,s)=>({id:u,name:u,credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>({key:u,nature:e,messages:lM(t),template:s})}),uM=ke.point("reentryTypes").provide(ke.BUILT_IN,[Zo("meteor","meteor","natural",{distanceKm:150,speedKmS:40,durationS:1,fromAltitudeKm:100,toAltitudeKm:85,fragments:[{id:"main",absoluteMagnitude:0,trainS:.3,sheds:[]}]}),Zo("fireball","fireball","natural",{distanceKm:150,speedKmS:30,durationS:3,fromAltitudeKm:100,toAltitudeKm:60,fragments:[{id:"main",absoluteMagnitude:-6}]}),Zo("satellite","satellite","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-3},{id:"piece-2",lagS:2,absoluteMagnitude:-1.5}]}),Zo("rocket-stage","rocketStage","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-4},{id:"piece-2",lagS:1.5,absoluteMagnitude:-2.5},{id:"piece-3",lagS:3,absoluteMagnitude:-1.5}]}),Zo("capsule","capsule","artificial",{distanceKm:300,speedKmS:7.5,durationS:40,fromAltitudeKm:80,toAltitudeKm:55,fragments:[{id:"main",absoluteMagnitude:-5,sheds:[]}]})]);class mi{static built=new WeakMap;static names=new Map;static namesLanguage;static all(){return uM.map(t=>{let e=mi.built.get(t);return e||mi.built.set(t,e=t.create()),e})}static of(t){return t===void 0?void 0:mi.all().find(e=>e.key===t)}static async load(t){const e=mi.all(),s=await Promise.all(e.map(i=>i.messages.load(t).then(n=>n.name,()=>i.key)));mi.names=new Map(e.map((i,n)=>[i.key,s[n]])),mi.namesLanguage=t}static nameOf(t){return mi.names.get(t)??t}static get language(){return mi.namesLanguage}}const u0={key:"reentries",messages:cM,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>H(async()=>{const{ReentrySimulation:u}=await import("./ReentrySimulation-D0XIfeyt.js");return{ReentrySimulation:u}},__vite__mapDeps([29,4,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({ReentrySimulation:u})=>()=>new u),editor:()=>H(async()=>{const{ReentryEditor:u}=await import("./ReentryEditor-x_C9chQN.js");return{ReentryEditor:u}},__vite__mapDeps([30,1,5,6,23,2,3,24,25,31,4,7,8,9,10]),import.meta.url).then(({ReentryEditor:u})=>(t,e,s)=>new u(t,e,s)),describe:(u,t,{said:e,texts:s})=>{const i=t.detail,n=u.type!==void 0&&mi.language!==void 0?mi.nameOf(u.type):"",a=(u.title?e.read(u.title):"")||u.object?.name||n||s.name,o=i.view.head,r=6371,c=Math.sqrt(r**2+o.distanceKm**2+2*r*o.distanceKm*Math.sin(o.altitudeDeg*Math.PI/180))-r;return{name:(i.view.fragmentId.includes(".")?s.fragment:s.piece).replace("{name}",a).replace("{mag}",i.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(c).toLocaleString()).replace("{distance}",Math.round(o.distanceKm).toLocaleString())}}},dM=Sn.catalog({en:()=>H(()=>import("./AuroraKindMessages_en-D_W4giJa.js"),[],import.meta.url).then(u=>u.auroraKindMessages_en),fr:()=>H(()=>import("./AuroraKindMessages_fr-6IzUVbRH.js"),[],import.meta.url).then(u=>u.auroraKindMessages_fr),es:()=>H(()=>import("./AuroraKindMessages_es-jJ5_ltZq.js"),[],import.meta.url).then(u=>u.auroraKindMessages_es),it:()=>H(()=>import("./AuroraKindMessages_it-DcwuoMkp.js"),[],import.meta.url).then(u=>u.auroraKindMessages_it)}),d0={key:"auroras",messages:dM,pickKind:"aurora",simulation:()=>H(async()=>{const{AuroraSimulation:u}=await import("./AuroraSimulation-Cj8dyvm4.js");return{AuroraSimulation:u}},__vite__mapDeps([32,33,4,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({AuroraSimulation:u})=>()=>new u),editor:()=>H(async()=>{const{AuroraEditor:u}=await import("./AuroraEditor-B0Q9h5C6.js");return{AuroraEditor:u}},__vite__mapDeps([34,1,5,6,23,24,33,2,3,4,7,8,9,10]),import.meta.url).then(({AuroraEditor:u})=>(t,e,s)=>new u(t,e,s)),describe:(u,t,{texts:e,name:s})=>{const i=t.detail,n=a=>a.toLocaleString(void 0,{maximumFractionDigits:1});return{name:s,detail:e.detail.replace("{name}",s).replace("{kp}",n(i.kp)).replace("{green}",n(i.green)).replace("{red}",n(i.red))}}};class Hs{static DEFAULT_HEIGHT_M=2;static DEFAULT_INTENSITY_CD=3e8;static DEFAULT_DIVERGENCE_DEG=1;static DEFAULT_TEMPERATURE_K=5600;static DEFAULT_TILT_DEG=25;static DEFAULT_SPREAD_DEG=60;static DEFAULT_PERIOD_S=12;static RANGE_M=25e3;static CEILING_M=15e3;static MAX_BEAMS=16;static onAt(t,e){return t.filter(s=>(s.fromT===void 0||e>=s.fromT)&&(s.untilT===void 0||e<=s.untilT))}static beamsOf(t){return Math.max(1,Math.min(Hs.MAX_BEAMS,Math.round(t.beams??1)))}static motionOf(t){if(t.motion)return t.motion;const e=Hs.beamsOf(t);return e===4?"cloverleaf":e===1?"sweep":"rotate"}static aimsAt(t,e){const s=Hs.beamsOf(t),i=t.tiltDeg??Hs.DEFAULT_TILT_DEG,n=t.spreadDeg??Hs.DEFAULT_SPREAD_DEG,a=t.azimuthDeg??0,o=Math.max(.1,t.periodS??Hs.DEFAULT_PERIOD_S),r=2*Math.PI*(e/1e3)/o,c=[];for(let h=0;h<s;h++){const l=360*h/s;switch(Hs.motionOf(t)){case"fixed":c.push({tiltDeg:i,azimuthDeg:a+l});break;case"sweep":c.push({tiltDeg:i,azimuthDeg:a+n/2*Math.sin(r-2*Math.PI*h/s)});break;case"rotate":c.push({tiltDeg:i,azimuthDeg:a+l+r*180/Math.PI});break;case"cloverleaf":{const d=r+2*Math.PI*h/s;c.push({tiltDeg:i*Math.abs(Math.cos(2*d)),azimuthDeg:a+d*180/Math.PI});break}}}return c.map(h=>({tiltDeg:h.tiltDeg,azimuthDeg:(h.azimuthDeg%360+360)%360}))}static axisOf(t){const e=t.tiltDeg*Math.PI/180,s=t.azimuthDeg*Math.PI/180;return{east:Math.sin(e)*Math.sin(s),north:Math.sin(e)*Math.cos(s),up:Math.cos(e)}}static fluxLm(t,e){const s=e*Math.PI/180;return t*Math.PI*s*s/(4*Math.LN2)}static illuminanceLux(t,e,s,i=0){const n=e*Math.PI/180;return t*Math.exp(-4*Math.LN2*i*i/(n*n))/Math.max(1,s*s)}static reachM(t,e){let s=0;for(const i of t){const n=ot(i.lat,i.lng,e.lat,e.lng);s=Math.max(s,Math.hypot(n.x,n.z)+Hs.RANGE_M)}return s}static patchOn(t,e){const s=Hs.axisOf(t);if(s.up<=1e-6)return;const i=e/s.up;return{eastM:s.east*i,northM:s.north*i}}}const fM=Sn.catalog({en:()=>H(()=>import("./SearchlightKindMessages_en-CwJDAjsc.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_en),fr:()=>H(()=>import("./SearchlightKindMessages_fr-DsxiUhmK.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_fr),es:()=>H(()=>import("./SearchlightKindMessages_es-CCCgZyTQ.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_es),it:()=>H(()=>import("./SearchlightKindMessages_it-CyWpJL5c.js"),[],import.meta.url).then(u=>u.searchlightKindMessages_it)}),f0={key:"searchlights",messages:fM,pickKind:"searchlight",simulation:()=>H(async()=>{const{SearchlightSystem:u}=await import("./SearchlightSystem-C-qAMIFS.js");return{SearchlightSystem:u}},__vite__mapDeps([35,20,4,21,1,2,3,5,6,7,8,9,10]),import.meta.url).then(({SearchlightSystem:u})=>()=>new u),editor:()=>H(async()=>{const{SearchlightEditor:u}=await import("./SearchlightEditor-Dy-gMDUN.js");return{SearchlightEditor:u}},__vite__mapDeps([36,1,5,6,23,24,2,3,4,7,8,9,10]),import.meta.url).then(({SearchlightEditor:u})=>(t,e,s)=>new u(t,e,s)),reachM:(u,t)=>Hs.reachM(u,t),describe:(u,t,{texts:e,name:s,distance:i})=>{const n=t.detail?.beam??1;return{name:s,detail:e.detail.replace("{name}",s).replace("{beam}",String(n)).replace("{beams}",String(Hs.beamsOf(u))).replace("{intensity}",(u.intensityCd??Hs.DEFAULT_INTENSITY_CD).toExponential(1)).replace("{distance}",i(t.distanceM??0))}}},fu=ke.point("skyEvents").provide(ke.BUILT_IN,[{id:l0.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>l0},{id:h0.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>h0},{id:f0.key,name:"Searchlights",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>f0},{id:u0.key,name:"Re-entries",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>u0},{id:d0.key,name:"Aurorae",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>d0}]);class vn{static built=new WeakMap;static of(t){let e=vn.built.get(t);return e||(e=t.create(),vn.built.set(t,e)),e}static eventsOf(t,e){const s=t?.[e.key];return Array.isArray(s)?s:[]}}class nh{static KEY="cloudDimming";static apply(t,e){const s=e.map(i=>i.mesh.uuid).join(",");t.userData[nh.KEY]!==s&&(t.userData[nh.KEY]=s,t.customProgramCacheKey=()=>`cloud-dimming|${s}`,t.onBeforeCompile=i=>{if(e.length===0)return;i.vertexShader=`varying vec3 dimmedPoint;
|
|
3288
3292
|
`+i.vertexShader.replace("#include <project_vertex>",`#include <project_vertex>
|
|
3289
3293
|
dimmedPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let n=`varying vec3 dimmedPoint;
|
|
3290
3294
|
`,a="";e.forEach((o,r)=>{const c=`dim${r}_`;for(const[h,l]of Object.entries(o.uniforms))i.uniforms[c+h]=l;n+=sp(c),a+=`diffuseColor.a *= ${c}transmissionAt(normalize(dimmedPoint), length(dimmedPoint));
|
|
@@ -4350,7 +4354,7 @@ ${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
4350
4354
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
4351
4355
|
}
|
|
4352
4356
|
`,transparent:!0,depthWrite:!1,side:tn,fog:!1,blending:Fo,blendSrc:Ho,blendDst:Xf})}static wallReflectance(t,e,s){const i=s(t,1,e);return 2*i/(1+i)}static DISCS={uDiscDirection:{value:[new D(0,1,0),new D(0,1,0)]},uDiscCosRadius:{value:[2,2]},uDiscRadiance:{value:[new D,new D]}};static DISC_INDEX={sun:0,moon:1};static setDisc(t,e){const s=ps.DISC_INDEX[t],i=ps.DISCS;if(!e){i.uDiscCosRadius.value[s]=2,i.uDiscRadiance.value[s].set(0,0,0);return}i.uDiscDirection.value[s].set(...e.direction).normalize(),i.uDiscCosRadius.value[s]=Math.cos(e.radiusRad),i.uDiscRadiance.value[s].set(...e.radiance)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return W.respond(e*W.relativeOfResponse(Math.max(t,1e-5)))}}class Ts{static SIZE=64;static MOVE_M=.01;holder=new Jf;cameras=[];faces=[];target=new ye(Ts.SIZE,Ts.SIZE);white=new $s({color:new q(1,1,1),side:tn});scene=new js;cabin;meshes=0;eye=new D;scratch=new D;constructor(){const t=[[new D(1,0,0),new D(0,1,0)],[new D(-1,0,0),new D(0,1,0)],[new D(0,1,0),new D(0,0,1)],[new D(0,-1,0),new D(0,0,-1)],[new D(0,0,1),new D(0,1,0)],[new D(0,0,-1),new D(0,1,0)]];for(const[e,s]of t){const i=new Gc(90,1,.02,20);i.up.copy(s),i.lookAt(e),this.holder.add(i),this.cameras.push(i),this.faces.push(new Uint8Array(Ts.SIZE*Ts.SIZE*4))}this.scene.background=new q(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,s){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const i=this.scratch.copy(s);e.worldToLocal(i);let n=0;e.traverse(a=>{a.isMesh&&n++}),!(e===this.cabin&&n===this.meshes&&i.distanceTo(this.eye)<Ts.MOVE_M)&&(this.cabin=e,this.meshes=n,this.eye.copy(i),this.draw(t,e))}hides(t){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let e=0;e<6;e++){const s=this.cameras[e],i=this.scratch.copy(t).transformDirection(s.matrixWorldInverse);if(i.z>=0)continue;const n=i.x/-i.z,a=i.y/-i.z;if(Math.abs(n)>1||Math.abs(a)>1)continue;const o=Math.min(Ts.SIZE-1,Math.floor((n+1)/2*Ts.SIZE)),r=Math.min(Ts.SIZE-1,Math.floor((a+1)/2*Ts.SIZE));return this.faces[e][(r*Ts.SIZE+o)*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 s=[];e.traverse(a=>{const o=a;if(!o.isMesh||!o.visible||(Array.isArray(o.material)?o.material:[o.material]).every(h=>h instanceof ps))return;const c=new B(o.geometry,this.white);c.matrixAutoUpdate=!1,c.matrix.copy(o.matrixWorld),c.matrixWorld.copy(o.matrixWorld),s.push(c)});for(const a of s)this.scene.add(a);const i=t.getRenderTarget(),n=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let a=0;a<6;a++){const o=this.cameras[a];o.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,o),oh.now(t,this.target,0,0,Ts.SIZE,Ts.SIZE,this.faces[a])}t.setRenderTarget(i),t.shadowMap.autoUpdate=n;for(const a of s)a.removeFromParent()}}const Jh="https://ufoathome.org/models/index.json";class Ir{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??nv()}async entries(t){const e=await this.load();return t?e.filter(s=>[s.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(`
|
|
4353
|
-
`);let e=Ir.shared.get(t);return e||(e=this.fetchFirstAvailable(),Ir.shared.set(t,e),e.then(s=>{s.length===0&&Ir.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 s=await e.json();return Array.isArray(s?.models)?s.models.map(({file:i,...n})=>({...n,url:new URL(i,t).href})):void 0}catch{return}}}function nv(){const u=`?v=${encodeURIComponent("0.204.
|
|
4357
|
+
`);let e=Ir.shared.get(t);return e||(e=this.fetchFirstAvailable(),Ir.shared.set(t,e),e.then(s=>{s.length===0&&Ir.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 s=await e.json();return Array.isArray(s?.models)?s.models.map(({file:i,...n})=>({...n,url:new URL(i,t).href})):void 0}catch{return}}}function nv(){const u=`?v=${encodeURIComponent("0.204.2")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==Jh?[t,Jh]:[Jh]).map(e=>e+u)}const av=ke.point("decorModels").provide(ke.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 Ir}]);class gp{constructor(t,e=av){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(s=>s.id===this.preferredId)??this.sources[0];return(t?[t,...this.sources.filter(s=>s!==t)]:[]).map(s=>{let i=this.built.get(s);return i||(i=s.create(),this.built.set(s,i)),i})}entries(t){const e=this.catalogues()[0];return e?e.entries(t):Promise.resolve([])}async entry(t){for(const e of this.catalogues()){const s=await e.entry(t).catch(()=>{});if(s)return s}}async moduleOf(t){const e=ke.point("decorModels");for(const s of this.sources){const i=e.ownerOf(s.id);if(!(i===void 0||i===ke.BUILT_IN)&&await this.catalogueOf(s).entry(t).catch(()=>{}))return i}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function Qh(u){const{GLTFLoader:t}=await H(async()=>{const{GLTFLoader:s}=await import("./GLTFLoader-s3EU9qS0.js");return{GLTFLoader:s}},__vite__mapDeps([37,4,1,2,3,5,6,7,8,9,10]),import.meta.url),e=new t;return new Promise((s,i)=>{e.load(u,n=>s(Object.assign(n.scene,{animations:n.animations})),void 0,n=>i(new Error(`Could not load 3D model ${u}: ${n instanceof Error?n.message:String(n)}`)))})}class Gs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new B(new hi(2,2),new Lt({uniforms:{uColor:{value:new q(0,0,0)},uRadius:{value:1}},vertexShader:Gs.VERTEX,fragmentShader:Gs.FRAGMENT,transparent:!0,depthWrite:!1,blending:rs,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,s){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(s[0],s[1],s[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,s,i){const n=Math.max(t,i*Gs.MIN_ANGLE_RAD),a=Gs.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:s*Math.min(Gs.MAX_SHARE,e/a)}}static conserving(t){return Math.sqrt(t/(Gs.MAX_SHARE*Gs.FILL*Math.PI))}static VERTEX=`
|
|
4354
4358
|
uniform float uRadius;
|
|
4355
4359
|
varying vec2 vOffset;
|
|
4356
4360
|
void main() {
|
|
@@ -4926,7 +4930,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
4926
4930
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
4927
4931
|
gl_FragColor = vec4(light, 1.0);
|
|
4928
4932
|
}
|
|
4929
|
-
`,transparent:!0,blending:rs,depthWrite:!1,side:Ai,fog:!1});this.object=new B(new Ge(qu.RADIUS,128,32,0,Math.PI*2,0,At.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let s=0;s<At.STEPS;s++){for(let i=0;i<3;i++)this.texels[s*4+i]=Xe.toHalfFloat(Math.min(e[s*3+i],6e4));this.texels[s*4+3]=Xe.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class ch{constructor(t){this.generator=t}static SIZE=128;target=new Cl(ch.SIZE,{type:oe,generateMipmaps:!0,minFilter:Go,magFilter:Xt});camera=new Zf(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,s,i=[]){const n=t.shadowMap.autoUpdate;let a=!1;e.traverse(r=>{const c=r;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(a=!0)}),t.shadowMap.autoUpdate=a?n:!1;const o=i.map(r=>r.visible);for(const r of i)r.visible=!1;this.camera.position.copy(s),this.camera.update(t,e),i.forEach((r,c)=>{r.visible=o[c]}),t.shadowMap.autoUpdate=n,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class ds{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){ds.install(),this.generator=new Zp(t),this.eye=new ch(this.generator)}static decor;refresh(t,e,s,i,n,a,o,r=[],c,h=ds.REFRESH_MS){for(const g of[...this.probes.keys()])i.some(M=>M.id===g&&M.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const l=[{probe:this.eye}];for(const g of i){if(!g.shiny)continue;let M=this.probes.get(g.id);M||(M=new ch(this.generator),this.probes.set(g.id,M)),l.push({probe:M,reflector:g})}const d=performance.now(),f=()=>l.filter(({probe:g})=>g.capturedVersion!==o),m=f().filter(({probe:g})=>d-g.capturedAtMs>=h);if(m.length>0){const g=m.reduce((M,v)=>v.probe.capturedAtMs<M.probe.capturedAtMs?v:M);if(g.reflector){const M=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,M,[g.reflector.holder,...n]),ds.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,s,[...n,...r]),c?.(g.probe.sharp),ds.decor=g.probe.filtered;for(const M of a)ds.reflectOn(M,g.probe);for(const M of i)M.shiny||ds.reflectOn(M.holder,g.probe)}g.probe.capturedVersion=o}const p=f();if(p.length!==0)return Math.max(16,Math.min(...p.map(({probe:g})=>h-(d-g.capturedAtMs))))}scratch=new D;static reflectOn(t,e={filtered:ds.decor}){t.traverse(s=>{const i=s.material;for(const n of Array.isArray(i)?i:i?[i]:[])n instanceof ps?e.sharp&&n.setSurroundings(e.sharp):n instanceof un&&e.filtered&&n.envMap!==e.filtered&&(n.envMap=e.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(ds.installed)return;ds.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!yi.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}yi.lights_fragment_maps=yi.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const yp=0,cv=1,hv=2,k0=2,tl=1.25,L0=1,gs=32,Fe=gs/4,wp=65535,_c=Math.pow(2,-24),ju=Symbol("SKIP_GENERATION"),bp={strategy:yp,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[ju]:!1};function ve(u,t,e){return e.min.x=t[u],e.min.y=t[u+1],e.min.z=t[u+2],e.max.x=t[u+3],e.max.y=t[u+4],e.max.z=t[u+5],e}function wu(u){let t=-1,e=-1/0;for(let s=0;s<3;s++){const i=u[s+3]-u[s];i>e&&(e=i,t=s)}return t}function N0(u,t){t.set(u)}function C0(u,t,e){let s,i;for(let n=0;n<3;n++){const a=n+3;s=u[n],i=t[n],e[n]=s<i?s:i,s=u[a],i=t[a],e[a]=s>i?s:i}}function ic(u,t,e){for(let s=0;s<3;s++){const i=t[u+2*s],n=t[u+2*s+1],a=i-n,o=i+n;a<e[s]&&(e[s]=a),o>e[s+3]&&(e[s+3]=o)}}function er(u){const t=u[3]-u[0],e=u[4]-u[1],s=u[5]-u[2];return 2*(t*e+e*s+s*t)}function Ae(u,t){return t[u+15]===wp}function Ze(u,t){return t[u+6]}function Ms(u,t){return t[u+14]}function He(u){return u+Fe}function Ue(u,t){const e=t[u+6];return u+e*Fe}function Zu(u,t){return t[u+7]}function el(u,t,e,s,i){let n=1/0,a=1/0,o=1/0,r=-1/0,c=-1/0,h=-1/0,l=1/0,d=1/0,f=1/0,m=-1/0,p=-1/0,g=-1/0;const M=u.offset||0;for(let v=(t-M)*6,y=(t+e-M)*6;v<y;v+=6){const w=u[v+0],b=u[v+1],E=w-b,A=w+b;E<n&&(n=E),A>r&&(r=A),w<l&&(l=w),w>m&&(m=w);const S=u[v+2],x=u[v+3],T=S-x,I=S+x;T<a&&(a=T),I>c&&(c=I),S<d&&(d=S),S>p&&(p=S);const R=u[v+4],O=u[v+5],P=R-O,k=R+O;P<o&&(o=P),k>h&&(h=k),R<f&&(f=R),R>g&&(g=R)}s[0]=n,s[1]=a,s[2]=o,s[3]=r,s[4]=c,s[5]=h,i[0]=l,i[1]=d,i[2]=f,i[3]=m,i[4]=p,i[5]=g}const hn=32,lv=(u,t)=>u.candidate-t.candidate,Pn=new Array(hn).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),nc=new Float32Array(6);function uv(u,t,e,s,i,n){let a=-1,o=0;if(n===yp)a=wu(t),a!==-1&&(o=(t[a]+t[a+3])/2);else if(n===cv)a=wu(u),a!==-1&&(o=dv(e,s,i,a));else if(n===hv){const r=er(u);let c=tl*i;const h=e.offset||0,l=(s-h)*6,d=(s+i-h)*6;for(let f=0;f<3;f++){const m=t[f],M=(t[f+3]-m)/hn;if(i<hn/4){const v=[...Pn];v.length=i;let y=0;for(let b=l;b<d;b+=6,y++){const E=v[y];E.candidate=e[b+2*f],E.count=0;const{bounds:A,leftCacheBounds:S,rightCacheBounds:x}=E;for(let T=0;T<3;T++)x[T]=1/0,x[T+3]=-1/0,S[T]=1/0,S[T+3]=-1/0,A[T]=1/0,A[T+3]=-1/0;ic(b,e,A)}v.sort(lv);let w=i;for(let b=0;b<w;b++){const E=v[b];for(;b+1<w&&v[b+1].candidate===E.candidate;)v.splice(b+1,1),w--}for(let b=l;b<d;b+=6){const E=e[b+2*f];for(let A=0;A<w;A++){const S=v[A];E>=S.candidate?ic(b,e,S.rightCacheBounds):(ic(b,e,S.leftCacheBounds),S.count++)}}for(let b=0;b<w;b++){const E=v[b],A=E.count,S=i-E.count,x=E.leftCacheBounds,T=E.rightCacheBounds;let I=0;A!==0&&(I=er(x)/r);let R=0;S!==0&&(R=er(T)/r);const O=L0+tl*(I*A+R*S);O<c&&(a=f,c=O,o=E.candidate)}}else{for(let w=0;w<hn;w++){const b=Pn[w];b.count=0,b.candidate=m+M+w*M;const E=b.bounds;for(let A=0;A<3;A++)E[A]=1/0,E[A+3]=-1/0}for(let w=l;w<d;w+=6){let A=~~((e[w+2*f]-m)/M);A>=hn&&(A=hn-1);const S=Pn[A];S.count++,ic(w,e,S.bounds)}const v=Pn[hn-1];N0(v.bounds,v.rightCacheBounds);for(let w=hn-2;w>=0;w--){const b=Pn[w],E=Pn[w+1];C0(b.bounds,E.rightCacheBounds,b.rightCacheBounds)}let y=0;for(let w=0;w<hn-1;w++){const b=Pn[w],E=b.count,A=b.bounds,x=Pn[w+1].rightCacheBounds;E!==0&&(y===0?N0(A,nc):C0(A,nc,nc)),y+=E;let T=0,I=0;y!==0&&(T=er(nc)/r);const R=i-y;R!==0&&(I=er(x)/r);const O=L0+tl*(T*y+I*R);O<c&&(a=f,c=O,o=b.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:a,pos:o}}function dv(u,t,e,s){let i=0;const n=u.offset;for(let a=t,o=t+e;a<o;a++)i+=u[(a-n)*6+s*2];return i/e}class sl{constructor(){this.boundingData=new Float32Array(6)}}function fv(u,t,e,s,i,n){let a=s,o=s+i-1;const r=n.pos,c=n.axis*2,h=e.offset||0;for(;;){for(;a<=o&&e[(a-h)*6+c]<r;)a++;for(;a<=o&&e[(o-h)*6+c]>=r;)o--;if(a<o){for(let l=0;l<t;l++){let d=u[a*t+l];u[a*t+l]=u[o*t+l],u[o*t+l]=d}for(let l=0;l<6;l++){const d=a-h,f=o-h,m=e[d*6+l];e[d*6+l]=e[f*6+l],e[f*6+l]=m}a++,o--}else return a}}let Ep,zc,bu,Ap;const mv=Math.pow(2,32);function Eu(u){return"count"in u?1:1+Eu(u.left)+Eu(u.right)}function pv(u,t,e){return Ep=new Float32Array(e),zc=new Uint32Array(e),bu=new Uint16Array(e),Ap=new Uint8Array(e),Au(u,t)}function Au(u,t){const e=u/4,s=u/2,i="count"in t,n=t.boundingData;for(let a=0;a<6;a++)Ep[e+a]=n[a];if(i)return t.buffer?(Ap.set(new Uint8Array(t.buffer),u),u+t.buffer.byteLength):(zc[e+6]=t.offset,bu[s+14]=t.count,bu[s+15]=wp,u+gs);{const{left:a,right:o,splitAxis:r}=t,c=u+gs;let h=Au(c,a);const l=u/gs,f=h/gs-l;if(f>mv)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return zc[e+6]=f,zc[e+7]=r,Au(h,o)}}function gv(u,t,e,s,i,n){const{maxDepth:a,verbose:o,targetLeafSize:r,_strictLeafSize:c=1/0,strategy:h,onProgress:l}=i,d=u.primitiveBuffer,f=u.primitiveBufferStride,m=new Float32Array(6);let p=!1;const g=new sl;return el(t,e,s,g.boundingData,m),v(g,e,s,m),g;function M(y){l&&l((y-n.offset)/n.count)}function v(y,w,b,E=null,A=0){!p&&A>=a&&(p=!0,o&&console.warn(`BVH: Max depth of ${a} reached when generating BVH. Consider increasing maxDepth.`));const S=b>c;if(b<=r&&!S||A>=a)return M(w+b),y.offset=w,y.count=b,y;const x=uv(y.boundingData,E,t,w,b,h);let T=x.axis===-1?-1:fv(d,f,t,w,b,x);if(x.axis===-1||T===w||T===w+b){if(!S)return M(w+b),y.offset=w,y.count=b,y;x.axis=Math.max(0,wu(y.boundingData)),T=w+Math.max(1,Math.floor(b/2))}y.splitAxis=x.axis;const I=new sl,R=w,O=T-w;y.left=I,el(t,R,O,I.boundingData,m),v(I,R,O,m,A+1);const P=new sl,k=T,_=b-O;return y.right=P,el(t,k,_,P.boundingData,m),v(P,k,_,m,A+1),y}}function Mv(u,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=u.getRootRanges(t.range),i=s[0],n=s[s.length-1],a={offset:i.offset,count:n.offset+n.count-i.offset},o=new Float32Array(6*a.count);o.offset=a.offset,u.computePrimitiveBounds(a.offset,a.count,o),u._roots=s.map(r=>{const c=gv(u,o,r.offset,r.count,t,a),h=Eu(c),l=new e(gs*h);return pv(0,c,l),l})}class Ju{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class vv{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=s=>{e&&t.push(e),e=s,this.float32Array=new Float32Array(s),this.uint16Array=new Uint16Array(s),this.uint32Array=new Uint32Array(s)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const re=new vv;let Xn,xo;const Ba=[],ac=new Ju(()=>new ee);function yv(u,t,e,s,i,n){Xn=ac.getPrimitive(),xo=ac.getPrimitive(),Ba.push(Xn,xo),re.setBuffer(u._roots[t]);const a=Su(0,u.geometry,e,s,i,n);re.clearBuffer(),ac.releasePrimitive(Xn),ac.releasePrimitive(xo),Ba.pop(),Ba.pop();const o=Ba.length;return o>0&&(xo=Ba[o-1],Xn=Ba[o-2]),a}function Su(u,t,e,s,i=null,n=0,a=0){const{float32Array:o,uint16Array:r,uint32Array:c}=re;let h=u*2;if(Ae(h,r)){const d=Ze(u,c),f=Ms(h,r);return ve(u,o,Xn),s(d,f,!1,a,n+u/Fe,Xn)}else{let T=function(R){const{uint16Array:O,uint32Array:P}=re;let k=R*2;for(;!Ae(k,O);)R=He(R),k=R*2;return Ze(R,P)},I=function(R){const{uint16Array:O,uint32Array:P}=re;let k=R*2;for(;!Ae(k,O);)R=Ue(R,P),k=R*2;return Ze(R,P)+Ms(k,O)};const d=He(u),f=Ue(u,c);let m=d,p=f,g,M,v,y;if(i&&(v=Xn,y=xo,ve(m,o,v),ve(p,o,y),g=i(v),M=i(y),M<g)){m=f,p=d;const R=g;g=M,M=R,v=y}v||(v=Xn,ve(m,o,v));const w=Ae(m*2,r),b=e(v,w,g,a+1,n+m/Fe);let E;if(b===k0){const R=T(m),P=I(m)-R;E=s(R,P,!0,a+1,n+m/Fe,v)}else E=b&&Su(m,t,e,s,i,n,a+1);if(E)return!0;y=xo,ve(p,o,y);const A=Ae(p*2,r),S=e(y,A,M,a+1,n+p/Fe);let x;if(S===k0){const R=T(p),P=I(p)-R;x=s(R,P,!0,a+1,n+p/Fe,y)}else x=S&&Su(p,t,e,s,i,n,a+1);return!!x}}const Or=new re.constructor,hh=new re.constructor,Un=new Ju(()=>new ee),Va=new ee,Wa=new ee,il=new ee,nl=new ee;let al=!1;function wv(u,t,e,s){if(al)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");al=!0;const i=u._roots,n=t._roots;let a,o=0,r=0;const c=new Oe().copy(e).invert();for(let h=0,l=i.length;h<l;h++){Or.setBuffer(i[h]),r=0;const d=Un.getPrimitive();ve(0,Or.float32Array,d),d.applyMatrix4(c);for(let f=0,m=n.length;f<m&&(hh.setBuffer(n[f]),a=ui(0,0,e,c,s,o,r,0,0,d),hh.clearBuffer(),r+=n[f].byteLength/gs,!a);f++);if(Un.releasePrimitive(d),Or.clearBuffer(),o+=i[h].byteLength/gs,a)break}return al=!1,a}function ui(u,t,e,s,i,n=0,a=0,o=0,r=0,c=null,h=!1){let l,d;h?(l=hh,d=Or):(l=Or,d=hh);const f=l.float32Array,m=l.uint32Array,p=l.uint16Array,g=d.float32Array,M=d.uint32Array,v=d.uint16Array,y=u*2,w=t*2,b=Ae(y,p),E=Ae(w,v);let A=!1;if(E&&b)h?A=i(Ze(t,M),Ms(t*2,v),Ze(u,m),Ms(u*2,p),r,a+t/Fe,o,n+u/Fe):A=i(Ze(u,m),Ms(u*2,p),Ze(t,M),Ms(t*2,v),o,n+u/Fe,r,a+t/Fe);else if(E){const S=Un.getPrimitive();ve(t,g,S),S.applyMatrix4(e);const x=He(u),T=Ue(u,m);ve(x,f,Va),ve(T,f,Wa);const I=S.intersectsBox(Va),R=S.intersectsBox(Wa);A=I&&ui(t,x,s,e,i,a,n,r,o+1,S,!h)||R&&ui(t,T,s,e,i,a,n,r,o+1,S,!h),Un.releasePrimitive(S)}else{const S=He(t),x=Ue(t,M);ve(S,g,il),ve(x,g,nl);const T=c.intersectsBox(il),I=c.intersectsBox(nl);if(T&&I)A=ui(u,S,e,s,i,n,a,o,r+1,c,h)||ui(u,x,e,s,i,n,a,o,r+1,c,h);else if(T)if(b)A=ui(u,S,e,s,i,n,a,o,r+1,c,h);else{const R=Un.getPrimitive();R.copy(il).applyMatrix4(e);const O=He(u),P=Ue(u,m);ve(O,f,Va),ve(P,f,Wa);const k=R.intersectsBox(Va),_=R.intersectsBox(Wa);A=k&&ui(S,O,s,e,i,a,n,r,o+1,R,!h)||_&&ui(S,P,s,e,i,a,n,r,o+1,R,!h),Un.releasePrimitive(R)}else if(I)if(b)A=ui(u,x,e,s,i,n,a,o,r+1,c,h);else{const R=Un.getPrimitive();R.copy(nl).applyMatrix4(e);const O=He(u),P=Ue(u,m);ve(O,f,Va),ve(P,f,Wa);const k=R.intersectsBox(Va),_=R.intersectsBox(Wa);A=k&&ui(x,O,s,e,i,a,n,r,o+1,R,!h)||_&&ui(x,P,s,e,i,a,n,r,o+1,R,!h),Un.releasePrimitive(R)}}return A}const ol=new class{constructor(){let u=null,t=null,e=null,s=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,a)=>{if(s)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=a,this.buffer=u=n._roots[a],this.uint16Array=e=new Uint16Array(u),this.uint32Array=t=new Uint32Array(u)},this.reset=()=>{this.root=null,this.buffer=u=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=n=>{let a=n*2;for(;!Ae(a,e);)n=He(n),a=n*2;return Ze(n,t)},this.getRangeEnd=n=>{let a=n*2;for(;!Ae(a,e);)n=Ue(n,t),a=n*2;return Ze(n,t)+Ms(a,e)};const i=(n,a,o)=>{const r=a*2,c=Ae(r,e);if(!n(o,c,a)&&!c){const l=He(a),d=Ue(a,t);i(n,l,o+1),i(n,d,o+1)}};this.traverseBuffer=n=>{if(s)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");s=!0;try{i(n,0,0)}finally{s=!1}},this.traverse=n=>{this.traverseBuffer((a,o,r)=>{if(o){const c=r*2,h=t[r+6],l=e[c+14];return n(a,o,new Float32Array(u,r*4,6),h,l)}else{const c=Zu(r,t);return n(a,o,new Float32Array(u,r*4,6),c)}})}}},_0=new ee,Ka=new Float32Array(6);class bv{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...bp,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),Mv(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,s,i){let n=1/0,a=1/0,o=1/0,r=-1/0,c=-1/0,h=-1/0;for(let l=t,d=t+e;l<d;l++){this.writePrimitiveBounds(l,Ka,0);const[f,m,p,g,M,v]=Ka;f<n&&(n=f),g>r&&(r=g),m<a&&(a=m),M>c&&(c=M),p<o&&(o=p),v>h&&(h=v)}return s[i+0]=n,s[i+1]=a,s[i+2]=o,s[i+3]=r,s[i+4]=c,s[i+5]=h,s}computePrimitiveBounds(t,e,s){const i=s.offset||0;for(let n=t,a=t+e;n<a;n++){this.writePrimitiveBounds(n,Ka,0);const[o,r,c,h,l,d]=Ka,f=(o+h)/2,m=(r+l)/2,p=(c+d)/2,g=(h-o)/2,M=(l-r)/2,v=(d-c)/2,y=(n-i)*6;s[y+0]=f,s[y+1]=g+(Math.abs(f)+g)*_c,s[y+2]=m,s[y+3]=M+(Math.abs(m)+M)*_c,s[y+4]=p,s[y+5]=v+(Math.abs(p)+v)*_c}return s}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let s=0,i=e.length;s<i;s++)e[s]+=t;else{const s=this._roots;for(let i=0;i<s.length;i++){const n=s[i],a=new Uint32Array(n),o=new Uint16Array(n),r=n.byteLength/gs;for(let c=0;c<r;c++){const h=Fe*c,l=2*h;Ae(l,o)&&(a[h+6]+=t)}}}}traverse(t,e=0){ol.setBVH(this,e),ol.traverse(t),ol.reset()}refit(){const t=this._roots;for(let e=0,s=t.length;e<s;e++){const i=t[e],n=new Uint32Array(i),a=new Uint16Array(i),o=new Float32Array(i),r=i.byteLength/gs;for(let c=r-1;c>=0;c--){const h=c*Fe,l=h*2;if(Ae(l,a)){const f=Ze(h,n),m=Ms(l,a);this.writePrimitiveRangeBounds(f,m,Ka,0),o.set(Ka,h)}else{const f=He(h),m=Ue(h,n);for(let p=0;p<3;p++){const g=o[f+p],M=o[f+p+3],v=o[m+p],y=o[m+p+3];o[h+p]=g<v?g:v,o[h+p+3]=M>y?M:y}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(s=>{ve(0,new Float32Array(s),_0),t.union(_0)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:s,intersectsRange:i,intersectsPrimitive:n,scratchPrimitive:a,iterate:o}=t;if(i&&n){const l=i;i=(d,f,m,p,g)=>l(d,f,m,p,g)?!0:o(d,f,this,n,m,p,a)}else i||(n?i=(l,d,f,m)=>o(l,d,this,n,f,m,a):i=(l,d,f)=>f);let r=!1,c=0;const h=this._roots;for(let l=0,d=h.length;l<d;l++){const f=h[l];if(r=yv(this,l,s,i,e,c),r)break;c+=f.byteLength/gs}return r}bvhcast(t,e,s){let{intersectsRanges:i}=s;return wv(this,t,e,i)}}function Ev(){return typeof SharedArrayBuffer<"u"}function Qu(u){return u.index?u.index.count:u.attributes.position.count}function Rh(u){return Qu(u)/3}function Av(u,t=ArrayBuffer){return u>65535?new Uint32Array(new t(4*u)):new Uint16Array(new t(2*u))}function Sv(u,t){if(!u.index){const e=u.attributes.position.count,s=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=Av(e,s);u.setIndex(new Ot(i,1));for(let n=0;n<e;n++)i[n]=n}}function xv(u,t,e){const s=Qu(u)/e,i=t||u.drawRange,n=i.start/e,a=(i.start+i.count)/e,o=Math.max(0,n),r=Math.min(s,a)-o;return{offset:Math.floor(o),count:Math.floor(r)}}function Tv(u,t){return u.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function z0(u,t,e){const s=xv(u,t,e),i=Tv(u,e);if(!i.length)return[s];const n=[],a=s.offset,o=s.offset+s.count,r=Qu(u)/e,c=[];for(const d of i){const{offset:f,count:m}=d,p=f,g=isFinite(m)?m:r-f,M=f+g;p<o&&M>a&&(c.push({pos:Math.max(a,p),isStart:!0}),c.push({pos:Math.min(o,M),isStart:!1}))}c.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,l=null;for(const d of c){const f=d.pos;h!==0&&f!==l&&n.push({offset:l,count:f-l}),h+=d.isStart?1:-1,l=f}return n}function Dv(u,t){const e=u[u.length-1],s=e.offset+e.count>2**16,i=u.reduce((c,h)=>c+h.count,0),n=s?4:2,a=t?new SharedArrayBuffer(i*n):new ArrayBuffer(i*n),o=s?new Uint32Array(a):new Uint16Array(a);let r=0;for(let c=0;c<u.length;c++){const{offset:h,count:l}=u[c];for(let d=0;d<l;d++)o[r+d]=h+d;r+=l}return o}class Iv extends bv{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Ev())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?s=>this._indirectBuffer[s]:s=>s,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...bp,...e},e[ju]||this.init(e)}init(t){const{geometry:e,primitiveStride:s}=this;if(t.indirect){const i=z0(e,t.range,s),n=Dv(i,t.useSharedArrayBuffer);this._indirectBuffer=n}else Sv(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new ee))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:z0(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class An{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let s=1/0,i=-1/0;for(let n=0,a=t.length;n<a;n++){const r=t[n][e];s=r<s?r:s,i=r>i?r:i}this.min=s,this.max=i}setFromPoints(t,e){let s=1/0,i=-1/0;for(let n=0,a=e.length;n<a;n++){const o=e[n],r=t.dot(o);s=r<s?r:s,i=r>i?r:i}this.min=s,this.max=i}isSeparated(t){return this.min>t.max||t.min>this.max}}An.prototype.setFromBox=(function(){const u=new D;return function(e,s){const i=s.min,n=s.max;let a=1/0,o=-1/0;for(let r=0;r<=1;r++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){u.x=i.x*r+n.x*(1-r),u.y=i.y*c+n.y*(1-c),u.z=i.z*h+n.z*(1-h);const l=e.dot(u);a=Math.min(l,a),o=Math.max(l,o)}this.min=a,this.max=o}})();const Rv=(function(){const u=new D,t=new D,e=new D;return function(i,n,a){const o=i.start,r=u,c=n.start,h=t;e.subVectors(o,c),u.subVectors(i.end,i.start),t.subVectors(n.end,n.start);const l=e.dot(h),d=h.dot(r),f=h.dot(h),m=e.dot(r),g=r.dot(r)*f-d*d;let M,v;g!==0?M=(l*d-m*f)/g:M=0,v=(l+M*d)/f,a.x=M,a.y=v}})(),td=(function(){const u=new ht,t=new D,e=new D;return function(i,n,a,o){Rv(i,n,u);let r=u.x,c=u.y;if(r>=0&&r<=1&&c>=0&&c<=1){i.at(r,a),n.at(c,o);return}else if(r>=0&&r<=1){c<0?n.at(0,o):n.at(1,o),i.closestPointToPoint(o,!0,a);return}else if(c>=0&&c<=1){r<0?i.at(0,a):i.at(1,a),n.closestPointToPoint(a,!0,o);return}else{let h;r<0?h=i.start:h=i.end;let l;c<0?l=n.start:l=n.end;const d=t,f=e;if(i.closestPointToPoint(l,!0,t),n.closestPointToPoint(h,!0,e),d.distanceToSquared(l)<=f.distanceToSquared(h)){a.copy(d),o.copy(l);return}else{a.copy(h),o.copy(f);return}}}})(),Ov=(function(){const u=new D,t=new D,e=new yh,s=new bn;return function(n,a){const{radius:o,center:r}=n,{a:c,b:h,c:l}=a;if(s.start=c,s.end=h,s.closestPointToPoint(r,!0,u).distanceTo(r)<=o||(s.start=c,s.end=l,s.closestPointToPoint(r,!0,u).distanceTo(r)<=o)||(s.start=h,s.end=l,s.closestPointToPoint(r,!0,u).distanceTo(r)<=o))return!0;const p=a.getPlane(e);if(Math.abs(p.distanceToPoint(r))<=o){const M=p.projectPoint(r,t);if(a.containsPoint(M))return!0}return!1}})(),Pv=["x","y","z"],mn=1e-15,F0=mn*mn;function Zs(u){return Math.abs(u)<mn}class Ei extends eo{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new D),this.satBounds=new Array(4).fill().map(()=>new An),this.points=[this.a,this.b,this.c],this.plane=new yh,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new bn,this.needsUpdate=!0}intersectsSphere(t){return Ov(t,this)}update(){const t=this.a,e=this.b,s=this.c,i=this.points,n=this.satAxes,a=this.satBounds,o=n[0],r=a[0];this.getNormal(o),r.setFromPoints(o,i);const c=n[1],h=a[1];c.subVectors(t,e),h.setFromPoints(c,i);const l=n[2],d=a[2];l.subVectors(e,s),d.setFromPoints(l,i);const f=n[3],m=a[3];f.subVectors(s,t),m.setFromPoints(f,i);const p=c.length(),g=l.length(),M=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,p<mn?g<mn||M<mn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(s)):g<mn?M<mn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):M<mn&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(s),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}Ei.prototype.closestPointToSegment=(function(){const u=new D,t=new D,e=new bn;return function(i,n=null,a=null){const{start:o,end:r}=i,c=this.points;let h,l=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(c[d]),e.end.copy(c[f]),td(e,i,u,t),h=u.distanceToSquared(t),h<l&&(l=h,n&&n.copy(u),a&&a.copy(t))}return this.closestPointToPoint(o,u),h=o.distanceToSquared(u),h<l&&(l=h,n&&n.copy(u),a&&a.copy(o)),this.closestPointToPoint(r,u),h=r.distanceToSquared(u),h<l&&(l=h,n&&n.copy(u),a&&a.copy(r)),Math.sqrt(l)}})();Ei.prototype.intersectsTriangle=(function(){const u=new Ei,t=new An,e=new An,s=new D,i=new D,n=new D,a=new D,o=new bn,r=new bn,c=new D,h=new ht,l=new ht;function d(y,w,b,E){const A=s;!y.isDegenerateIntoPoint&&!y.isDegenerateIntoSegment?A.copy(y.plane.normal):A.copy(w.plane.normal);const S=y.satBounds,x=y.satAxes;for(let R=1;R<4;R++){const O=S[R],P=x[R];if(t.setFromPoints(P,w.points),O.isSeparated(t)||(a.copy(A).cross(P),t.setFromPoints(a,y.points),e.setFromPoints(a,w.points),t.isSeparated(e)))return!1}const T=w.satBounds,I=w.satAxes;for(let R=1;R<4;R++){const O=T[R],P=I[R];if(t.setFromPoints(P,y.points),O.isSeparated(t)||(a.crossVectors(A,P),t.setFromPoints(a,y.points),e.setFromPoints(a,w.points),t.isSeparated(e)))return!1}return b&&(E||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),b.start.set(0,0,0),b.end.set(0,0,0)),!0}function f(y,w,b,E,A,S,x,T,I,R,O){let P=x/(x-T);R.x=E+(A-E)*P,O.start.subVectors(w,y).multiplyScalar(P).add(y),P=x/(x-I),R.y=E+(S-E)*P,O.end.subVectors(b,y).multiplyScalar(P).add(y)}function m(y,w,b,E,A,S,x,T,I,R,O){if(A>0)f(y.c,y.a,y.b,E,w,b,I,x,T,R,O);else if(S>0)f(y.b,y.a,y.c,b,w,E,T,x,I,R,O);else if(T*I>0||x!=0)f(y.a,y.b,y.c,w,b,E,x,T,I,R,O);else if(T!=0)f(y.b,y.a,y.c,b,w,E,T,x,I,R,O);else if(I!=0)f(y.c,y.a,y.b,E,w,b,I,x,T,R,O);else return!0;return!1}function p(y,w,b,E){const A=w.degenerateSegment,S=y.plane.distanceToPoint(A.start),x=y.plane.distanceToPoint(A.end);return Zs(S)?Zs(x)?d(y,w,b,E):(b&&(b.start.copy(A.start),b.end.copy(A.start)),y.containsPoint(A.start)):Zs(x)?(b&&(b.start.copy(A.end),b.end.copy(A.end)),y.containsPoint(A.end)):y.plane.intersectLine(A,s)!=null?(b&&(b.start.copy(s),b.end.copy(s)),y.containsPoint(s)):!1}function g(y,w,b){const E=w.a;return Zs(y.plane.distanceToPoint(E))&&y.containsPoint(E)?(b&&(b.start.copy(E),b.end.copy(E)),!0):!1}function M(y,w,b){const E=y.degenerateSegment,A=w.a;return E.closestPointToPoint(A,!0,s),A.distanceToSquared(s)<F0?(b&&(b.start.copy(A),b.end.copy(A)),!0):!1}function v(y,w,b,E){if(y.isDegenerateIntoSegment)if(w.isDegenerateIntoSegment){const A=y.degenerateSegment,S=w.degenerateSegment,x=i,T=n;A.delta(x),S.delta(T);const I=s.subVectors(S.start,A.start),R=x.x*T.y-x.y*T.x;if(Zs(R))return!1;const O=(I.x*T.y-I.y*T.x)/R,P=-(x.x*I.y-x.y*I.x)/R;if(O<0||O>1||P<0||P>1)return!1;const k=A.start.z+x.z*O,_=S.start.z+T.z*P;return Zs(k-_)?(b&&(b.start.copy(A.start).addScaledVector(x,O),b.end.copy(A.start).addScaledVector(x,O)),!0):!1}else return w.isDegenerateIntoPoint?M(y,w,b):p(w,y,b,E);else{if(y.isDegenerateIntoPoint)return w.isDegenerateIntoPoint?w.a.distanceToSquared(y.a)<F0?(b&&(b.start.copy(y.a),b.end.copy(y.a)),!0):!1:w.isDegenerateIntoSegment?M(w,y,b):g(w,y,b);if(w.isDegenerateIntoPoint)return g(y,w,b);if(w.isDegenerateIntoSegment)return p(y,w,b,E)}}return function(w,b=null,E=!1){this.needsUpdate&&this.update(),w.isExtendedTriangle?w.needsUpdate&&w.update():(u.copy(w),u.update(),w=u);const A=v(this,w,b,E);if(A!==void 0)return A;const S=this.plane,x=w.plane;let T=x.distanceToPoint(this.a),I=x.distanceToPoint(this.b),R=x.distanceToPoint(this.c);Zs(T)&&(T=0),Zs(I)&&(I=0),Zs(R)&&(R=0);const O=T*I,P=T*R;if(O>0&&P>0)return!1;let k=S.distanceToPoint(w.a),_=S.distanceToPoint(w.b),rt=S.distanceToPoint(w.c);Zs(k)&&(k=0),Zs(_)&&(_=0),Zs(rt)&&(rt=0);const lt=k*_,St=k*rt;if(lt>0&&St>0)return!1;i.copy(S.normal),n.copy(x.normal);const K=i.cross(n);let mt=0,xt=Math.abs(K.x);const Ht=Math.abs(K.y);Ht>xt&&(xt=Ht,mt=1),Math.abs(K.z)>xt&&(mt=2);const ue=Pv[mt],ce=this.a[ue],li=this.b[ue],Be=this.c[ue],L=w.a[ue],Ve=w.b[ue],_a=w.c[ue];if(m(this,ce,li,Be,O,P,T,I,R,h,o))return d(this,w,b,E);if(m(w,L,Ve,_a,lt,St,k,_,rt,l,r))return d(this,w,b,E);if(h.y<h.x){const gt=h.y;h.y=h.x,h.x=gt,c.copy(o.start),o.start.copy(o.end),o.end.copy(c)}if(l.y<l.x){const gt=l.y;l.y=l.x,l.x=gt,c.copy(r.start),r.start.copy(r.end),r.end.copy(c)}return h.y<l.x||l.y<h.x?!1:(b&&(l.x>h.x?b.start.copy(r.start):b.start.copy(o.start),l.y<h.y?b.end.copy(r.end):b.end.copy(o.end)),!0)}})();Ei.prototype.distanceToPoint=(function(){const u=new D;return function(e){return this.closestPointToPoint(e,u),e.distanceTo(u)}})();Ei.prototype.distanceToTriangle=(function(){const u=new D,t=new D,e=["a","b","c"],s=new bn,i=new bn;return function(a,o=null,r=null){const c=o||r?s:null;if(this.intersectsTriangle(a,c,!0))return(o||r)&&(o&&c.getCenter(o),r&&c.getCenter(r)),0;let h=1/0;for(let l=0;l<3;l++){let d;const f=e[l],m=a[f];this.closestPointToPoint(m,u),d=m.distanceToSquared(u),d<h&&(h=d,o&&o.copy(u),r&&r.copy(m));const p=this[f];a.closestPointToPoint(p,u),d=p.distanceToSquared(u),d<h&&(h=d,o&&o.copy(p),r&&r.copy(u))}for(let l=0;l<3;l++){const d=e[l],f=e[(l+1)%3];s.set(this[d],this[f]);for(let m=0;m<3;m++){const p=e[m],g=e[(m+1)%3];i.set(a[p],a[g]),td(s,i,u,t);const M=u.distanceToSquared(t);M<h&&(h=M,o&&o.copy(u),r&&r.copy(t))}}return Math.sqrt(h)}})();class As{constructor(t,e,s){this.isOrientedBox=!0,this.min=new D,this.max=new D,this.matrix=new Oe,this.invMatrix=new Oe,this.points=new Array(8).fill().map(()=>new D),this.satAxes=new Array(3).fill().map(()=>new D),this.satBounds=new Array(3).fill().map(()=>new An),this.alignedSatBounds=new Array(3).fill().map(()=>new An),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),s&&this.matrix.copy(s)}set(t,e,s){this.min.copy(t),this.max.copy(e),this.matrix.copy(s),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}As.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,s=this.max,i=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let l=0;l<=1;l++){const d=1*c|2*h|4*l,f=i[d];f.x=c?s.x:e.x,f.y=h?s.y:e.y,f.z=l?s.z:e.z,f.applyMatrix4(t)}const n=this.satBounds,a=this.satAxes,o=i[0];for(let c=0;c<3;c++){const h=a[c],l=n[c],d=1<<c,f=i[d];h.subVectors(o,f),l.setFromPoints(h,i)}const r=this.alignedSatBounds;r[0].setFromPointsField(i,"x"),r[1].setFromPointsField(i,"y"),r[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();As.prototype.intersectsBox=(function(){const u=new An;return function(e){this.needsUpdate&&this.update();const s=e.min,i=e.max,n=this.satBounds,a=this.satAxes,o=this.alignedSatBounds;if(u.min=s.x,u.max=i.x,o[0].isSeparated(u)||(u.min=s.y,u.max=i.y,o[1].isSeparated(u))||(u.min=s.z,u.max=i.z,o[2].isSeparated(u)))return!1;for(let r=0;r<3;r++){const c=a[r],h=n[r];if(u.setFromBox(c,e),h.isSeparated(u))return!1}return!0}})();As.prototype.intersectsTriangle=(function(){const u=new Ei,t=new Array(3),e=new An,s=new An,i=new D;return function(a){this.needsUpdate&&this.update(),a.isExtendedTriangle?a.needsUpdate&&a.update():(u.copy(a),u.update(),a=u);const o=this.satBounds,r=this.satAxes;t[0]=a.a,t[1]=a.b,t[2]=a.c;for(let d=0;d<3;d++){const f=o[d],m=r[d];if(e.setFromPoints(m,t),f.isSeparated(e))return!1}const c=a.satBounds,h=a.satAxes,l=this.points;for(let d=0;d<3;d++){const f=c[d],m=h[d];if(e.setFromPoints(m,l),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=r[d];for(let m=0;m<4;m++){const p=h[m];if(i.crossVectors(f,p),e.setFromPoints(i,t),s.setFromPoints(i,l),e.isSeparated(s))return!1}}return!0}})();As.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();As.prototype.distanceToPoint=(function(){const u=new D;return function(e){return this.closestPointToPoint(e,u),e.distanceTo(u)}})();As.prototype.distanceToBox=(function(){const u=["x","y","z"],t=new Array(12).fill().map(()=>new bn),e=new Array(12).fill().map(()=>new bn),s=new D,i=new D;return function(a,o=0,r=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(a))return(r||c)&&(a.getCenter(i),this.closestPointToPoint(i,s),a.closestPointToPoint(s,i),r&&r.copy(s),c&&c.copy(i)),0;const h=o*o,l=a.min,d=a.max,f=this.points;let m=1/0;for(let g=0;g<8;g++){const M=f[g];i.copy(M).clamp(l,d);const v=M.distanceToSquared(i);if(v<m&&(m=v,r&&r.copy(M),c&&c.copy(i),v<h))return Math.sqrt(v)}let p=0;for(let g=0;g<3;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){const y=(g+1)%3,w=(g+2)%3,b=M<<y|v<<w,E=1<<g|M<<y|v<<w,A=f[b],S=f[E];t[p].set(A,S);const T=u[g],I=u[y],R=u[w],O=e[p],P=O.start,k=O.end;P[T]=l[T],P[I]=M?l[I]:d[I],P[R]=v?l[R]:d[I],k[T]=d[T],k[I]=M?l[I]:d[I],k[R]=v?l[R]:d[I],p++}for(let g=0;g<=1;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){i.x=g?d.x:l.x,i.y=M?d.y:l.y,i.z=v?d.z:l.z,this.closestPointToPoint(i,s);const y=i.distanceToSquared(s);if(y<m&&(m=y,r&&r.copy(s),c&&c.copy(i),y<h))return Math.sqrt(y)}for(let g=0;g<12;g++){const M=t[g];for(let v=0;v<12;v++){const y=e[v];td(M,y,s,i);const w=s.distanceToSquared(i);if(w<m&&(m=w,r&&r.copy(s),c&&c.copy(i),w<h))return Math.sqrt(w)}}return Math.sqrt(m)}})();class kv extends Ju{constructor(){super(()=>new Ei)}}const oi=new kv,sr=new D,rl=new D;function Lv(u,t,e={},s=0,i=1/0){const n=s*s,a=i*i;let o=1/0,r=null;if(u.shapecast({boundsTraverseOrder:h=>(sr.copy(t).clamp(h.min,h.max),sr.distanceToSquared(t)),intersectsBounds:(h,l,d)=>d<o&&d<a,intersectsTriangle:(h,l)=>{h.closestPointToPoint(t,sr);const d=t.distanceToSquared(sr);return d<o&&(rl.copy(sr),o=d,r=l),d<n}}),o===1/0)return null;const c=Math.sqrt(o);return e.point?e.point.copy(rl):e.point=rl.clone(),e.distance=c,e.faceIndex=r,e}const oc=parseInt(em)>=169,Nv=parseInt(em)<=161,sa=new D,ia=new D,na=new D,rc=new ht,cc=new ht,hc=new ht,H0=new D,U0=new D,G0=new D,ir=new D;function Cv(u,t,e,s,i,n,a,o){let r;if(n===Ai?r=u.intersectTriangle(s,e,t,!0,i):r=u.intersectTriangle(t,e,s,n!==tn,i),r===null)return null;const c=u.origin.distanceTo(i);return c<a||c>o?null:{distance:c,point:i.clone()}}function B0(u,t,e,s,i,n,a,o,r,c,h){sa.fromBufferAttribute(t,n),ia.fromBufferAttribute(t,a),na.fromBufferAttribute(t,o);const l=Cv(u,sa,ia,na,ir,r,c,h);if(l){if(s){rc.fromBufferAttribute(s,n),cc.fromBufferAttribute(s,a),hc.fromBufferAttribute(s,o),l.uv=new ht;const f=eo.getInterpolation(ir,sa,ia,na,rc,cc,hc,l.uv);oc||(l.uv=f)}if(i){rc.fromBufferAttribute(i,n),cc.fromBufferAttribute(i,a),hc.fromBufferAttribute(i,o),l.uv1=new ht;const f=eo.getInterpolation(ir,sa,ia,na,rc,cc,hc,l.uv1);oc||(l.uv1=f),Nv&&(l.uv2=l.uv1)}if(e){H0.fromBufferAttribute(e,n),U0.fromBufferAttribute(e,a),G0.fromBufferAttribute(e,o),l.normal=new D;const f=eo.getInterpolation(ir,sa,ia,na,H0,U0,G0,l.normal);l.normal.dot(u.direction)>0&&l.normal.multiplyScalar(-1),oc||(l.normal=f)}const d={a:n,b:a,c:o,normal:new D,materialIndex:0};if(eo.getNormal(sa,ia,na,d.normal),l.face=d,l.faceIndex=n,oc){const f=new D;eo.getBarycoord(ir,sa,ia,na,f),l.barycoord=f}}return l}function V0(u){return u&&u.isMaterial?u.side:u}function Oh(u,t,e,s,i,n,a){const o=s*3;let r=o+0,c=o+1,h=o+2;const{index:l,groups:d}=u;u.index&&(r=l.getX(r),c=l.getX(c),h=l.getX(h));const{position:f,normal:m,uv:p,uv1:g}=u.attributes;if(Array.isArray(t)){const M=s*3;for(let v=0,y=d.length;v<y;v++){const{start:w,count:b,materialIndex:E}=d[v];if(M>=w&&M<w+b){const A=V0(t[E]),S=B0(e,f,m,p,g,r,c,h,A,n,a);if(S)if(S.faceIndex=s,S.face.materialIndex=E,i)i.push(S);else return S}}}else{const M=V0(t),v=B0(e,f,m,p,g,r,c,h,M,n,a);if(v)if(v.faceIndex=s,v.face.materialIndex=0,i)i.push(v);else return v}return null}function Pe(u,t,e,s){const i=u.a,n=u.b,a=u.c;let o=t,r=t+1,c=t+2;e&&(o=e.getX(o),r=e.getX(r),c=e.getX(c)),i.x=s.getX(o),i.y=s.getY(o),i.z=s.getZ(o),n.x=s.getX(r),n.y=s.getY(r),n.z=s.getZ(r),a.x=s.getX(c),a.y=s.getY(c),a.z=s.getZ(c)}function _v(u,t,e,s,i,n,a,o){const{geometry:r,_indirectBuffer:c}=u;for(let h=s,l=s+i;h<l;h++)Oh(r,t,e,h,n,a,o)}function zv(u,t,e,s,i,n,a){const{geometry:o,_indirectBuffer:r}=u;let c=1/0,h=null;for(let l=s,d=s+i;l<d;l++){let f;f=Oh(o,t,e,l,null,n,a),f&&f.distance<c&&(h=f,c=f.distance)}return h}function Fv(u,t,e,s,i,n,a){const{geometry:o}=e,{index:r}=o,c=o.attributes.position;for(let h=u,l=t+u;h<l;h++){let d;if(d=h,Pe(a,d*3,r,c),a.needsUpdate=!0,s(a,d,i,n))return!0}return!1}function Hv(u,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=u.geometry,s=e.index?e.index.array:null,i=e.attributes.position;let n,a,o,r,c=0;const h=u._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),o=new Uint16Array(n),r=new Float32Array(n),l(0,c),c+=n.byteLength;function l(d,f,m=!1){const p=d*2;if(Ae(p,o)){const g=Ze(d,a),M=Ms(p,o);let v=1/0,y=1/0,w=1/0,b=-1/0,E=-1/0,A=-1/0;for(let S=3*g,x=3*(g+M);S<x;S++){let T=s[S];const I=i.getX(T),R=i.getY(T),O=i.getZ(T);I<v&&(v=I),I>b&&(b=I),R<y&&(y=R),R>E&&(E=R),O<w&&(w=O),O>A&&(A=O)}return r[d+0]!==v||r[d+1]!==y||r[d+2]!==w||r[d+3]!==b||r[d+4]!==E||r[d+5]!==A?(r[d+0]=v,r[d+1]=y,r[d+2]=w,r[d+3]=b,r[d+4]=E,r[d+5]=A,!0):!1}else{const g=He(d),M=Ue(d,a);let v=m,y=!1,w=!1;if(t){if(!v){const T=g/Fe+f/gs,I=M/Fe+f/gs;y=t.has(T),w=t.has(I),v=!y&&!w}}else y=!0,w=!0;const b=v||y,E=v||w;let A=!1;b&&(A=l(g,f,v));let S=!1;E&&(S=l(M,f,v));const x=A||S;if(x)for(let T=0;T<3;T++){const I=g+T,R=M+T,O=r[I],P=r[I+3],k=r[R],_=r[R+3];r[d+T]=O<k?O:k,r[d+T+3]=P>_?P:_}return x}}}function Jn(u,t,e,s,i){let n,a,o,r,c,h;const l=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,m=e.origin.x,p=e.origin.y,g=e.origin.z;let M=t[u],v=t[u+3],y=t[u+1],w=t[u+3+1],b=t[u+2],E=t[u+3+2];return l>=0?(n=(M-m)*l,a=(v-m)*l):(n=(v-m)*l,a=(M-m)*l),d>=0?(o=(y-p)*d,r=(w-p)*d):(o=(w-p)*d,r=(y-p)*d),n>r||o>a||((o>n||isNaN(n))&&(n=o),(r<a||isNaN(a))&&(a=r),f>=0?(c=(b-g)*f,h=(E-g)*f):(c=(E-g)*f,h=(b-g)*f),n>h||c>a)?!1:((c>n||n!==n)&&(n=c),(h<a||a!==a)&&(a=h),n<=i&&a>=s)}function Uv(u,t,e,s,i,n,a,o){const{geometry:r,_indirectBuffer:c}=u;for(let h=s,l=s+i;h<l;h++){let d=c?c[h]:h;Oh(r,t,e,d,n,a,o)}}function Gv(u,t,e,s,i,n,a){const{geometry:o,_indirectBuffer:r}=u;let c=1/0,h=null;for(let l=s,d=s+i;l<d;l++){let f;f=Oh(o,t,e,r?r[l]:l,null,n,a),f&&f.distance<c&&(h=f,c=f.distance)}return h}function Bv(u,t,e,s,i,n,a){const{geometry:o}=e,{index:r}=o,c=o.attributes.position;for(let h=u,l=t+u;h<l;h++){let d;if(d=e.resolveTriangleIndex(h),Pe(a,d*3,r,c),a.needsUpdate=!0,s(a,d,i,n))return!0}return!1}function Vv(u,t,e,s,i,n,a){re.setBuffer(u._roots[t]),xu(0,u,e,s,i,n,a),re.clearBuffer()}function xu(u,t,e,s,i,n,a){const{float32Array:o,uint16Array:r,uint32Array:c}=re,h=u*2;if(Ae(h,r)){const d=Ze(u,c),f=Ms(h,r);_v(t,e,s,d,f,i,n,a)}else{const d=He(u);Jn(d,o,s,n,a)&&xu(d,t,e,s,i,n,a);const f=Ue(u,c);Jn(f,o,s,n,a)&&xu(f,t,e,s,i,n,a)}}const Wv=["x","y","z"];function Kv(u,t,e,s,i,n){re.setBuffer(u._roots[t]);const a=Tu(0,u,e,s,i,n);return re.clearBuffer(),a}function Tu(u,t,e,s,i,n){const{float32Array:a,uint16Array:o,uint32Array:r}=re;let c=u*2;if(Ae(c,o)){const l=Ze(u,r),d=Ms(c,o);return zv(t,e,s,l,d,i,n)}else{const l=Zu(u,r),d=Wv[l],m=s.direction[d]>=0;let p,g;m?(p=He(u),g=Ue(u,r)):(p=Ue(u,r),g=He(u));const v=Jn(p,a,s,i,n)?Tu(p,t,e,s,i,n):null;if(v){const b=v.point[d];if(m?b<=a[g+l]:b>=a[g+l+3])return v}const w=Jn(g,a,s,i,n)?Tu(g,t,e,s,i,n):null;return v&&w?v.distance<=w.distance?v:w:v||w||null}}const lc=new ee,Ya=new Ei,$a=new Ei,nr=new Oe,W0=new As,uc=new As;function Yv(u,t,e,s){re.setBuffer(u._roots[t]);const i=Du(0,u,e,s);return re.clearBuffer(),i}function Du(u,t,e,s,i=null){const{float32Array:n,uint16Array:a,uint32Array:o}=re;let r=u*2;if(i===null&&(e.boundingBox||e.computeBoundingBox(),W0.set(e.boundingBox.min,e.boundingBox.max,s),i=W0),Ae(r,a)){const h=t.geometry,l=h.index,d=h.attributes.position,f=e.index,m=e.attributes.position,p=Ze(u,o),g=Ms(r,a);if(nr.copy(s).invert(),e.boundsTree)return ve(u,n,uc),uc.matrix.copy(nr),uc.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>uc.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(s),v.b.applyMatrix4(s),v.c.applyMatrix4(s),v.needsUpdate=!0;for(let y=p*3,w=(g+p)*3;y<w;y+=3)if(Pe($a,y,l,d),$a.needsUpdate=!0,v.intersectsTriangle($a))return!0;return!1}});{const M=Rh(e);for(let v=p*3,y=(g+p)*3;v<y;v+=3){Pe(Ya,v,l,d),Ya.a.applyMatrix4(nr),Ya.b.applyMatrix4(nr),Ya.c.applyMatrix4(nr),Ya.needsUpdate=!0;for(let w=0,b=M*3;w<b;w+=3)if(Pe($a,w,f,m),$a.needsUpdate=!0,Ya.intersectsTriangle($a))return!0}}}else{const h=He(u),l=Ue(u,o);return ve(h,n,lc),!!(i.intersectsBox(lc)&&Du(h,t,e,s,i)||(ve(l,n,lc),i.intersectsBox(lc)&&Du(l,t,e,s,i)))}}const dc=new Oe,cl=new As,ar=new As,$v=new D,Xv=new D,qv=new D,jv=new D;function Zv(u,t,e,s={},i={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),cl.set(t.boundingBox.min,t.boundingBox.max,e),cl.needsUpdate=!0;const o=u.geometry,r=o.attributes.position,c=o.index,h=t.attributes.position,l=t.index,d=oi.getPrimitive(),f=oi.getPrimitive();let m=$v,p=Xv,g=null,M=null;i&&(g=qv,M=jv);let v=1/0,y=null,w=null;return dc.copy(e).invert(),ar.matrix.copy(dc),u.shapecast({boundsTraverseOrder:b=>cl.distanceToBox(b),intersectsBounds:(b,E,A)=>A<v&&A<a?(E&&(ar.min.copy(b.min),ar.max.copy(b.max),ar.needsUpdate=!0),!0):!1,intersectsRange:(b,E)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:S=>ar.distanceToBox(S),intersectsBounds:(S,x,T)=>T<v&&T<a,intersectsRange:(S,x)=>{for(let T=S,I=S+x;T<I;T++){Pe(f,3*T,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let R=b,O=b+E;R<O;R++){Pe(d,3*R,c,r),d.needsUpdate=!0;const P=d.distanceToTriangle(f,m,g);if(P<v&&(p.copy(m),M&&M.copy(g),v=P,y=R,w=T),P<n)return!0}}}});{const A=Rh(t);for(let S=0,x=A;S<x;S++){Pe(f,3*S,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=b,I=b+E;T<I;T++){Pe(d,3*T,c,r),d.needsUpdate=!0;const R=d.distanceToTriangle(f,m,g);if(R<v&&(p.copy(m),M&&M.copy(g),v=R,y=T,w=S),R<n)return!0}}}}}),oi.releasePrimitive(d),oi.releasePrimitive(f),v===1/0?null:(s.point?s.point.copy(p):s.point=p.clone(),s.distance=v,s.faceIndex=y,i&&(i.point?i.point.copy(M):i.point=M.clone(),i.point.applyMatrix4(dc),p.applyMatrix4(dc),i.distance=p.sub(i.point).length(),i.faceIndex=w),s)}function Jv(u,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=u.geometry,s=e.index?e.index.array:null,i=e.attributes.position;let n,a,o,r,c=0;const h=u._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),o=new Uint16Array(n),r=new Float32Array(n),l(0,c),c+=n.byteLength;function l(d,f,m=!1){const p=d*2;if(Ae(p,o)){const g=Ze(d,a),M=Ms(p,o);let v=1/0,y=1/0,w=1/0,b=-1/0,E=-1/0,A=-1/0;for(let S=g,x=g+M;S<x;S++){const T=3*u.resolveTriangleIndex(S);for(let I=0;I<3;I++){let R=T+I;R=s?s[R]:R;const O=i.getX(R),P=i.getY(R),k=i.getZ(R);O<v&&(v=O),O>b&&(b=O),P<y&&(y=P),P>E&&(E=P),k<w&&(w=k),k>A&&(A=k)}}return r[d+0]!==v||r[d+1]!==y||r[d+2]!==w||r[d+3]!==b||r[d+4]!==E||r[d+5]!==A?(r[d+0]=v,r[d+1]=y,r[d+2]=w,r[d+3]=b,r[d+4]=E,r[d+5]=A,!0):!1}else{const g=He(d),M=Ue(d,a);let v=m,y=!1,w=!1;if(t){if(!v){const T=g/Fe+f/gs,I=M/Fe+f/gs;y=t.has(T),w=t.has(I),v=!y&&!w}}else y=!0,w=!0;const b=v||y,E=v||w;let A=!1;b&&(A=l(g,f,v));let S=!1;E&&(S=l(M,f,v));const x=A||S;if(x)for(let T=0;T<3;T++){const I=g+T,R=M+T,O=r[I],P=r[I+3],k=r[R],_=r[R+3];r[d+T]=O<k?O:k,r[d+T+3]=P>_?P:_}return x}}}function Qv(u,t,e,s,i,n,a){re.setBuffer(u._roots[t]),Iu(0,u,e,s,i,n,a),re.clearBuffer()}function Iu(u,t,e,s,i,n,a){const{float32Array:o,uint16Array:r,uint32Array:c}=re,h=u*2;if(Ae(h,r)){const d=Ze(u,c),f=Ms(h,r);Uv(t,e,s,d,f,i,n,a)}else{const d=He(u);Jn(d,o,s,n,a)&&Iu(d,t,e,s,i,n,a);const f=Ue(u,c);Jn(f,o,s,n,a)&&Iu(f,t,e,s,i,n,a)}}const ty=["x","y","z"];function ey(u,t,e,s,i,n){re.setBuffer(u._roots[t]);const a=Ru(0,u,e,s,i,n);return re.clearBuffer(),a}function Ru(u,t,e,s,i,n){const{float32Array:a,uint16Array:o,uint32Array:r}=re;let c=u*2;if(Ae(c,o)){const l=Ze(u,r),d=Ms(c,o);return Gv(t,e,s,l,d,i,n)}else{const l=Zu(u,r),d=ty[l],m=s.direction[d]>=0;let p,g;m?(p=He(u),g=Ue(u,r)):(p=Ue(u,r),g=He(u));const v=Jn(p,a,s,i,n)?Ru(p,t,e,s,i,n):null;if(v){const b=v.point[d];if(m?b<=a[g+l]:b>=a[g+l+3])return v}const w=Jn(g,a,s,i,n)?Ru(g,t,e,s,i,n):null;return v&&w?v.distance<=w.distance?v:w:v||w||null}}const fc=new ee,Xa=new Ei,qa=new Ei,or=new Oe,K0=new As,mc=new As;function sy(u,t,e,s){re.setBuffer(u._roots[t]);const i=Ou(0,u,e,s);return re.clearBuffer(),i}function Ou(u,t,e,s,i=null){const{float32Array:n,uint16Array:a,uint32Array:o}=re;let r=u*2;if(i===null&&(e.boundingBox||e.computeBoundingBox(),K0.set(e.boundingBox.min,e.boundingBox.max,s),i=K0),Ae(r,a)){const h=t.geometry,l=h.index,d=h.attributes.position,f=e.index,m=e.attributes.position,p=Ze(u,o),g=Ms(r,a);if(or.copy(s).invert(),e.boundsTree)return ve(u,n,mc),mc.matrix.copy(or),mc.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>mc.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(s),v.b.applyMatrix4(s),v.c.applyMatrix4(s),v.needsUpdate=!0;for(let y=p,w=g+p;y<w;y++)if(Pe(qa,3*t.resolveTriangleIndex(y),l,d),qa.needsUpdate=!0,v.intersectsTriangle(qa))return!0;return!1}});{const M=Rh(e);for(let v=p,y=g+p;v<y;v++){const w=t.resolveTriangleIndex(v);Pe(Xa,3*w,l,d),Xa.a.applyMatrix4(or),Xa.b.applyMatrix4(or),Xa.c.applyMatrix4(or),Xa.needsUpdate=!0;for(let b=0,E=M*3;b<E;b+=3)if(Pe(qa,b,f,m),qa.needsUpdate=!0,Xa.intersectsTriangle(qa))return!0}}}else{const h=He(u),l=Ue(u,o);return ve(h,n,fc),!!(i.intersectsBox(fc)&&Ou(h,t,e,s,i)||(ve(l,n,fc),i.intersectsBox(fc)&&Ou(l,t,e,s,i)))}}const pc=new Oe,hl=new As,rr=new As,iy=new D,ny=new D,ay=new D,oy=new D;function ry(u,t,e,s={},i={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),hl.set(t.boundingBox.min,t.boundingBox.max,e),hl.needsUpdate=!0;const o=u.geometry,r=o.attributes.position,c=o.index,h=t.attributes.position,l=t.index,d=oi.getPrimitive(),f=oi.getPrimitive();let m=iy,p=ny,g=null,M=null;i&&(g=ay,M=oy);let v=1/0,y=null,w=null;return pc.copy(e).invert(),rr.matrix.copy(pc),u.shapecast({boundsTraverseOrder:b=>hl.distanceToBox(b),intersectsBounds:(b,E,A)=>A<v&&A<a?(E&&(rr.min.copy(b.min),rr.max.copy(b.max),rr.needsUpdate=!0),!0):!1,intersectsRange:(b,E)=>{if(t.boundsTree){const A=t.boundsTree;return A.shapecast({boundsTraverseOrder:S=>rr.distanceToBox(S),intersectsBounds:(S,x,T)=>T<v&&T<a,intersectsRange:(S,x)=>{for(let T=S,I=S+x;T<I;T++){const R=A.resolveTriangleIndex(T);Pe(f,3*R,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let O=b,P=b+E;O<P;O++){const k=u.resolveTriangleIndex(O);Pe(d,3*k,c,r),d.needsUpdate=!0;const _=d.distanceToTriangle(f,m,g);if(_<v&&(p.copy(m),M&&M.copy(g),v=_,y=O,w=T),_<n)return!0}}}})}else{const A=Rh(t);for(let S=0,x=A;S<x;S++){Pe(f,3*S,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=b,I=b+E;T<I;T++){const R=u.resolveTriangleIndex(T);Pe(d,3*R,c,r),d.needsUpdate=!0;const O=d.distanceToTriangle(f,m,g);if(O<v&&(p.copy(m),M&&M.copy(g),v=O,y=T,w=S),O<n)return!0}}}}}),oi.releasePrimitive(d),oi.releasePrimitive(f),v===1/0?null:(s.point?s.point.copy(p):s.point=p.clone(),s.distance=v,s.faceIndex=y,i&&(i.point?i.point.copy(M):i.point=M.clone(),i.point.applyMatrix4(pc),p.applyMatrix4(pc),i.distance=p.sub(i.point).length(),i.faceIndex=w),s)}function Y0(u,t,e){return u===null?null:(u.point.applyMatrix4(t.matrixWorld),u.distance=u.point.distanceTo(e.ray.origin),u.object=t,u)}const gc=new As,Mc=new sm,$0=new D,X0=new Oe,q0=new D,ll=["getX","getY","getZ"];class lh extends Iv{static serialize(t,e={}){e={cloneBuffers:!0,...e};const s=t.geometry,i=t._roots,n=t._indirectBuffer,a=s.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(o.roots=i.map(r=>r.slice()),o.index=a?a.array.slice():null,o.indirectBuffer=n?n.slice():null):(o.roots=i,o.index=a?a.array:null,o.indirectBuffer=n),o}static deserialize(t,e,s={}){s={setIndex:!0,indirect:!!t.indirectBuffer,...s};const{index:i,roots:n,indirectBuffer:a}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),r(n));const o=new lh(e,{...s,[ju]:!0});if(o._roots=n,o._indirectBuffer=a||null,s.setIndex){const c=e.getIndex();if(c===null){const h=new Ot(t.index,1,!1);e.setIndex(h)}else c.array!==i&&(c.array.set(i),c.needsUpdate=!0)}return o;function r(c){for(let h=0;h<c.length;h++){const l=c[h],d=new Uint32Array(l),f=new Uint16Array(l);for(let m=0,p=l.byteLength/gs;m<p;m++){const g=Fe*m,M=2*g;Ae(M,f)||(d[g+6]=d[g+6]/Fe-m)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,s){const i=this.geometry,n=this._indirectBuffer,a=i.attributes.position,o=i.index?i.index.array:null,c=(n?n[t]:t)*3;let h=c+0,l=c+1,d=c+2;o&&(h=o[h],l=o[l],d=o[d]);for(let f=0;f<3;f++){const m=a[ll[f]](h),p=a[ll[f]](l),g=a[ll[f]](d);let M=m;p<M&&(M=p),g<M&&(M=g);let v=m;p>v&&(v=p),g>v&&(v=g),e[s+f]=M,e[s+f+3]=v}return e}computePrimitiveBounds(t,e,s){const i=this.geometry,n=this._indirectBuffer,a=i.attributes.position,o=i.index?i.index.array:null,r=a.normalized;if(t<0||e+t-s.offset>s.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const c=a.array,h=a.offset||0;let l=3;a.isInterleavedBufferAttribute&&(l=a.data.stride);const d=["getX","getY","getZ"],f=s.offset;for(let m=t,p=t+e;m<p;m++){const M=(n?n[m]:m)*3,v=(m-f)*6;let y=M+0,w=M+1,b=M+2;o&&(y=o[y],w=o[w],b=o[b]),r||(y=y*l+h,w=w*l+h,b=b*l+h);for(let E=0;E<3;E++){let A,S,x;r?(A=a[d[E]](y),S=a[d[E]](w),x=a[d[E]](b)):(A=c[y+E],S=c[w+E],x=c[b+E]);let T=A;S<T&&(T=S),x<T&&(T=x);let I=A;S>I&&(I=S),x>I&&(I=x);const R=(I-T)/2,O=E*2;s[v+O+0]=T+R,s[v+O+1]=R+(Math.abs(T)+R)*_c}}return s}raycastObject3D(t,e,s=[]){const{material:i}=t;if(i===void 0)return;X0.copy(t.matrixWorld).invert(),Mc.copy(e.ray).applyMatrix4(X0),q0.setFromMatrixScale(t.matrixWorld),$0.copy(Mc.direction).multiply(q0);const n=$0.length(),a=e.near/n,o=e.far/n;if(e.firstHitOnly===!0){let r=this.raycastFirst(Mc,i,a,o);r=Y0(r,t,e),r&&s.push(r)}else{const r=this.raycast(Mc,i,a,o);for(let c=0,h=r.length;c<h;c++){const l=Y0(r[c],t,e);l&&s.push(l)}}return s}refit(t=null){return(this.indirect?Jv:Hv)(this,t)}raycast(t,e=md,s=0,i=1/0){const n=this._roots,a=[],o=this.indirect?Qv:Vv;for(let r=0,c=n.length;r<c;r++)o(this,r,e,t,a,s,i);return a}raycastFirst(t,e=md,s=0,i=1/0){const n=this._roots;let a=null;const o=this.indirect?ey:Kv;for(let r=0,c=n.length;r<c;r++){const h=o(this,r,e,t,s,i);h!=null&&(a==null||h.distance<a.distance)&&(a=h)}return a}intersectsGeometry(t,e){let s=!1;const i=this._roots,n=this.indirect?sy:Yv;for(let a=0,o=i.length;a<o&&(s=n(this,a,t,e),!s);a++);return s}shapecast(t){const e=oi.getPrimitive(),s=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?Bv:Fv});return oi.releasePrimitive(e),s}bvhcast(t,e,s){let{intersectsRanges:i,intersectsTriangles:n}=s;const a=oi.getPrimitive(),o=this.geometry.index,r=this.geometry.attributes.position,c=this.indirect?m=>{const p=this.resolveTriangleIndex(m);Pe(a,p*3,o,r)}:m=>{Pe(a,m*3,o,r)},h=oi.getPrimitive(),l=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?m=>{const p=t.resolveTriangleIndex(m);Pe(h,p*3,l,d)}:m=>{Pe(h,m*3,l,d)};if(n){if(!(t instanceof lh))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const m=(p,g,M,v,y,w,b,E)=>{for(let A=M,S=M+v;A<S;A++){f(A),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let x=p,T=p+g;x<T;x++)if(c(x),a.needsUpdate=!0,n(a,h,x,A,y,w,b,E))return!0}return!1};if(i){const p=i;i=function(g,M,v,y,w,b,E,A){return p(g,M,v,y,w,b,E,A)?!0:m(g,M,v,y,w,b,E,A)}}else i=m}return super.bvhcast(t,e,{intersectsRanges:i})}intersectsBox(t,e){return gc.set(t.min,t.max,e),gc.needsUpdate=!0,this.shapecast({intersectsBounds:s=>gc.intersectsBox(s),intersectsTriangle:s=>gc.intersectsTriangle(s)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,s={},i={},n=0,a=1/0){return(this.indirect?ry:Zv)(this,t,e,s,i,n,a)}closestPointToPoint(t,e={},s=0,i=1/0){return Lv(this,t,e,s,i)}}class Ri{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new zl;static install(){if(Ri.installed)return;Ri.installed=!0;const t=B.prototype.raycast;B.prototype.raycast=function(e,s){const i=Ri.treeOf(this,e);i!==null&&(i?i.raycastObject3D(this,e,s):t.call(this,e,s))}}static treeOf(t,e){const s=t.geometry,i=s?.attributes.position;if(!(i instanceof Ot)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||s.morphAttributes.position)return;const n=s.index;if((n?n.count:i.count)/3<Ri.MIN_TRIANGLES||s.drawRange.start!==0||s.drawRange.count!==1/0)return;s.boundingSphere===null&&s.computeBoundingSphere();const a=Ri.sphere.copy(s.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(a))return null;const o=Ri.trees.get(s);if(o){if(!o.bvh)return;if(o.position===i&&o.positionVersion===i.version&&o.index===n&&o.indexVersion===(n?.version??0))return o.bvh;Ri.trees.set(s,{positionVersion:-1,index:null,indexVersion:-1});return}const r=new lh(s,{indirect:!0});return Ri.trees.set(s,{bvh:r,position:i,positionVersion:i.version,index:n,indexVersion:n?.version??0}),r}}function cy(u,t){return JSON.stringify(u.cloudLayers)===JSON.stringify(t.cloudLayers)&&u.cloudCover===t.cloudCover&&u.cloudDarkness===t.cloudDarkness&&u.cloudBaseM===t.cloudBaseM&&u.highCloudCover===t.highCloudCover&&u.iceCrystalAlignment===t.iceCrystalAlignment&&u.rareIceCrystals===t.rareIceCrystals&&u.lowerCloudCover===t.lowerCloudCover&&u.relativeHumidity===t.relativeHumidity&&u.visibilityKm===t.visibilityKm&&u.precipitationType===t.precipitationType&&u.precipitationIntensity===t.precipitationIntensity&&u.precipitationAmount===t.precipitationAmount&&u.windDirectionDeg===t.windDirectionDeg&&u.windSpeed===t.windSpeed&&u.storm===t.storm}const vc=900,ul=Ca.decorDepth,j0=Ca.dazzle,dl=Ca.hud,yc=.5,wc=it.GROUND_RADIUS_M;function Z0(u){return it.groundRadiusFor(u)}const fl=.5,ml=850,bc=.03,hy=.015,de=850,ja=300,sn=120,ly=700,pl=.03,uy=3.5,Ec=20,gl=.04,dy=.26,J0=4,Ml=1.5,Q0=-1,fy=.01,Fc=-4,my=2,py=20,Ac=2600,gy=.97,My=.38,cr=Fc,vy=8,yy=2,tf=1500,wy=.7,by=.3,Ey=.32,Ay=.65,ef=2.4,Sy=.9,xy=400,Ty=[0,45,90,135,180,225,270,315],Dy=2,Iy=16,sf=4e3,nf=880,Sc=40,af=60,Ry=10,of=1,Oy=it.REBUILD_DISTANCE_M,rf=.265,cf=[[0,0],...Array.from({length:8},(u,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*rf,Math.sin(e)*rf]})],vl=700,yl=250/Yf,Py=12,hf=5,wl=6,aa=[.92,.92,.95],bl=[.15,.15,.19],El={snow:{fallSpeedMPerS:2,size:.3,color:new q(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new q(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},ao=0,Al=0,ky=150,Sl=3e3,hr=20,Ly=15,lf=ao,Ny=40,uf=1,Cy=9;function xl(u){return uf+(Cy-uf)*u}const df=new q(.75,.82,.92),_y=10,zy=.5;function ff(u){return Oi(u/_y,zy,1)}const oa=200,mf=.18,pf=.32,Fy=.35,gf=new q(.85,.9,.98),Mf=5,vf=.85,yf=.01;function Hy(u,t,e=1){return Math.round(u*(yf+(1-yf)*t)*e)}function Uy(u,t){return JSON.stringify(u.cloudLayers)===JSON.stringify(t.cloudLayers)&&u.cloudCover===t.cloudCover&&u.cloudDarkness===t.cloudDarkness&&u.cloudBaseM===t.cloudBaseM&&u.highCloudCover===t.highCloudCover&&u.iceCrystalAlignment===t.iceCrystalAlignment&&u.lowerCloudCover===t.lowerCloudCover}const wf=230,bf=.7,Ef=.05,Gy=.6,By=.7,Vy=.15,Af=.35,Wy=3,Ky=1/12,Yy=.5,xi=new q(.82,.86,1),$y=2500,Xy=1.6,Tl=15,qy={Venus:new q(1,.96,.85),Mars:new q(1,.55,.4),Jupiter:new q(.95,.87,.72),Saturn:new q(.92,.86,.68)};class N{renderer;scene=new js;phenomena=new Rs(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Ft;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let s=!0;const i=()=>{s&&(s=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=e===void 0?void 0:setTimeout(i,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(n),i()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+sf,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),sf+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ct;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ht;decorModelProvider=new gp;decorModelToken=0;decorModelCredits=new Map;emitterLights=new ys(this.scene,()=>this.relativeScale,{halfExtentM:sn,depthHalfRangeM:ja,biasM:pl,normalBiasM:gl,mapSize:1024});bodySystem=new G(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??N.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*N.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;skyEventCloudLights=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Uc(16777215,0);celestialLightTarget=new Jf;skyLight=new Jp(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new Pc;weather=Fp;observerElevationM=0;siteElevationM=0;air=new us;groundRadius=wc;terrainRadius=wc;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new D;cloudFieldOffset=new D;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new D;rainLastVerticalFacing=-1;rainViewportSize=new ht;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Uc(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new Pc;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new Pc;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=wt.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Ur;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Gm()){Ar.install(),Sr.install(),Ri.install(),this.renderer=new Qp({canvas:t,antialias:!0}),this.resolution=new zt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=tg,this.camera=new Gc(60,t.width/Math.max(t.height,1),.1,vc*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-sn,this.celestialLight.shadow.camera.right=sn,this.celestialLight.shadow.camera.top=sn,this.celestialLight.shadow.camera.bottom=-sn,this.celestialLight.shadow.camera.near=de-ja,this.celestialLight.shadow.camera.far=de+ja,this.celestialLight.shadow.bias=-pl/(2*ja),this.celestialLight.shadow.normalBias=gl,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(xi),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const s=new st(this.renderer,()=>{this.skyColoursStale=!0,this.render()});s.supported?this.scatteredSky=s:s.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.lastBodies&&this.setBodies(...this.lastBodies),this.render()}lastBodies;setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*yl,0,t.z*yl);for(const s of[this.cloudUniforms,this.cirrusUniforms])s?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Mt,s=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Mt;t.headingDeg!==void 0?this.camera.rotation.set(s,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Mt,e,"YXZ"):this.camera.rotation.set(s,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(Z0(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/wc),this.camera.far=Math.max(vc*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseStatedElevationM=t.elevationM,this.poseAltitudeM=t.altitudeM,this.poseElevationM=t.altitudeM!==void 0?Math.max(0,t.altitudeM-this.siteElevationM-this.groundYUnder(0,0)):t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=N.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return it.decorReachFor(t,e)}placeTerrain(t,e,s,i){const n=(a,o)=>{const r=ot(o.lat,o.lng,t,e);a.position.x=r.x-s,a.position.z=r.z+i};if(this.terrainMesh&&this.terrainMeshOrigin&&n(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&n(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const a=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=a}this.lookPatch&&n(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=of+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=it.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const s=(t.headingDeg??0)*Math.PI/180,i=t.lat+e.distanceM*Math.cos(s)/111320,n=t.lng+e.distanceM*Math.sin(s)/(111320*Math.cos(t.lat*Math.PI/180)),a=this.lookPatchAsked;if(a){const c=ot(i,n,a.lat,a.lng);if(Math.hypot(c.x,c.z)<a.radiusM*N.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:i,lng:n,radiusM:e.radiusM};const o=++this.lookPatchToken,r=this.terrainProviders;Kh(i,n,{elevation:r.elevation,imagery:r.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:c})=>{if(o!==this.lookPatchToken||this.terrainProviders!==r||!this.terrainMesh){this.disposeMesh(c);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),c.renderOrder=N.LOOK_PATCH_RENDER_ORDER,c.position.y=this.terrainMesh.position.y;const h=c.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:c,origin:{lat:i,lng:n},radiusM:e.radiusM};const l=ot(i,n,t.lat,t.lng);c.position.x=l.x,c.position.z=l.z,this.scene.add(c),this.compileNextFrameOffThread(),this.render()},c=>console.warn("No sharp ground under what is looked at:",c))}setTerrainOrigin(t,e,s){if(t===void 0||e===void 0)return;const i=this.terrainProviders.patches;let n;if(i){if(!i.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:s},this.patchesAwaited!==i){this.patchesAwaited=i;const d=this.terrainProviders;this.awaitArrival(i.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),N.TERRAIN_PATIENCE_MS)}return}const l=i.nearest(t,e);l&&(t=l.lat,e=l.lng,n=l.radiusM)}const a=n??Math.max(it.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-a)<a*.1){const{x:l,z:d}=ot(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(l*l+d*d)<Oy*(a/wc))return}const o=this.terrainRadius,r=this.terrainMeshOrigin;r!==void 0&&Math.hypot(ot(t,e,r.lat,r.lng).x,ot(t,e,r.lat,r.lng).z)<=o||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=a;const h=++this.terrainBuildToken;this.awaitArrival(Kh(t,e,this.terrainProviders,a,{route:this.observerRoute}),N.TERRAIN_PATIENCE_MS).then(({mesh:l,attribution:d,originElevationM:f,water:m,waterLater:p})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(l,t,e);const g=this.terrainMesh,M=this.terrainMeshOrigin,v=M?ot(t,e,M.lat,M.lng):void 0;g&&v&&Math.hypot(v.x,v.z)<=o&&(l.position.y=g.position.y+this.groundYOfPatch(g,v.x,v.z)),g&&M&&v&&Math.hypot(v.x,v.z)<=o?this.crossfadeTerrain(l,g,M):this.disposeMesh(this.terrainMesh),l.renderOrder=of,this.terrainMesh=l,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(l),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,a),this.buildWater(t,e,a,m,p),this.buildRailways(t,e,a),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,a,l,f),this.render(),s?.()}).catch(l=>{console.warn("Terrain build failed, keeping the flat ground fallback:",l),s?.()})}buildFarRing(t,e,s,i,n){i.geometry.computeBoundingBox();const a=i.position.y+(i.geometry.boundingBox?.min.y??0),o=this.camera.position.y-a,r=this.skyEventReachM({lat:t,lng:e}),c=it.farRingRadiusFor(this.weather.visibilityKm);if(!it.needsFarRing(s,o,r,c)){this.dropFarRing();return}if(this.farRing&&this.farRingRadiusM===c){const{x:p,z:g}=ot(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,g)<s*N.FAR_RING_KEPT_SHARE)return}const h=this.terrainProviders.patches,l=h?.farRingOf?.(t,e);if(h&&!l){this.dropFarRing();return}const d=l?.radiusM??c,f=++this.farRingToken,m=this.terrainProviders;this.awaitArrival(Kh(t,e,{elevation:m.elevation,imagery:m.imagery},d,void 0,{innerM:s*N.FAR_RING_OPEN_SHARE,referenceElevationM:n,gridSize:it.farRingGridFor(d)}),N.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(f!==this.farRingToken||this.terrainProviders!==m){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=f,p.renderOrder=N.FAR_RING_RENDER_ORDER,p.position.y=i.position.y-N.FAR_RING_DROP_M;const g=p.material;g.polygonOffset=!0,g.polygonOffsetFactor=2,g.polygonOffsetUnits=8,g.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=d,this.applyGroundDepthWrite(),this.scene.add(p),p.position.x=i.position.x,p.position.z=i.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,s){if(this.grassReference){const a=ot(this.grassReference.lat,this.grassReference.lng,e,s);Math.hypot(a.x,a.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:s};const i=ot(this.grassReference.lat,this.grassReference.lng,e,s);t.material.userData?.grassOrigin?.set(i.x,i.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,s){this.stopTerrainFade();const i=t.material;i.opacity=0,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-4;const n=performance.now(),a=()=>{const o=Math.min(1,(performance.now()-n)/N.TERRAIN_CROSSFADE_MS);if(i.opacity=o*o*(3-2*o),this.render(),o<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(a);return}i.polygonOffset=!1,i.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:s,frameId:requestAnimationFrame(a)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=it.ROADS_MAX_RADIUS_M;buildRoads(t,e,s){const i=this.terrainProviders.roads;if(!i||s>N.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===t&&n.lng===e&&n.radiusM===s){this.drapeRoads(n.ways,t,e,i.contemporary);return}n&&Math.hypot(ot(t,e,n.lat,n.lng).x,ot(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,t,e,i.contemporary),this.awaitArrival(i.getRoads(xr(t,e,s)),N.ROADS_PATIENCE_MS).then(a=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:s,ways:a},this.drapeRoads(a,t,e,i.contemporary))}).catch(a=>{console.warn("Roads unavailable, drawing none:",a)})}buildWater(t,e,s,i,n){const a=this.terrainProviders.water;if(!a||s>N.ROADS_MAX_RADIUS_M){this.clearWater();return}if(i){this.waterSurfaces={lat:t,lng:e,radiusM:s,surfaces:i},this.awaitArrival(this.drapeWater(i,t,e,s),N.ROADS_PATIENCE_MS).catch(r=>console.warn("Water not drawn:",r));return}const o=this.waterSurfaces;if(o&&o.lat===t&&o.lng===e&&o.radiusM===s){this.drapeWater(o.surfaces,t,e,s);return}o&&Math.hypot(ot(t,e,o.lat,o.lng).x,ot(t,e,o.lat,o.lng).z)<=o.radiusM&&this.drapeWater(o.surfaces,t,e,s),this.awaitArrival((n??a.getWater(xr(t,e,s))).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:s,surfaces:r},this.drapeWater(r,t,e,s)}),N.ROADS_PATIENCE_MS).catch(r=>{console.warn("Water unavailable, drawing none:",r)})}async drapeWater(t,e,s,i){if(t.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.set(t,e,s,(o,r)=>this.groundYOfPatch(a,o,r),i,this.patchSpacingM(a)),ds.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=H(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BNxlYNtW.js");return{WaterSystem:t}},__vite__mapDeps([38,4,6]),import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,s){const i=this.terrainProviders.railways;if(!i||s>N.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===t&&n.lng===e&&n.radiusM===s){this.drapeRailways(n.lines,t,e,s);return}n&&Math.hypot(ot(t,e,n.lat,n.lng).x,ot(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,t,e,s),this.awaitArrival(i.getRailways(xr(t,e,s)).then(a=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:s,lines:a},this.drapeRailways(a,t,e,s)}),N.ROADS_PATIENCE_MS).catch(a=>{console.warn("Railways unavailable, drawing none:",a)})}async drapeRailways(t,e,s,i){if(!this.railwaySystem&&!t.some(o=>o.level>=0))return;const n=await this.loadRailwaySystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.setGroundSpacing(this.patchSpacingM(a)),n.set(t,e,s,(o,r)=>this.groundYOfPatch(a,o,r),i),ds.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=H(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-KlBj8mLP.js");return{RailwaySystem:t}},__vite__mapDeps([39,4,6]),import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,s)=>this.groundYOfPatch(t,e,s)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=H(async()=>{const{TraceSystem:t}=await import("./TraceSystem-CiBRo1aU.js");return{TraceSystem:t}},__vite__mapDeps([40,4,6,1,2,3,5,7,8,9,10]),import.meta.url).then(({TraceSystem:t})=>{const e=new t(dl);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,s=this.terrainMeshOrigin;!t||!e||!s||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,s.lat,s.lng,this.siteElevationM,(i,n)=>this.groundYOfPatch(e,i,n)))}buildingFootprints(t,e){const s=this.decorOriginInRoads(t,e);return this.decorObjects.filter(i=>i.kind==="building"&&!i.observerSide&&!i.track).map(i=>{const n=C.naturalSize(i.kind,i.floors),a=(i.headingDeg??0)*Math.PI/180;return{x:s.x+i.eastM,z:s.z-i.northM,alongX:Math.sin(a),alongZ:-Math.cos(a),halfAlongM:(i.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(i.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(t,e){const s=this.decorReferencePose;return s?.lat!==void 0&&s.lng!==void 0?ot(s.lat,s.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const s=this.decorOriginInRoads(t,e);return this.decorObjects.filter(i=>i.kind==="streetlight"&&!i.lamp?.supposed&&!i.track).map(i=>({x:s.x+i.eastM,z:s.z-i.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const s=this.decorOriginInRoads(t,e);for(const i of this.decorObjects){if(i.kind!=="streetlight"||!i.lamp?.supposed||i.track)continue;const n=s.x+i.eastM,a=s.z-i.northM,o=this.roadSystem.atKerb(n,a);(o.x!==n||o.z!==a)&&this.lampNudges.set(i.id,{eastM:o.x-n,northM:-(o.z-a)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((s,i)=>{const n=e[i];if(s.id!==n.id||(s.track?.length??-1)!==(n.track?.length??-1))return!1;const a=new Set([...Object.keys(s),...Object.keys(n)]);for(const o of a)if(!(o==="eastM"||o==="northM"||o==="track")&&s[o]!==n[o])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,s=this.terrainProviders.roads;if(!e||!s)return;const i=this.wallsOf(t,e.lat,e.lng),n=this.roadWalls;n?.lat===e.lat&&n.lng===e.lng&&n.walls.length===i.length&&n.walls.every((o,r)=>o.what===i[r].what&&Math.hypot(o.x-i[r].x,o.z-i[r].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,s.contemporary)}wallsOf(t,e,s){const i=this.decorOriginInRoads(e,s);return t.filter(n=>n.kind==="building"||n.kind==="streetlight").map(n=>({what:`${n.kind}:${n.lamp?.supposed?"s":""}${n.headingDeg??0}:${n.sizeM?.widthM??""}:${n.sizeM?.lengthM??""}`,x:i.x+n.eastM,z:i.z-n.northM}))}roadWalls;drapeRoads(t,e,s,i){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(t,e,s,(a,o)=>this.groundYOfPatch(n,a,o),i,this.terrainRadius,new Jt(this.buildingFootprints(e,s),this.surveyedLamps(e,s))),this.roadWalls={lat:e,lng:s,walls:this.wallsOf(this.decorObjects,e,s)},this.lampsToKerb(e,s),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,s]=this.sunArriving,i=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/i,1,s/i),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?_e.LENS_K:_e.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(cy(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const s=!Uy(e,t),i=e.precipitationType!==t.precipitationType,n=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;e.visibilityKm!==t.visibilityKm&&this.terrainMesh&&this.terrainMeshOrigin&&it.farRingRadiusFor(t.visibilityKm)!==it.farRingRadiusFor(e.visibilityKm)&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),(e.relativeHumidity!==t.relativeHumidity||e.visibilityKm!==t.visibilityKm||i||n)&&this.restateHaze(),s&&(this.buildClouds(),this.buildCirrus()),i?this.buildPrecipitation():n&&this.updatePrecipitationDensity(),this.lastAstronomy&&(s&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(s||i||n)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=Yy,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(N.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=N.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=N.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const s of this.decorGroups.values())s.removeFromParent(),C.dispose(s);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(s=>s.kind==="streetlight").sort((s,i)=>Math.hypot(s.eastM,s.northM)-Math.hypot(i.eastM,i.northM)).slice(0,vy);for(const s of t){const i=C.build(s,s.lit??!1);this.scene.add(i),this.decorGroups.set(s.id,i),s.kind==="streetlight"&&e.includes(s)&&this.addStreetlightLight(s.id,i,e.indexOf(s)<yy,s.lamp),s.model&&s.id.startsWith(Nt.ID_PREFIX)?(this.pendingTrafficModels.set(s.id,s),this.awaitArrival(this.loadDecorModel(s,this.decorModelToken,!0))):this.reuseLoadedDecorModel(s,i)||this.awaitArrival(this.loadDecorModel(s,this.decorModelToken))}this.decorLamps=N.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(s=>s.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=H(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-D2AR5Zgy.js");return{ContrailSystem:t}},__vite__mapDeps([41,4,42]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),s=this.lastAstronomy?.sun,i=N.CONTRAIL_SCATTERING,n=this.skyLight.color,a=[n.r*i*.5,n.g*i*.5,n.b*i*.5];if(e&&s){const o=ms.litFraction(e.sunElevationDeg,e.heightM);if(o>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),c=At.illuminanceOf(s.magnitude)*this.relativeScale;for(let h=0;h<3;h++)a[h]+=i*c*r[h]*o}}return a}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,s){if(this.skyEventsStart=s,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let i=!1;const n=new Set;for(const a of fu){const o=vn.of(a);n.add(o.key);const r=vn.eventsOf(t,o);let c=this.skyEventLayers.get(o.key);if(c?.kind!==o&&c&&(this.disposeSkyEventLayer(o.key,c),c=void 0),!(!c&&r.length===0)){if(!c)c={kind:o,events:r},this.skyEventLayers.set(o.key,c);else if(c.events===r)continue;c.events=r,i||=o.reachM!==void 0,this.loadSkyEventSimulation(c)}}for(const[a,o]of this.skyEventLayers)n.has(a)||(this.disposeSkyEventLayer(a,o),i||=o.kind.reachM!==void 0);i&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const s=e();(s.inSky?this.celestialGroup:this.scene).add(s.object),t.simulation=s,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[]),this.skyEventCloudLight(t,[])}skyEventCloudLight(t,e){e.length===0?this.skyEventCloudLights.delete(t):this.skyEventCloudLights.set(t,e),this.layeredClouds?.setLights([...this.skyEventCloudLights.values()].flat(),this.camera.position)}skyEventClouds(){const t=this.layeredClouds?.volumes??[];if(t.length===0)return;const e=this.camera.position,s={x:0,y:0,z:0};return{bottomY:Math.min(...t.map(i=>i.uniforms.baseM.value)),topY:Math.max(...t.map(i=>i.uniforms.baseM.value+i.uniforms.thicknessM.value)),extinctionAt:(i,n,a)=>{s.x=i-e.x,s.y=n-e.y,s.z=a-e.z;let o=0;for(const r of t)o+=r.densityAt(s);return o*.006},dim:i=>nh.apply(i,t)}}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(s=>this.farEmitterOf(s.position,s.magnitude)).filter(s=>s!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const s=`skyEvent:${t}:`,i=new Set;for(const n of e){const a=s+n.key,{x:o,y:r,z:c}=Vt(n.position.altitudeDeg,n.position.azimuthDeg,de),[h,l,d]=this.arrivingIlluminance(n.position,n.magnitude,this.cloudTransmission(n.position));this.setGlare(a,o,r,c,[h*n.fade,l*n.fade,d*n.fade],0,N.POINT_VEIL_HOLD_DEG),i.add(a)}for(const n of[...this.glareSprites.keys()])n.startsWith(s)&&!i.has(n)&&this.disposeGlare(n)}skyEventReachM(t){let e=0;for(const s of this.skyEventLayers.values())s.events.length>0&&s.kind.reachM&&(e=Math.max(e,s.kind.reachM(s.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,s={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},i=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,n=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Er(-90,this.instrumentMagnitudeGain);let a;for(const[o,r]of this.skyEventLayers)r.simulation&&(a??={observer:s,date:i,magnitudeLimit:n,cloudTransmission:c=>this.cloudTransmission(c),arrivingIlluminance:(c,h,l)=>this.arrivingIlluminance(c,h,l),transmittanceFromSpace:c=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,c.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(c,h,l)=>this.transmittanceTo(c,h,l),groundYAt:(c,h)=>this.groundYUnder(c,h),clouds:this.skyEventClouds(),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Mt)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Mt)*this.weather.windSpeed}},r.simulation.update(r.events,this.decorTime,{...a,lightFrom:c=>this.skyEventLight(o,c),glareFrom:c=>this.skyEventGlare(o,c),lightClouds:c=>this.skyEventCloudLight(o,c)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?Vt(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}directionToDecor(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const s=new ee().setFromObject(e);if(s.isEmpty())return;const i=s.getCenter(new D),n=this.camera.getWorldPosition(new D),a=i.x-n.x,o=n.z-i.z,r=i.y-n.y,c=Math.hypot(a,o);if(!(c===0&&r===0))return{azimuthDeg:(Math.atan2(a,o)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(r,c)*180/Math.PI}}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,s=this.groundYUnder(t,e),i=this.bodyEastScale,n=this.farRing?.mesh??(this.terrainMesh&&this.terrainRadius>it.ROADS_MAX_RADIUS_M?this.terrainMesh:void 0),a=n?(o,r)=>it.curvatureDropM(Math.hypot(o-n.position.x,r-n.position.z)):void 0;return{heightAt:(o,r)=>this.groundYUnder(t+o*i,e-r)-s,...a?{dropAt:(o,r)=>a(t+o*i,e-r)-a(t,e)}:{}}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*Mt)/Math.cos(t.lat*Mt)}bodyMaskedByDecor(t,e){const s=this.decorGroups.get(e);return s?this.bodySystem.maskedShare(t,s):void 0}setBodies(t,e=0,s=t.map(a=>a.id),i=[],n){this.lastBodies=[t,e,s,i,n];const{x:a,z:o}=this.bodyOrigin,r=this.scatteredSky,c=this.bodyEastScale;Math.abs(c-1)>1e-9&&(t=t.map(l=>({...l,eastM:l.eastM*c}))),this.bodySystem.set(t,{originX:a,originZ:o,originGroundY:this.groundYUnder(a,o),eye:this.camera.position,groundYAt:(l,d)=>this.groundYUnder(l,d),wind:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(l,d,f)=>this.transmittanceTo(l,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y),daylight:this.daylightOnBodies(),sunAloft:this.sunAloft()},e,r?Object.assign((l,d)=>r.relativeOfLuminance(l,d),{recorded:r.recorded}):void 0,s),this.bodySystem.setSmoke(i,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}daylightOnBodies(){const t=this.celestialLight.color,e=this.celestialLight.intensity,s=this.skyLight.color,i=this.skyLight.groundColor,n=this.skyLight.intensity;return{towardSun:this.lightDirection,sun:[t.r*e,t.g*e,t.b*e],round:[(s.r+i.r)/2*n,(s.g+i.g)/2*n,(s.b+i.b)/2*n],sky:[s.r*n,s.g*n,s.b*n],ground:[i.r*n,i.g*n,i.b*n]}}sunAloft(){const t=this.lastAstronomy?.sun;if(!t)return;const{x:e,y:s,z:i}=Vt(t.altitudeDeg,t.azimuthDeg,1),n=new D(e,s,i),a=At.illuminanceOf(t.magnitude)*this.relativeScale,o=Math.sin(t.altitudeDeg*Mt),r=Math.cos(t.altitudeDeg*Mt),c=Math.sin(t.azimuthDeg*Mt),h=Math.cos(t.azimuthDeg*Mt),l=this.sceneSunBeam;let d;return{towardSun:n,beamAt:(f,m,p)=>{const g=this.siteElevationM+Math.max(0,p),M=(c*f+h*m)/N.EARTH_RADIUS_M,v=Math.asin(Math.max(-1,Math.min(1,o+r*M)))/Mt,y=ms.litFraction(v,g);if(y<=0)return;const w=this.air.transmittanceFromSpace(g,v),b=g>=N.ABOVE_CLOUD_M?1:d??=this.cloudTransmission(t),E=[0,0,0];for(let A=0;A<3;A++)E[A]=Math.max(0,a*w[A]*y*b-l[A]);return E[0]>0||E[1]>0||E[2]>0?E:void 0}}}static EARTH_RADIUS_M=6371e3;plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,s=this.skyLight.color,i=this.skyLight.groundColor,n=this.skyLight.intensity,a=(o,r,c)=>(o*e+(r+c)/2*n)/Math.PI;return[a(t.r,s.r,i.r),a(t.g,s.g,i.g),a(t.b,s.b,i.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,s=this.modelUrl(t)??e?.url,i=t.credit??e?.credit;if(!(!s||!i))return{scene:await Qh(s),credit:i,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const s=this.loadedDecorModels.get(t.id);return!s||s.ref!==JSON.stringify(Bc(t))||!C.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,s),!0)}applyLoadedDecorModel(t,e,s){const i=Mp(s.scene);i.traverse(n=>{n instanceof B&&(n.userData.sharedModel=!0)}),C.applyModelParameters(i,t.modelParameters,s.bindings),C.applyModel(e,t,i,{headingOffsetDeg:s.headingOffsetDeg,depictedSizeM:s.depictedSizeM}),this.mirrors.adopt(i),this.decorModelCredits.set(t.id,s.credit)}mirrors=new Is;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,s=!1){const i=s?hg[t.kind]:Bc(t);if(!(!i||!C.usesModel(t)))try{const n=i.url?void 0:i.id?await this.decorModelProvider.entry(i.id):void 0,a=this.modelUrl(i)??n?.url,o=i.credit??n?.credit;if(!a||!o)return;const r=s||t.kind==="tree"?await this.standInScene(a):await Qh(a);if(e!==this.decorModelToken||s&&!this.pendingTrafficModels.has(t.id))return;const c=this.decorGroups.get(t.id);if(!c)return;!s&&t.kind!=="tree"&&(G.glaze(r),ds.reflectOn(r));const h={ref:JSON.stringify(i),scene:r,headingOffsetDeg:i.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:o,bindings:n?.parameters?.bindings};s||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,c,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${t.id}":`,n)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=Qh(t).then(s=>(/jungle-jim-realistic-trees/.test(t)||ds.reflectOn(s),s)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,s=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=s;const i=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?ot(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},n=this.decorObjects.find(m=>m.observerSide!==void 0&&Bo(m.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,n?0:this.gaitOffset.eastM,n?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),n||(i.x-=this.gaitOffset.eastM,i.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const a={x:0,z:0};let o=0,r;if(n){const m=wi(n,s),p=C.occupantView(n,m.headingDeg),g=-(m.headingDeg??0)*Mt,M=p.x*Math.cos(g)+p.z*Math.sin(g),v=-p.x*Math.sin(g)+p.z*Math.cos(g),y=m.eastM+i.x,w=-m.northM+i.z;a.x=-(y+M),a.z=-(w+v),this.camera.position.y=this.groundYUnder(y,w)+p.eyeY,r=p.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Mt,-(p.headingDeg+this.indoorLookYawDeg)*Mt,0,"YXZ")}this.bodyOrigin={x:i.x+a.x,z:i.z+a.z};const c=this.findCabin(s,i,a);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(s,i,a);const h=this.terraces.map(m=>[m.x,m.z,m.cos,m.sin,m.halfWidthM,m.halfLengthM,m.levelY].map(p=>p.toFixed(3)).join(",")).join(";");!n&&this.terraces.length>0&&(this.poseAltitudeM!==void 0&&(this.poseElevationM=Math.max(0,this.poseAltitudeM-this.siteElevationM-this.groundYUnder(0,0))),this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const m of this.decorObjects){if(m.kind==="terrace")continue;const p=this.decorGroups.get(m.id);if(!p)continue;const g=wi(m,s),M=this.lampNudges.get(m.id),v=g.eastM+(M?.eastM??0)+i.x+a.x,y=-(g.northM+(M?.northM??0))+i.z+a.z,w=this.terrainMesh,b=`${w?.geometry.uuid}:${(v-(w?.position.x??0)).toFixed(3)}:${(y-(w?.position.z??0)).toFixed(3)}:${(w?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(p.userData.footprintKey!==b){if(m.kind==="wire"){const O=C.wireGround(m,v,y,g.headingDeg,(P,k)=>this.groundYUnder(P,k));p.userData.footprintGroundY=O.startY,C.shearWire(p,C.sizeOf(m).lengthM,O.dropM)}else if(m.kind==="crossing"){const O=this.groundYUnder(v,y),P=-(g.headingDeg??0)*Mt,k=Math.cos(P),_=Math.sin(P);p.userData.footprintGroundY=O,ft.drape(C.bodyOf(p),(rt,lt)=>this.groundYUnder(v+rt*k+lt*_,y-rt*_+lt*k)-O)}else p.userData.footprintGroundY=this.groundUnderFootprint(m,v,y,g.headingDeg,g.altitudeM);p.userData.footprintKey=b}const A=g.altitudeM>N.AIRBORNE_M&&Math.hypot(v,y)<N.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseStatedElevationM:p.userData.footprintGroundY,S=m.id.startsWith(Nt.ID_PREFIX)?N.trafficHeight(g.altitudeM,p.userData.footprintGroundY):A+g.altitudeM;if(p.position.set(v,S,y),m.kind==="crop"){const O=Math.hypot(v,y);p.visible=O<=ky}const x=this.decorPresence.get(m.id),T=x!==void 0&&(s<x.fromMs||s>x.untilMs);x&&(p.visible=!T);const I=this.decorSunlight.get(m.id);I&&!T&&this.lightFromAbove(p,I),g.headingDeg!==void 0&&(p.rotation.y=-g.headingDeg*Mt);const R=lg(m,s);if(R!==void 0&&N.turnHead(p,g.headingDeg??0,R),m.kind==="crop"&&p.visible){const O=this.terrainMesh,P=[O?.geometry.uuid,v-(O?.position.x??0),y-(O?.position.z??0),p.position.y-(O?.position.y??0),g.headingDeg,g.altitudeM].map(k=>typeof k=="number"?k.toFixed(4):k).join(":");p.userData.cropGroundKey!==P&&(C.fitCropToGround(p,(k,_)=>this.groundYUnder(k,_)+g.altitudeM),p.userData.cropGroundKey=P)}if(!T){const O=p.position.distanceTo(this.camera.position);o=Math.max(o,O),O<N.trafficModelRangeM(m)&&this.pendingTrafficModels.delete(m.id)&&this.loadDecorModel(m,this.decorModelToken)}}if(n&&r!==void 0){const m=this.decorGroups.get(n.id);m&&(this.camera.position.y=m.position.y+r)}this.updateContrails(),this.updateSkyEvents();const l=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(vc*1.2,this.groundRadius*2.5,o*1.2,l*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const s=this.terrainYUnder(t,e);let i=s;for(const n of this.terraces){const a=t-n.x,o=e-n.z,r=a*n.cos-o*n.sin,c=a*n.sin+o*n.cos;if(Math.abs(r)<=n.halfWidthM&&Math.abs(c)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(r))/n.bankM)),l=h*h*(3-2*h);i=Math.max(i,l*n.levelY+(1-l)*Math.min(n.levelY,s))}}return i}placeTerraces(t,e,s){this.terraces=[];const i=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const a=this.decorGroups.get(n.id);if(!a)continue;const o=wi(n,t),r=o.eastM+e.x+s.x,c=-o.northM+e.z+s.z,h=C.sizeOf(n),l=-(o.headingDeg??0)*Mt,d=Math.cos(l),f=Math.sin(l),m=`${i?.geometry.uuid}:${(r-(i?.position.x??0)).toFixed(3)}:${(c-(i?.position.z??0)).toFixed(3)}:${(i?.position.y??0).toFixed(3)}:${o.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;a.position.set(r,0,c),o.headingDeg!==void 0&&(a.rotation.y=l),a.userData.terraceKey!==m&&(a.userData.terraceLevelY=C.fitTerrace(a,n,(p,g)=>this.terrainYUnder(r+p*d+g*f,c-p*f+g*d)),a.userData.terraceKey=m),this.terraces.push({x:r,z:c,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:a.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const s=this.terrainMesh;return s?s.position.y+this.groundYOfPatch(s,t-s.position.x,e-s.position.z):Al}horizonAltitudeDeg(t){const e=this.camera.position,s=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;s!==this.horizonFor&&(this.horizonFor=s,this.horizonByBearing.fill(Number.NaN));const i=this.horizonByBearing.length,n=Math.round((t%360+360)%360/(360/i))%i;let a=this.horizonByBearing[n];return Number.isNaN(a)&&(a=this.horizonByBearing[n]=this.marchHorizon(n*360/i)),a}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+N.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const s=this.camera.position,i=t*Math.PI/180,n=Math.sin(i),a=-Math.cos(i),o=this.farRing?.mesh,r=Math.max(this.terrainRadius,o?this.farRingRadiusM:0),c=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let l=c;l<=r;l=Math.max(l+c,l*1.02)){const d=s.x+n*l,f=s.z+a*l,m=l<=this.terrainRadius?this.terrainYUnder(d,f):o.position.y+this.groundYOfPatch(o,d-o.position.x,f-o.position.z);h=Math.max(h,Math.atan2(m-s.y,l))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,s){const i=t.geometry.getAttribute("position"),n=Math.round(Math.sqrt(i.count));if(n<2||n*n!==i.count)return Al;const a=i.getX(0),o=i.getX(n-1),r=i.getZ(0),c=i.getZ((n-1)*n),h=Oi((e-a)/(o-a)*(n-1),0,n-1),l=Oi((s-r)/(c-r)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(l))return Al;const d=Math.min(Math.floor(h),n-2),f=Math.min(Math.floor(l),n-2),m=h-d,p=l-f,g=(b,E)=>i.getY(b*n+E),M=g(f,d),v=g(f,d+1),y=g(f+1,d),w=g(f+1,d+1);return m+p<=1?M+(v-M)*m+(y-M)*p:w+(y-w)*(1-m)+(v-w)*(1-p)}groundUnderFootprint(t,e,s,i,n=0){return C.groundUnderFootprint(t,e,s,i,(a,o)=>this.groundYUnder(a,o),n)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;poseStatedElevationM=0;poseAltitudeM;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=Cs.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,s,i,n){const a=t&&e!==void 0&&e>0&&s!==void 0&&s>0?{kind:t.kind,iso:i??t.iso,autoExposure:t.autoExposure===!0&&i===void 0,maxIso:t.maxIso,metering:n??t.metering??"average",exposureSeconds:e,fNumber:s,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}:void 0;JSON.stringify(a)!==JSON.stringify(this.medium)&&(this.medium=a,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),s=t?Cs.NONE:this.perception??Cs.NONE;if(ne.uColorVision.value.set(...s.colorMatrix),ne.uContrast.value=s.contrastGain,!t){ne.uMedium.value=0;return}const i=t.kind==="sensor"&&t.development==="computational";ne.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:i?4:3;const n=t.autoExposure?this.frameLight:void 0,a=t.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,o=a===void 0?void 0:this.meteredBodies(),r=a===void 0?void 0:a+o.mean,c=d=>zn.middleGreys(1/e,t.exposureSeconds,d,t.fNumber,this.filterTransmittance);let h=r!==void 0&&r>0?1/(e*r):void 0;h!==void 0&&t.metering==="highlights"&&o.brightest>0&&(h=Math.min(h,N.HIGHLIGHT_KEPT_AT/(.18*e*o.brightest))),h!==void 0&&t.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,N.ZONE_KEPT_AT/(.18*e*n.brightest)));const l=h!==void 0?Math.min(h,t.maxIso!==void 0?c(t.maxIso):1/0):c(t.iso);ne.uMediumExposure.value=l,ne.uPhoneStrength.value=i&&r!==void 0&&r>0?fi.strengthFor(fi.MID_GREY*l*e*r):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,s=2*Math.atan(Math.tan(e/2)*t.aspect),i=4*Math.asin(Math.sin(s/2)*Math.sin(e/2)),n=new D;let a=0,o=0;for(const{position:r,luminanceCdM2:c,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(r).project(t),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(a+=c*h,o=Math.max(o,c*Math.min(1,h/(N.HIGHLIGHT_SHARE*i))**2));return{mean:a/i,brightest:o}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),s=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/s)}bloomSize=new ht;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,s=this.siteElevationM+t.position.y;return this.air.transmittance(e,s,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const s=this.lampBloomRadiusRad();for(const i of this.decorObjects){const n=this.decorGroups.get(i.id);if(n&&i.lights?.length&&C.setLights(n,i.lights,t,n.position.distanceTo(this.camera.position),e,this.relativeScale,s,this.lampTransmittance(n),this.camera.position),i.kind!=="streetlight"&&i.kind!=="vehicle")continue;const a=this.decorGroups.get(i.id);if(!a)continue;const o=i.kind==="vehicle"?om(i,t):void 0,r=o!==void 0?Hl.lamps(o):Lu(i,t,this.lastAstronomy?.sun.altitudeDeg);C.setLit(a,i.kind,r,this.relativeScale,i.lamp);const c=this.streetlightLights.get(i.id);c&&(c.visible=r),o!==void 0&&(this.headlightSettings.set(i.id,o),this.aimDecorBeam(i,a,o))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=H(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-D5-78PFB.js");return{HeadlightSystem:t}},__vite__mapDeps([43,4,7]),import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),s=this.decorGroups.get(t.id);e!==void 0&&s&&this.aimDecorBeam(t,s,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,s=this.air.transmittance(t,t,e)[1];return s>0?-Math.log(Math.min(1,s))/e:.05}aimDecorBeam(t,e,s){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const i=new D(0,0,-1).transformDirection(e.matrixWorld);if(i.y=0,i.lengthSq()<1e-9)return;i.normalize();const n=C.sizeOf(t).lengthM,a=e.getWorldPosition(new D).addScaledVector(i,n/2-by);a.y+=wy;const o=C.sizeOf(t).widthM;this.headlightSystem.aim(t.id,s,a,i,o*Ey,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?Hl.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,s=t.headingDeg*Math.PI/180,i=new D(Math.sin(s),0,-Math.cos(s)),n=new D(i.x*ef,this.camera.position.y-Sy,i.z*ef);this.headlightSystem.aim("observer",e,n,i,Ay,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,s,i){const n=C.bodyOf(e),a=n.children.find(c=>c.userData.emissive);if(!a)return;const o=tf*C.lampShare(i),r=new jf(16764006,o*this.relativeScale,xy);i?.colorTemperatureK&&r.color.setRGB(...C.lampHue(i)),r.userData.candela=o,r.position.copy(a.position).multiply(n.scale),r.castShadow=s,r.shadow.mapSize.set(512,512),r.shadow.bias=-.002,e.add(r),this.streetlightLights.set(t,r)}applyWindowGlow(){const t=this.lastAstronomy;C.setLitWindowShare(t?ts.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const s=a=>{const o=Ls.luminanceOf(a);if(!(o>0))return[0,0,0];const r=W.relativeOfResponse(o)/o;return[a[0]*r,a[1]*r,a[2]*r]},i=s(t.zenith),n=s(t.horizon);return{zenith:i,horizon:n,airlight:n,skyIrradiance:[i[0]*Math.PI,i[1]*Math.PI,i[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=be.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,J0,new q(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<Fc){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const s=J0/de*(180/Math.PI),i=s/e.sunRadiusDeg,n=Vt(t.sun.altitudeDeg,t.sun.azimuthDeg,1),a=Vt(t.moon.altitudeDeg,t.moon.azimuthDeg,1),o=Math.acos(Oi(n.x*a.x+n.y*a.y+n.z*a.z,-1,1)),r=o>1e-9?Oi(e.separationDeg*i*Mt/o,0,2):0,c=Math.sin(o),[h,l]=o>1e-9?[Math.sin((1-r)*o)/c,Math.sin(r*o)/c]:[1,0],d={x:n.x*h+a.x*l,y:n.y*h+a.y*l,z:n.z*h+a.z*l},f=e.moonRadiusDeg*i;this.eclipseDiscs={sun:new D(n.x,n.y,n.z).normalize(),moon:new D(d.x,d.y,d.z).normalize(),sunRadiusRad:s*Mt,moonRadiusRad:f*Mt};const m=.01,p=(v,y)=>Vt(t.sun.altitudeDeg+v,t.sun.azimuthDeg+y,1),g={x:p(m,0).x-p(-m,0).x,y:p(m,0).y-p(-m,0).y,z:p(m,0).z-p(-m,0).z},M={x:p(0,m).x-p(0,-m).x,y:p(0,m).y-p(0,-m).y,z:p(0,m).z-p(0,-m).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:i,up:g,right:M}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new So(s*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateSkyEvents());const e=this.scatteredSky?.ambient??N.relativeSkyOf(sh(t.sun.altitudeDeg),this.relativeScale),s=e,i=this.lightUnderClouds(t),n=a=>i?[0,1,2].map(o=>a[o]*i.through+i.radiance[o]*(1-i.through)):[a[0],a[1],a[2]];this.baseFogColor=[s.horizon[0],s.horizon[1],s.horizon[2]],this.airlight=n(s.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Z.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const a of this.streetlightLights.values())a.intensity=(a.userData.candela??tf)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,s.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const s=(this.hazeOpticalDepth()??$.DEFAULT_AEROSOL_OPTICAL_DEPTH)*$.aerosolDensity(this.siteElevationM+this.observerElevationM),i=this.cloudTransmission(t),n=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=At.aureoleScale(s,At.airMass(t.altitudeDeg))*i,o=At.coronaScale(n),r=At.illuminanceOf(t.magnitude),c=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),o.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(c===this.lunarDiffractionKey)return;this.lunarDiffractionKey=c,this.lunarDiffraction||(this.lunarDiffraction=new qu,this.celestialGroup.add(this.lunarDiffraction.object));const h=At.profile(At.HAZE_COARSE_MODE),l=At.profile(At.CLOUD_DROPLETS),d=rp(t.altitudeDeg),f=new Float32Array(At.STEPS*3);let m=0;for(let v=0;v<At.STEPS;v++){const y=v*3,w=[0,1,2].map(E=>r*d[E]*(a*h[y+E]+o*l[y+E])),b=Ls.shown(w,Ls.luminanceOf(w),(E,A)=>e.relativeOfLuminance(E,A));f.set(b,y),m=Math.max(m,Ls.response(b))}const{x:p,y:g,z:M}=Vt(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:p,y:g,z:M}:void 0,f)}applyAir(){this.scene.fog instanceof jn||(this.scene.fog=new jn),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,s){const i=this.camera.position;return this.air.transmittance(this.siteElevationM+i.y,this.siteElevationM+e,Math.hypot(t-i.x,e-i.y,s-i.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}hazeOpticalDepth(){return us.aerosolOpticalDepthOf(this.weather,this.siteElevationM)}restateHaze(){this.air=us.of(this.weather,this.siteElevationM),this.applyAir();const t=this.hazeOpticalDepth(),e=ya.OPTICAL_DEPTH_STEP;this.scatteredSky?.setConditions({aerosolOpticalDepth:t===void 0?void 0:Math.round(t/e)*e}),this.pumpScatteredSky()}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.weather.visibilityKm!==void 0&&this.restateHaze(),this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,s,i]=this.air.transmittance(t,t,N.UMBRA_PATH_M),n=.2126*e+.7152*s+.0722*i;return n>0?[(.4124*e+.3576*s+.1805*i)/n,1,(.0193*e+.1192*s+.9505*i)/n]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:be.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?be.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:U.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?Iy:Dy),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new IM(ml),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Er(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,s=>this.cloudTransmission(s),(s,i)=>this.arrivingIlluminance(s,i,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}decorSkyPoint(t){const e=this.decorGroups.get(t);if(!e?.visible)return;const s=new D().copy(e.position).sub(this.camera.position),i=s.length();if(i===0)return;const n=(Math.atan2(s.x,-s.z)*180/Math.PI+360)%360,a=Math.asin(s.y/i)*180/Math.PI;return{sky:{azimuthDeg:n,altitudeDeg:a,distanceKm:i/1e3},altitudeM:this.siteElevationM+e.position.y}}flightScreenPoint(t){const e=Nt.declaredIdOf(t);if(e!==void 0){const i=this.decorGroups.get(e);if(!i?.visible)return;const n=new D().copy(i.position).sub(this.camera.position),a=this.screenPointOf(n.clone().normalize());return a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY,n.length())?a:void 0}const s=`${Nt.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(s))continue;const a=this.screenPointOf(new D().copy(n.position).sub(this.camera.position).normalize());if(a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY))return a}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.direction,i=Math.cos(bc*this.camera.fov*Math.PI/180);let n,a=i;const o=new D;for(const[r,c]of this.decorGroups){if(!c.visible||!r.startsWith(Nt.ID_PREFIX))continue;o.copy(c.position).sub(this.camera.position).normalize();const h=o.dot(s);h>a&&(a=h,n=r)}return n&&!this.groundHides(t,e)?n:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=Math.cos(bc*this.camera.fov*Math.PI/180),i=this.satelliteField.nearest(this.raycaster.ray.direction,s);return i&&this.groundHides(t,e)?void 0:i}updateCelestialLight(t,e){const s=this.relativeScale,i=t.sun.altitudeDeg>=cr,n=!i&&t.moon.altitudeDeg>=cr,a=i?t.sun:t.moon,o=[0,0,0],r=Math.max(0,Math.sin(Math.max(a.altitudeDeg,0)*Mt)),c=this.siteElevationM+this.observerElevationM;let h=a,l=i||n?P0.directFraction(a.altitudeDeg,c):0;i&&l<=0&&t.moon.altitudeDeg>=cr&&(h=t.moon,l=P0.directFraction(h.altitudeDeg,c));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Mt)),f=i||n?this.cloudTransmission(a):1,m=-Math.log(Math.max(f,1e-6)),p=Math.max(0,1/(1+.1125*m)-f),g=[0,0,0];if(i||n){const E=At.illuminanceOf(a.magnitude)*s,A=this.air.transmittanceFromSpace(c,a.altitudeDeg);for(let I=0;I<3;I++)g[I]=E*A[I]*p*r,this.cloudBeam[I]=E*A[I];const{x:S,y:x,z:T}=Vt(a.altitudeDeg,a.azimuthDeg,1);if(this.cloudBeamDirection.set(S,x,T),l>0){const I=At.illuminanceOf(h.magnitude)*s,R=h===a?A:this.air.transmittanceFromSpace(c,h.altitudeDeg),O=h===a?f:this.cloudTransmission(h);for(let P=0;P<3;P++)o[P]=I*R[P]*O*l}}else this.cloudBeam.fill(0);const M=this.surroundings;if(M)this.skyLight.color.setRGB(M.up[0]*s,M.up[1]*s,M.up[2]*s),this.skyLight.groundColor.setRGB(M.down[0]*s,M.down[1]*s,M.down[2]*s);else{const E=this.skyCloudTransmission(),A=e.skyIrradiance,S=[0,1,2].map(T=>A[T]*E+g[T]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const x=J.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(x*(S[0]+o[0]*d),x*(S[1]+o[1]*d),x*(S[2]+o[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[o[0],o[1],o[2]]:[0,0,0],!i&&!n||l<=0){this.celestialLight.intensity=0;return}const{x:v,y,z:w}=Vt(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(v,y,w),this.celestialLight.shadow.normalBias=gl*Oi(y/dy,.1,1),this.placeShadowFrustum();const b=Math.max(o[0],o[1],o[2],1e-30);this.celestialLight.color.setRGB(o[0]/b,o[1]/b,o[2]/b),this.celestialLight.intensity=b,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const s=this.lastAstronomy?.sun,i=[0,0,0];if(s){const n=ms.litFraction(e.sunElevationDeg,e.heightM);if(n>0){const a=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),o=At.illuminanceOf(s.magnitude)*this.relativeScale,r=e.heightM>=N.ABOVE_CLOUD_M?1:this.cloudTransmission(s);for(let c=0;c<3;c++)i[c]=Math.max(0,o*a[c]*n*r-this.sceneSunBeam[c])}}t.traverse(n=>{const a=n.material;if(!(a instanceof ci||a instanceof un)||n.userData.emissive)return;a.map&&!a.emissiveMap&&(a.emissiveMap=a.map,a.needsUpdate=!0);const o=N.MEAN_COSINE/Math.PI;a.emissive.setRGB(a.color.r*i[0]*o,a.color.g*i[1]*o,a.color.b*i[2]*o)})}lightDirection=new D(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,s=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,i=this.shadowAxisX.crossVectors(this.shadowUp,t);i.lengthSq()<1e-8&&i.set(1,0,0),i.normalize();const n=this.shadowAxisY.crossVectors(t,i).normalize(),a=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),o=c=>{const h=a.dot(c)/s;return(h-Math.round(h))*s},r=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(i,o(i)).addScaledVector(n,o(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(r).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const s=e.camera,i=uy;s.left=-i,s.right=i,s.top=i,s.bottom=-i,this.shadowHalfExtentM=i,this.shadowLightDistanceM=Ec+5,s.near=this.shadowLightDistanceM-Ec,s.far=this.shadowLightDistanceM+Ec,s.updateProjectionMatrix(),e.bias=-.004/(2*Ec),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(s=>{const i=s.material;for(const n of Array.isArray(i)?i:i?[i]:[]){const a=n;a.isMeshStandardMaterial&&a.envMapIntensity!==N.CABIN_SKY_SHARE&&(a.envMapIntensity=N.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(ly,Math.max(sn,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const s=this.celestialLight.shadow,i=s.camera;i.left=-e,i.right=e,i.top=e,i.bottom=-e;const n=Math.max(ja,e*(ja/sn));this.shadowLightDistanceM=Math.max(de,n+10),i.near=this.shadowLightDistanceM-n,i.far=this.shadowLightDistanceM+n,i.updateProjectionMatrix(),s.bias=-pl/(2*n);const a=e>2*sn?2048:1024;s.mapSize.x!==a&&(s.mapSize.set(a,a),s.map?.dispose(),s.map=null),this.placeShadowFrustum()}shadowHalfExtentM=sn;shadowLightDistanceM=de;shadowUp=new D(0,1,0);shadowAxisX=new D;shadowAxisY=new D;shadowWorld=new D;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const s of[20,45,70]){const i=s*Mt,n=Math.sin(i)*Math.cos(i)*2;for(let a=0;a<360;a+=60)t+=n*this.cloudTransmission({altitudeDeg:s,azimuthDeg:a}),e+=n}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new D(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/W.semiSaturation(W.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,s){this.meteorSystem||(this.meteorSystem=new Ke,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,s)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const s=Math.max(this.relativeScale,1e-30),i=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:n,y:a,z:o}=Vt(t.altitudeDeg,t.azimuthDeg,1);return{direction:new D(n,a,o),lux:[i[0]/s,i[1]/s,i[2]/s],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const s=je.starPointsOf(t,e);s!==this.starPoints&&(this.starPoints=s,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=s),this.render())}magnitudeLimitOf(t){const e=U.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:U.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return Er(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor))}setInstrumentGain(t,e=!1,s=0){const i=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=i-2.5*s,this.filterTransmittance=10**-s,this.scatteredSky?.setInstrument(e,i,s)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.references?.release(),this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,s=performance.now()+N.COMPILE_WAIT_MS;return new Promise(i=>{const n=()=>{if(this.contextReleased)return i();for(const a of t){const o=e.get(a)?.currentProgram;(!o||o.isReady())&&t.delete(a)}t.size===0||performance.now()>s?i():setTimeout(n,10)};n()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.scatteredSky?.invalidate(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;if(this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e),!this.pixelRatioHeld){const s=this.resolution.ratioFor(t,e);s!==this.renderer.getPixelRatio()&&this.applyPixelRatio(s)}}this.drawIfDirty()}get maxPixelRatio(){return this.resolution.maximum}pixelRatioHeld=!1;holdPixelRatio(t){this.pixelRatioHeld=t!==void 0;const e=t??this.resolution.maximum;this.renderer.getPixelRatio()!==e&&this.applyPixelRatio(e)}async controlFrame(){await this.loadControlPasses(),this.render();const t=this.drawn;return this.drawIfDirty(),this.drawn===t?void 0:{image:this.renderer.domElement.toDataURL("image/png"),...this.drawControlPasses()}}async loadControlPasses(){if(this.controlPasses)return;const{ControlPasses:t}=await H(async()=>{const{ControlPasses:e}=await import("./ControlPasses-CeExr5X1.js");return{ControlPasses:e}},__vite__mapDeps([44,4,1,2,3,5,6,7,8,9,10]),import.meta.url);this.controlPasses??=new t}drawControlPasses(){if(!this.controlPasses)throw new Error("The control passes are not loaded: see loadControlPasses");return this.controlPasses.draw({renderer:this.renderer,scene:this.scene,camera:this.camera,equidistant:this.usableEquidistantPass(),sky:[this.celestialGroup,...this.pointLayerHost.clouds(),...this.lensFlare?[this.lensFlare.mesh]:[]],isSolid:t=>N.isSolidSurface(t),drawPhenomena:t=>this.renderPhenomenaPass(t)})}controlPasses;cabinDecor(){return this.cabinGroups}enclosingDecor(){const t=this.camera.getWorldPosition(this.enclosingEye);return this.decorObjects.filter(e=>e.kind==="aircraft"||e.kind==="vehicle").map(e=>this.decorGroups.get(e.id)).filter(e=>e!==void 0&&this.enclosingBox.setFromObject(e).containsPoint(t))}enclosingEye=new D;enclosingBox=new ee;cabinGroups=[];findCabin(t,e,s){const i=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&Bo(n.kind))continue;const a=this.decorGroups.get(n.id);if(!a)continue;const o=wi(n,t),r=o.eastM+e.x+s.x,c=-o.northM+e.z+s.z,h=C.sizeOf(n),l=Math.max(h.widthM,h.lengthM)/2;Math.hypot(r,c)<l&&Math.abs(o.altitudeM-this.poseStatedElevationM-1.6)<l&&i.push(a)}return this.cabinGroups=i,i}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new ds(this.renderer);const e=["sun","moon"].flatMap(c=>this.bodyMeshes.get(c)??[]),s=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...e,...[...this.glareSprites.values()].map(c=>c.mesh),...this.bodySystem.group.children.filter(c=>c.name.startsWith("body-speck:"))],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof Us),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.enclosingDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object].filter(c=>c!==void 0),...[...this.skyEventLayers.values()].filter(c=>c.simulation?.hiddenFromEye).map(c=>c.simulation.object)],n=this.relativeScale,a=this.sceneVersion,o=this.recordingTimeMs,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,s,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],a,i,c=>this.measureSurroundings(c,n,a,o),t?0:ds.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}static adaptingLuminance(t,e){const s=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,N.GROUND_ADAPTATION_SHARE*s)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,s,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new yo,this.framePhotograph={texture:t,scale:e,atMs:i};const a=[n.sun,n.moon].filter(o=>o.altitudeDeg>-2).map(o=>Vt(o.altitudeDeg,o.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,a,o=>{const r=m=>m.map(p=>p/e);if(![...o.up,...o.down,o.logAverage].every(Number.isFinite)){this.eyeSettledVersion=s,this.skyHoldUntilMs&&this.redrawHeld();return}const c=this.surroundings,h={up:r(o.up),down:r(o.down)},l=(m,p)=>m.some((g,M)=>Math.abs(g-p[M])>.03*Math.max(Math.abs(g),Math.abs(p[M]),1e-12)),d=!c||l(c.up,h.up)||l(c.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(N.adaptingLuminance(Math.exp(o.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=s,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const s=t.sun.altitudeDeg>=cr?t.sun:t.moon.altitudeDeg>=cr?t.moon:void 0;if(!s)return;const i=this.relativeScale/Math.PI;return{through:this.cloudTransmission(s),radiance:[e.up[0]*i,e.up[1]*i,e.up[2]*i]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new di;const e=this.lastAstronomy?.sun,s=e&&e.altitudeDeg>-2?Vt(e.altitudeDeg,e.azimuthDeg,1):void 0,i=this.medium.exposureFollowMs??N.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,s,n=>{const a={mean:n.mean/t.scale,brightest:n.brightest/t.scale};if(!Number.isFinite(a.mean)||!Number.isFinite(a.brightest))return;const o=this.frameLight,r=t.atMs,c=o?r-o.atMs:1/0,h=c<0||c>N.EXPOSURE_JUMP_MS,l=h||c===0&&o?.jumped?1:1-Math.exp(-c/i),d=(p,g)=>p>0&&g>0?p*(g/p)**l:g,f={mean:d(o?.mean??0,a.mean),brightest:d(o?.brightest??0,a.brightest),atMs:r,jumped:h||c===0&&(o?.jumped??!1)};this.frameLight=f;const m=(p,g)=>Math.abs(p-g)>.01*Math.max(p,g);(!o||m(o.mean,f.mean)||m(o.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(ne.uRetinaOn.value=0,this.medium)return;const t=[];for(const o of this.emitterLights.farEmitters){const r=this.screenPointOf(o.direction);!r||Math.abs(r.ndcX)>1.2||Math.abs(r.ndcY)>1.2||t.push({ndcX:r.ndcX,ndcY:r.ndcY,lux:Ls.luminanceOf(o.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),s=e.x/Math.max(e.y,1),i={width:this.camera.fov*s,height:this.camera.fov},n=this.retina?.atMs;if((n===void 0||this.recordingTimeMs<n||this.recordingTimeMs-n>et.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new et,this.retina.replay(0,this.recordingTimeMs,o=>this.historicBleachingAt(o,s),i,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new et,this.retina.advance(this.recordingTimeMs,t,i)}this.retina.any&&(ne.uRetina.value=this.retina.texture,ne.uRetinaOn.value=1,ne.uRetinaViewport.value.copy(e))}retinaSize=new ht;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const s=this.retinaHistory?.(t);if(!s||s.views.length===0)return[];const i=s.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((i?.pitchDeg??0)*Mt,-(i?.headingDeg??0)*Mt,(i?.rollDeg??0)*Mt,"YXZ")).invert(),a=i?.fovDeg??this.camera.fov,o=[];for(const r of s.views){const c=this.farEmitterOf(r.head,r.magnitude);if(!c)continue;const h=this.screenPointIn(this.historicDirection.copy(c.direction).applyQuaternion(n),a,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||o.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:Ls.luminanceOf(c.lux)})}return o}historicQuaternion=new Oa;historicEuler=new $f;historicDirection=new D;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<N.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const s of t)s.traverse(i=>{i.userData.emissive===!0&&e.push(i)});return e}surroundings;animate(t,e){const s=Math.min(e/1e3,Ky);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,s),this.updateRain(s),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const s=e?Math.max(1,Math.round(t)):1;if(s===this.exposureInstants&&(s===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=s,this.exposureInstantAt=e,s===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),C.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const a=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...a):this.onMapSubjectBounds(a)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(a,o,r)=>this.directionAtScreenPoint(a,o,r),a=>this.screenPointOf(a)),this.references?.place(this.camera);const s=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;s>this.camera.far&&(this.camera.far=s,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[yu]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Is.INTERVAL_MS)),ne.uRodShare.value=this.scatteredSky?.rodShare??0,ne.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina(),this.waterSystem?.reflectBodies(this.renderer,this.scene,this.camera,vu,this.bodySystem.any,e&&Zt.supports(this.camera.fov,this.camera.aspect)?e.sourceFovDeg(this.camera.fov,this.camera.aspect):void 0);const i=!!this.references?.any||this.phenomena.any||this.compassSprites.some(a=>a.visible);ne.uHasOverlay.value=i?1:0;const n=i?a=>this.renderOverlayPasses(a):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const a=this.usableDepthOfFieldPass();a?a.render(this.renderer,this.scene,this.camera,n,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,a=>{this.lensFlare&&(this.lensFlare.mesh.visible=a?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Us&&e.userData.pointSource||e instanceof B&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(n=>n.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const s=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(dl),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=s,this.renderer.shadowMap.autoUpdate=i}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(vu),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=s}bodyCutOutMaterial=new $s({blending:Fo,blendSrc:gn,blendDst:gn,blendSrcAlpha:gn,blendDstAlpha:gn,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=s}setReferences(t,e){const s=t.map(i=>{const n=this.documentRelative(i.src);return n===i.src?i:{...i,src:n}});if(this.references){this.references.set(s,void 0,e);return}if(s.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:s,observerAt:e},this.referencesLoading??=H(async()=>{const{ReferenceSystem:i}=await import("./ReferenceSystem-B30-UBHY.js");return{ReferenceSystem:i}},__vite__mapDeps([45,4,46,6,47,1,2,3,5,7,8,9,10]),import.meta.url).then(({ReferenceSystem:i})=>{const n=new i(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=n,n.onFrame=()=>this.render(),this.referenceClock&&n.setTime(this.referenceClock);for(const[o,r]of this.referenceViews)n.setView(o,r);n.setShown(this.referencesShown);const a=this.pendingReferences;return this.pendingReferences=void 0,a&&n.set(a.references,void 0,a.observerAt),this.render(),n})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new D)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}get areReferencesShown(){return this.referencesShown}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const s=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const n=e?this.narrowTo(t,e):t,a=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),o=this.phenomena.furthestM;let r=0;for(const c of this.decorObjects){const h=this.decorGroups.get(c.id);if(!h)continue;const l=c.kind!=="crop"&&this.mayHide(h,t,a,o);N.markDecorDepth(h,l),l&&r++}r>0&&(t.layers.set(ul),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(yu),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=s,this.renderer.shadowMap.autoUpdate=i}phenomenaFrustum=new eg;phenomenaViewProjection=new Oe;occluderSphere=new zl;occluderEye=new D;localBounds=new WeakMap;mayHide(t,e,s,i){let n=0;t.traverse(()=>n++);let a=this.localBounds.get(t);if(!a||a.objects!==n){t.updateMatrixWorld(!0);const r=new ee().setFromObject(t);if(r.isEmpty())return!1;a={sphere:r.getBoundingSphere(new zl).applyMatrix4(new Oe().copy(t.matrixWorld).invert()),objects:n},this.localBounds.set(t,a)}const o=this.occluderSphere.copy(a.sphere).applyMatrix4(t.matrixWorld);return o.center.distanceTo(e.getWorldPosition(this.occluderEye))-o.radius>i?!1:s.intersectsSphere(o)}narrowTo(t,e){const s=this.renderer.getDrawingBufferSize(new ht),i=N.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*s.x-i)),a=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*s.y-i)),o=Math.min(s.x,Math.ceil((Math.min(1,e.x1)+1)/2*s.x+i)),r=Math.min(s.y,Math.ceil((Math.min(1,e.y1)+1)/2*s.y+i)),c=this.narrowCamera.copy(t);return t.getWorldPosition(c.position),t.getWorldQuaternion(c.quaternion),c.setViewOffset(s.x,s.y,n,s.y-r,Math.max(1,o-n),Math.max(1,r-a)),c.updateMatrixWorld(),c}narrowCamera=new Gc;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new $s({colorWrite:!1,side:tn});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,s){const i=t.getObjectByName("head");if(!i)return;const n=((s-e)%360+540)%360-180,a=Math.max(-85,Math.min(N.HEAD_TURN_LIMIT_DEG,n));i.rotation.y=-a*Mt}static isSolidSurface(t){if(!(t instanceof B))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==rs}static markDecorDepth(t,e){t.traverse(s=>{if(!(s instanceof B))return;e&&N.isSolidSurface(s)?s.layers.enable(ul):s.layers.disable(ul)})}startExposure(){this.cancelExposure(),this.references?.hold(this.camera),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new ht),e=Math.max(1,Math.round(t.x)),s=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new D2(e,s)),this.exposureAccumulation.resize(e,s),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const s=1/this.exposureInstants;this.resolution.beginDrawing();const i=performance.now()+N.EXPOSURE_BUDGET_MS,n=N.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let a=0;do{this.restateAt(t,this.exposureInstantsDone);const o=this.compassSprites.map(r=>r.visible);for(const r of this.compassSprites)r.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((r,c)=>{r.visible=o[c]})}e.add(this.renderer,s),this.exposureInstantsDone++,a++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<i&&a<n);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){ne.uRodShare.value=this.scatteredSky?.rodShare??0,ne.uHasOverlay.value=1,ne.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(o=>o.visible))return;const s=new js,i=new Ji(-1,1,1,-1,0,2),n=Sc/(nf*Math.tan(af*Mt/2));for(const o of this.compassSprites){if(!o.visible)continue;const r=o.getWorldPosition(new D).sub(this.camera.position).normalize(),c=this.screenPointOf(r);if(!c)continue;const h=new to(o.material);h.position.set(c.ndcX,c.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),s.add(h)}const a=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(s,i)}finally{this.renderer.autoClear=a}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new ee,s=new D,i=this.camera.getWorldDirection(new D),n=this.decorObjects.filter(o=>o.track?.length||o.kind==="aircraft"||o.kind==="vehicle").map(o=>this.decorGroups.get(o.id)),a=this.bodySystem.reflectors.map(o=>o.holder);for(const o of[...n,...a]){if(!o?.visible||(e.setFromObject(o),e.isEmpty())||e.distanceToPoint(this.camera.position)<N.MAP_SUBJECT_NEAREST_M)continue;let r=1/0,c=-1/0,h=1/0,l=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const m of[e.min.z,e.max.z]){if(s.set(d,f,m).sub(this.camera.position).normalize(),s.dot(i)<=0)continue;const p=this.screenPointOf(s);if(!p)continue;const g=(p.ndcX+1)/2,M=(1-p.ndcY)/2;r=Math.min(r,g),c=Math.max(c,g),h=Math.min(h,M),l=Math.max(l,M)}r=Math.max(r,0),c=Math.min(c,1),h=Math.max(h,0),l=Math.min(l,1),c>=r&&l>=h&&t.push({x:r,y:h,width:c-r,height:l-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}eyeOptics(){if(!this.eyeAsLens)return;const t=Math.max(1e-6,this.scatteredSky?.sceneAdaptation??1e3),e=4.9-3*Math.tanh(.4*Math.log10(t)),s=N.EYE_FOCAL_MM;return{focalLengthMm:s,fNumber:s/e,focusDistance:0,frameHeightMm:2*s*Math.tan(this.camera.fov*Mt/2)}}static EYE_FOCAL_MM=17;static EYE_LENS_MAX_FOV_DEG=20;get eyeAsLens(){return this.projectionKind==="equidistant"&&!this.lensOptics&&this.camera.fov<=N.EYE_LENS_MAX_FOV_DEG}usableDepthOfFieldPass(){const t=this.lensOptics??this.eyeOptics();if(!t)return;const e=this.renderer.getDrawingBufferSize(new ht),s=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new wo(s,i)),this.depthOfFieldPass.resize(s,i),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass.setAir(this.weather.visibilityKm!==void 0?this.weather.visibilityKm*1e3:void 0,this.camera.fov),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(t,e){return this.ghostPass?.holdsPictureAt(this.renderer,t,e)??!1}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,ne.uMediumExposure.value,this.sunBeyondPicture())}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new ht);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Qt(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new ht);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new Xu(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant"||this.eyeAsLens)return;const t=this.renderer.getDrawingBufferSize(new ht);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Zt(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,s){this.aimStraightAtScreenPoint(t,e,s),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,i=>{const n=N.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=i-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(t,e,s){const i=this.projectionKind==="equidistant"&&!this.eyeAsLens?this.equidistantPass:void 0;if(!i){t.setFromCamera(new ht(e,s),this.camera);return}const n=i.directionFor(e,s,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(n.x,n.y,n.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new D)}directionAtScreenPoint(t,e,s){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),s.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),s=this.renderer.getDrawingBufferSize(this.screenPointSize),i=s.x/Math.max(s.y,1);return this.screenPointIn(e,this.camera.fov,i)}screenPointIn(t,e,s){if(this.projectionKind==="equidistant"&&!this.eyeAsLens&&this.equidistantPass)return Zt.ndcFor(t,e,s);if(t.z>=0)return;const i=Math.tan(e/2*Mt);return{ndcX:t.x/-t.z/(s*i),ndcY:t.y/-t.z/i}}screenPointScratch=new D;screenPointQuaternion=new Oa;screenPointSize=new ht;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const s=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(s.x,s.y);const i=this.renderer.domElement.width,n=this.renderer.domElement.height;t.uniforms.uResolution.value.set(i,n),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const t=this.lensFlare;if(!t||!t.mesh.visible)return;const e=this.sunDiscRadiance.map(c=>Math.max(0,c-N.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const s=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,i=Math.PI*s*s,n=t.uniforms.uLensPosition.value,a=t.uniforms.uTanHalfFov.value,o=this.camera.aspect,r=wt.offFrameShare(Math.atan(Math.hypot(n.x*o,n.y)*a)*180/Math.PI,Math.atan(Math.hypot(o,1)*a)*180/Math.PI,this.ghostOptics.reachDeg);if(!(r<=0))return{x:n.x,y:n.y,radius:s,flux:[e[0]*i*r,e[1]*i*r,e[2]*i*r]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const s=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!s)return;const i=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(s.ndcX,s.ndcY),t.uniforms.uResolution.value.set(i.x,i.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(j0),this.camera.layers.set(j0),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of cf)this.isSunOccluded(e[0],e[1])||t++;return t/cf.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const s=this.decorGroups.get(e.id);s&&t.push(s)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,s=0){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),a=n.length();if(n.normalize(),e!==0||s!==0){const c=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const l=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,e*c).addScaledVector(l,s*c).normalize()}if(this.groundBlocks(this.camera.position,n,a)||this.cabinMask.hides(n))return!0;const o=this.cabinMask.any?i.filter(c=>!this.cabinGroups.includes(c)):i;if(o.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(o,!0).find(c=>!(c.object.material instanceof ps));return r!==void 0&&r.distance<a}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const s=e.mesh.getWorldPosition(this.veilTargetScratch),i=e.mesh.material.uniforms.uSourceDeg.value,n=i>.05?N.VEIL_SAMPLES:N.VEIL_SAMPLES.slice(0,1);let a=0;for(const[o,r]of n)this.isOccludedToward(s,o*i,r*i)||a++;e.share=a/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new Ts;veilTargetScratch=new D;groundBlocks(t,e,s,i=0){const n=this.groundMesh;if(n&&e.y<0){const g=(n.position.y-t.y)/e.y;if(g>i&&g<s){const M=t.x+e.x*g-n.position.x,v=t.z+e.z*g-n.position.z;if(Math.hypot(M,v)<=this.groundRadius)return!0}}const a=this.terrainMesh;if(!a)return!1;const o=a.geometry.getAttribute("position"),r=Math.round(Math.sqrt(o.count));if(r<2||r*r!==o.count)return!1;const c=[a.position.x+o.getX(0),a.position.x+o.getX(r-1)],h=[a.position.z+o.getZ(0),a.position.z+o.getZ((r-1)*r)],l=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(r-1);if(!(l>0))return!1;let d=i,f=s;for(const[g,M,v]of[[t.x,e.x,c],[t.z,e.z,h]]){const y=Math.min(v[0],v[1]),w=Math.max(v[0],v[1]);if(Math.abs(M)<1e-12){if(g<y||g>w)return!1;continue}const b=(y-g)/M,E=(w-g)/M;d=Math.max(d,Math.min(b,E)),f=Math.min(f,Math.max(b,E))}if(!(f>d))return!1;const m=Math.hypot(e.x,e.z),p=Math.min(4096,Math.max(8,Math.ceil((f-d)*m/(l/2))));for(let g=0;g<=p;g++){const M=d+(f-d)*g/p,v=t.x+e.x*M,y=t.y+e.y*M,w=t.z+e.z*M;if(y<=this.groundYUnder(v,w))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,s){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=yc;let i,n;for(const a of this.decorObjects){if(a.kind==="crop")continue;const o=this.decorGroups.get(a.id);if(!o)continue;const r=this.ufoOcclusionRaycaster.intersectObject(o,!0).find(c=>N.isSolidSurface(c.object));r&&(a.occludesSourceIds?.includes(s)?i=i===void 0?r.distance:Math.max(i,r.distance):n=n===void 0?r.distance:Math.min(n,r.distance))}return{behindM:i,inFrontM:n}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.origin,i=this.raycaster.ray.direction,n=fy*this.camera.fov*Math.PI/180,a=[...this.hitAreas.entries()].map(([h,l])=>{const d=l.getWorldPosition(new D).sub(s);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(l.scale.x/2,d.length())}}),o=this.eclipseDiscs,r=o?[{key:"sun",direction:o.sun,radiusRad:o.sunRadiusRad},{key:"moon",direction:o.moon,radiusRad:o.moonRadiusRad,inFront:!0}]:[],c=N.nearestBody(i,[...a.filter(h=>!o||h.key!=="sun"&&h.key!=="moon"),...r],n);if(c)return this.groundHides(t,e)?void 0:c}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.iceHalos.featureAt(this.raycaster.ray.direction);return s&&!this.groundHides(t,e)?s:void 0}static nearestBody(t,e,s){let i,n=1/0,a=1/0,o=!1;for(const r of e){const c=Math.acos(Oi(r.direction.dot(t),-1,1))-r.radiusRad;if(c>s)continue;const h=c<=0,l=n<=0,d=r.inFront===!0;(h!==l?h:h?d!==o?d:r.radiusRad<a:c<n)&&(i=r.key,n=c,a=r.radiusRad,o=d)}return i}pickInterpretationBodyAt(t,e){const s=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(s.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=this.raycaster.ray.origin,a=hy*this.camera.fov*Math.PI/180,o=[...this.decorGroups.values()],r=o.length>0?N.firstSolid(this.raycaster.intersectObjects(o,!0))?.distance:void 0;let c,h=1/0;const l=new ee,d=new D;for(const f of s){if(l.setFromObject(f),l.isEmpty())continue;l.getCenter(d);const m=l.getSize(new D).length()/2,p=d.clone().sub(n),g=p.length();if(g===0||p.dot(i)<=0||r!==void 0&&r<g-m)continue;const M=Math.acos(Math.min(1,p.normalize().dot(i))),v=Math.atan(m/g);if(v>a){const y=this.raycaster.intersectObject(f,!0)[0];if(!y||r!==void 0&&r<y.distance)continue}else if(M>a)continue;v<h&&(h=v,c=f.name.slice(5))}return c}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.direction,i=Math.cos(bc*this.camera.fov*Math.PI/180);let n,a=i;for(const o of this.namedStars){const r=o.direction.dot(s);r>a&&(a=r,n={star:o.star,altitudeDeg:o.altitudeDeg})}return n&&this.groundHides(t,e)?void 0:n}groundHides(t,e,s=1/0){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,s,yc)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let s=1/0,i=1/0,n=-1/0,a=-1/0;for(let o=0;o<8;o++){const r=this.bodyCornerScratch.set(o&1?e.max.x:e.min.x,o&2?e.max.y:e.min.y,o&4?e.max.z:e.min.z),c=this.screenPointOf(r.sub(this.camera.position).normalize());if(!c)return;s=Math.min(s,c.ndcX),n=Math.max(n,c.ndcX),i=Math.min(i,c.ndcY),a=Math.max(a,c.ndcY)}return{minX:s,minY:i,maxX:n,maxY:a}}bodyBoxScratch=new ee;bodyCornerScratch=new D;decorFrameScratch=new Oe;decorPartMatrix=new Oe;decorPartScratch=new ee;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const s=this.decorFrameScratch.copy(e.matrixWorld).invert(),i=this.bodyBoxScratch.makeEmpty();if(e.traverse(c=>{const h=c.geometry;!h||!c.visible||(h.boundingBox||h.computeBoundingBox(),h.boundingBox&&i.union(this.decorPartScratch.copy(h.boundingBox).applyMatrix4(this.decorPartMatrix.multiplyMatrices(s,c.matrixWorld))))}),i.isEmpty())return;let n=1/0,a=1/0,o=-1/0,r=-1/0;for(let c=0;c<8;c++){const h=this.bodyCornerScratch.set(c&1?i.max.x:i.min.x,c&2?i.max.y:i.min.y,c&4?i.max.z:i.min.z).applyMatrix4(e.matrixWorld),l=this.screenPointOf(h.sub(this.camera.position).normalize());if(!l)return;n=Math.min(n,l.ndcX),o=Math.max(o,l.ndcX),a=Math.min(a,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:n,minY:a,maxX:o,maxY:r}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,s,i=0){const n=this.decorGroups.get(t);if(!n)return;this.aimAtScreenPoint(this.raycaster,e,s);const a=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+i)),this.decorHitScratch);return a?{x:a.x,z:a.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Mt/2):0}decorGrabHeightAt(t,e,s){const i=this.decorGroups.get(t);if(!i)return 0;const n=this.bodyBoxScratch.setFromObject(i).max.y-i.position.y;this.aimAtScreenPoint(this.raycaster,e,s);const a=this.decorHitScratch.set(this.camera.position.x-i.position.x,0,this.camera.position.z-i.position.z);if(a.lengthSq()<1e-6)return 0;a.normalize();const o=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(a,i.position),r=this.raycaster.ray.intersectPlane(o,this.decorHitScratch);return r?Math.min(Math.max(r.y-i.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new yh;decorHitScratch=new D;static firstSolid(t){return t.find(e=>{const s=e.object.material;return!(Array.isArray(s)?s:[s]).some(n=>n&&(n.transparent&&n.opacity<N.SEE_THROUGH_BELOW||n instanceof ps))})}static SEE_THROUGH_BELOW=.9;pickPeakAt(t,e){const s=this.renderer.getDrawingBufferSize(new ht),i=this.camera.fov*Mt/Math.max(1,s.y),n=this.camera.getWorldPosition(new D);let a;for(const o of this.decorObjects){if(o.kind!=="peak")continue;const r=this.decorGroups.get(o.id);if(!r)continue;const c=r.getWorldPosition(new D);c.y=this.reliefYAt(c.x,c.z);const h=c.distanceTo(n),l=this.screenPointOf(c.clone().sub(n).normalize());if(!l)continue;const d=(t-l.ndcX)*s.x/2,f=(l.ndcY-e)*s.y/2,m=Math.max(10,(o.sizeM?.widthM??2e3)/2/Math.max(h,1)/i);if(f<-8||f>m*.6)continue;const p=m*Math.max(.15,f/(m*.6));if(Math.abs(d)>Math.max(10,p))continue;const g=Math.abs(d)+Math.abs(f);(!a||g<a.score)&&(a={id:o.id,score:g})}return a?.id}reliefYAt(t,e){const s=this.terrainMesh;if(s&&Math.hypot(t-s.position.x,e-s.position.z)<=this.terrainRadius)return this.terrainYUnder(t,e);const i=this.farRing?.mesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):0}pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const s=[...this.decorGroups.entries()],i=N.firstSolid(this.raycaster.intersectObjects(s.map(([,o])=>o),!0));if(!i)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<i.distance)return;let a=i.object;for(;a&&!s.some(([,o])=>o===a);)a=a.parent;return s.find(([,o])=>o===a)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const s=this.railwaySystem;if(!s||s.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray;s.group.updateMatrixWorld();const n=new sm().copy(i).applyMatrix4(new Oe().copy(s.group.matrixWorld).invert()),a=s.group.matrixWorld,o=(d,f)=>{const m=new D(d,0,f).applyMatrix4(a);return this.groundYUnder(m.x,m.z)-a.elements[13]};if(!s.mayMeet(n.origin,n.direction,o,N.RAILWAY_PICK_ABOVE_M))return;const r=N.firstSolid(this.raycaster.intersectObject(s.group,!0));if(!r||this.terrainMesh&&this.groundBlocks(i.origin,i.direction,r.distance-N.RAILWAY_GROUND_MARGIN_M,yc))return;const c=s.group.worldToLocal(r.point.clone()),h=s.lineAt(c.x,c.z);if(!h)return;const l=s.contactHeightM(h);return{line:h,distanceM:r.distance,...l!==void 0?{contactM:l}:{}}}pickSkyEventAt(t,e,s=()=>!0){const i=[...this.skyEventLayers.values()].filter(c=>c.simulation?.pick&&c.simulation.drawnCount>0&&s(c.kind,c.simulation));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,a={toleranceRad:N.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(bc*this.camera.fov*Math.PI/180),skyLightTowards:c=>this.skyLightTowards(c)};let o;for(const c of i){const h=c.simulation.pick(n.origin,n.direction,a);h&&(!o||(h.distanceM??1/0)<(o.distanceM??1/0))&&(o={kind:c.kind.key,...h})}if(!o)return;if(o.distanceM===void 0)return this.groundHides(t,e)?void 0:o;if(this.terrainMesh&&this.groundBlocks(n.origin,n.direction,o.distanceM-1,yc))return;const r=N.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<o.distanceM))return o}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const s=a=>.2126*a[0]+.7152*a[1]+.0722*a[2],i=Math.hypot(t.x,t.y,t.z)||1,n=Math.max(0,Math.min(1,t.y/i));return s(e.horizon)+(s(e.zenith)-s(e.horizon))*Math.sqrt(n)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const t of this.skyEventLayers.values())t.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())C.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const s=t&&e;if(t===this.animationsRunning&&s===this.framesDriven)return;const i=this.animationsRunning;this.animationsRunning=t,this.framesDriven=s,t&&!i&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),n&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new D;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<N.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new Ge(vc,32,16),s=e.attributes.position,i=e.getAttribute("color")??new qe(new Float32Array(s.count*3),3);for(let a=0;a<s.count;a++){const{altitudeDeg:o,azimuthDeg:r}=$u(s.getX(a),s.getY(a),s.getZ(a)),c=ap(o,r,t.azimuthDeg,t.altitudeDeg);i.setXYZ(a,c[0],c[1],c[2])}if(i.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",i);const n=new $s({vertexColors:!0,side:Ai,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new B(e,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=Z0(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new sg(this.groundRadius,48),s=new ci({color:new q(fl,fl,fl),fog:!0});jn.fadeRim(s,this.groundRadius*.75,this.groundRadius),this.groundMesh=new B(e,s),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const s=this.terrainMesh;let i=0;if(s){const a=s.geometry.getAttribute("position");i=1/0;for(let o=0;o<a.count;o++)Math.abs(a.getX(o)+s.position.x)>600||Math.abs(a.getZ(o)+s.position.z)>600||(i=Math.min(i,a.getY(o)+s.position.y));i=Number.isFinite(i)?Math.min(0,i)-1:0}const n=this.farRing?.mesh;if(n){const a=n.geometry.getAttribute("position");let o=1/0;for(let r=0;r<a.count;r++)Math.hypot(a.getX(r)+n.position.x,a.getZ(r)+n.position.z)>this.groundRadius||(o=Math.min(o,a.getY(r)+n.position.y));Number.isFinite(o)&&(i=Math.min(i,o-1))}this.groundMesh.position.y=i,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const s=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([a,o])=>`${a}=${Math.round(o.x/10)},${Math.round(o.z/10)}`).join(";")+(e?":water":""),i=this.cloudTransmissionMemo.get(s);if(i!==void 0)return i;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(s,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const s=Vt(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(s,e);let i=1;const n=this.lowerCloudCover();n>0&&(i*=1-bt.alphaAt(s,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*gy);const a=e?0:this.weather.highCloudCover??0;return a>0&&(i*=1-bt.iceAlphaAt(s,Ac,a,this.cloudFieldOffset)*My),Math.max(0,Math.min(1,i))}setBodyMesh(t,e,s,i,n){if(e.altitudeDeg<Fc){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1,ps.setDisc("sun",void 0));return}const{x:a,y:o,z:r}=Vt(e.altitudeDeg,e.azimuthDeg,de),c=this.cloudTransmission(e),h=this.arrivingIlluminance(e,n,c),l=N.unitLuminance(i);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(s/de)**2,m=[0,1,2].map(g=>l[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=m;const p=m.map(g=>Math.min(N.BRIGHTEST_RELATIVE,g));d instanceof B||(this.disposeMesh(d),d=new B(new Ge(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(p[0],p[1],p[2]),d.scale.setScalar(s),ps.setDisc("sun",{direction:[a/de,o/de,r/de],radiusRad:Math.atan(s/de),radiance:p})}else{if(!(d instanceof Us)){this.disposeMesh(d);const p=new le;p.setAttribute("position",new Ot(new Float32Array(3),3)),p.setAttribute("color",new Ot(new Float32Array(3),3)),d=new Us(p,Z.material(Ta[Ta.length-1].size,!1)),Z.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),m=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,l[0]*h[0]*m,l[1]*h[1]*m,l[2]*h[2]*m),f.needsUpdate=!0}if(d.position.set(a,o,r),this.setHitArea(t,a,o,r,s),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,a,o,r,h,s/de*(180/Math.PI),N.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(a*f,o*f+this.celestialGroup.position.y,r*f),this.lensFlare||(this.lensFlare=DM(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const s="moon";if(t.magnitude>e||t.altitudeDeg<Fc){this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s),ps.setDisc("moon",void 0);return}const{x:i,y:n,z:a}=Vt(t.altitudeDeg,t.azimuthDeg,de),o=this.cloudTransmission(t),r=this.arrivingIlluminance(t,t.magnitude,o),c=t.radiusDeg??Bi.MEAN_RADIUS_DEG,h=de*Math.tan(c*Mt),l=Math.max(Oi(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/de)**2,d=new q(...r.map(g=>Math.min(N.BRIGHTEST_RELATIVE,g/l))),f=Math.PI*(h/de)**2;ps.setDisc("moon",{direction:[i/de,n/de,a/de],radiusRad:c*Mt,radiance:r.map(g=>Math.min(N.BRIGHTEST_RELATIVE,g/f))});const m=`${t.phase.phaseFraction<.5}:${Math.round(Oi(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(s);p instanceof to?(p.userData.phaseKey!==m&&(p.material.map?.dispose(),p.material.map=xf(t.phase),p.userData.phaseKey=m),p.material.color.copy(d)):(this.disposeMesh(p),p=new to(new kc({map:xf(t.phase),color:d,fog:!1,blending:rs,depthWrite:!1})),p.userData.phaseKey=m,this.celestialGroup.add(p),this.bodyMeshes.set(s,p)),p.scale.set(h*2,h*2,1),p.position.set(i,n,a),this.setHitArea(s,i,n,a,h),this.setGlare(s,i,n,a,r,c)}bentLight(t,e,s=my){const[i,n,a]=this.arrivingIlluminance(t,e,1),o=Math.max(n,1e-30);return{scale:n/s,tint:[i/o,1,a/o]}}static litBySky(t,e){return N.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new q;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Z.CONE_SOLID_ANGLE/e)}pointScratch=new ht;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,s){const i=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),n=At.illuminanceOf(e)*s*this.relativeScale;return[i[0]*n,i[1]*n,i[2]*n]}static unitLuminance(t){const e=Ls.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,s,i,n){let a=this.hitAreas.get(t);if(!a){const r=new kc({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});a=new to(r),this.celestialGroup.add(a),this.hitAreas.set(t,a)}a.position.set(e,s,i);const o=n*2;a.scale.set(o,o,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,s,i,n,a,o=0){if(_e.radiusDeg(_e.K*Math.max(...n))<=Math.max(a,o)){this.disposeGlare(t);return}let r=this.glareSprites.get(t);r||(r=new _e(`veil:${t}`),this.celestialGroup.add(r.mesh),this.glareSprites.set(t,r)),r.shine({x:e,y:s,z:i},n,a,o)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const s=t&&`comet:${t.id}`;if(!t||!s||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==s&&this.disposeComet();const i=va(t.magnitude,e),n=Cc(i);this.cometKey=s,this.setBodyMesh(s,t.position,Ml*(.5+.5*i),new q(n,n,n),t.magnitude),this.cometTail||(this.cometTail=new Fs(de),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,i)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new ge,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const s=this.highCloudCover(),i=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(i?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),s===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:Ac},0);return}const n=this.lowerCloudCover(),a=dt.deckLitUntilDeg(dt.DECK_HEIGHT_M),o=t.altitudeDeg>-a?t:e,r=this.bentLight(o,o===t?st.SUN_MAGNITUDE:e.magnitude),c=dt.strength(s,n,o.altitudeDeg,a)*r.scale,{x:h,y:l,z:d}=Vt(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:l,z:d},o.altitudeDeg,c,r.tint,{cover:i?.cover??s,layerHeight:i?.layerHeight??Ac},i?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Hp,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Ma,this.celestialGroup.add(this.rainbow.object));const s=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,i=t.altitudeDeg>0,n=i?t:e,a=this.lowerCloudCover(),o=this.bentLight(n,i?st.SUN_MAGNITUDE:e.magnitude,py),r=zs.strength(s,a,n.altitudeDeg)*o.scale;if(r<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:l}=Vt(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:l},r,o.tint,i)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Fn,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:s,observer:i}=t.frame,n=pi.galactic(s,i),a=N.directionOf(n.centre),o=N.directionOf(n.rotation),r=N.directionOf(n.pole),c=new Pa().set(a.x,a.y,a.z,o.x,o.y,o.z,r.x,r.y,r.z),h=N.directionOf(pi.eclipticPole(s,i)),l=N.directionOf(t.sun),d=l.clone().addScaledVector(h,-l.dot(h)).normalize();this.skyGlow.update({galactic:c,eclipticPole:h,sunLongitude:d,sunDirection:l,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:N.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:U.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new D(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:s,z:i}=Vt(t.altitudeDeg,t.azimuthDeg,1);return new D(e,s,i).normalize()}buildNovae(t,e){const s=new Set;for(const i of t){if(i.magnitude>e)continue;const n=`nova:${i.id}`;s.add(n);const a=va(i.magnitude,e),o=Cc(a);this.setBodyMesh(n,i.position,Ml*(.5+.5*a),new q(o,o,o),i.magnitude)}for(const i of this.novaKeys)s.has(i)||(this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i));this.novaKeys=s}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const s=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const i of t){if(i.magnitude>e)continue;s.add(i.body);const n=va(i.magnitude,e),a=Cc(n),o=qy[i.body]??new q(1,1,1),r=new q(o.r*a,o.g*a,o.b*a),c=Ml*(.5+.5*n);this.setBodyMesh(i.body,i.position,c,r,i.magnitude)}for(const i of[...this.bodyMeshes.keys()])s.has(i)||(this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:s,date:i,observer:n}=t,a=new Mi(i,n),o=Dl(1337),r=[],c=this.siteElevationM+this.observerElevationM;for(let h=0;h<s.count;h++){const l=s.mag[h];if(l>e)break;const{altitudeDeg:d,azimuthDeg:f}=a.position(s.ra[h],s.dec[h]);if(d<Q0)continue;const{x:m,y:p,z:g}=Vt(d,f,ml);r.push({x:m,y:p,z:g,brightness:va(l,e),illuminance:this.air.transmittanceFromSpace(c,d).map(M=>M*At.illuminanceOf(l)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of Z2){if(h.mag>e)continue;const{altitudeDeg:l,azimuthDeg:d}=a.position(h.raHours,h.decDeg);if(l<Q0)continue;const{x:f,y:m,z:p}=Vt(l,d,ml);this.namedStars.push({star:h,direction:new D(f,m,p).normalize(),altitudeDeg:l})}this.starTiers=Ta.map((h,l)=>{const d=r.filter(b=>Dh(b.brightness)===l),f=new Float32Array(d.length*3),m=new Float32Array(d.length),p=new Float32Array(d.length*3),g=new Float32Array(d.length),M=new Float32Array(d.length);d.forEach((b,E)=>{f[E*3]=b.x,f[E*3+1]=b.y,f[E*3+2]=b.z,m[E]=b.brightness,p.set(b.illuminance,E*3),g[E]=b.phase,M[E]=b.speedFactor});const v=new le;v.setAttribute("position",new Ot(f,3)),v.setAttribute("seed",new Ot(g.map(b=>b/(2*Math.PI)),1));const y=new Ot(new Float32Array(d.length*3),3);v.setAttribute("color",y);let w=this.starTiers[l]?.points;return w?(w.geometry.dispose(),w.geometry=v):(w=new Us(v,Z.material(h.size)),Z.track(w),this.celestialGroup.add(w)),{points:w,colorAttribute:y,brightness:m,illuminance:p,phase:g,speedFactor:M}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Z.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const s of this.starTiers){const i=s.colorAttribute.array;for(let n=0;n<s.brightness.length;n++)i[n*3]=s.illuminance[n*3]*e,i[n*3+1]=s.illuminance[n*3+1]*e,i[n*3+2]=s.illuminance[n*3+2]*e;s.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new _o(this.celestialGroup,vl,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.skyEventCloudLights.size>0&&this.layeredClouds.setLights([...this.skyEventCloudLights.values()].flat(),this.camera.position),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,s=new q(aa[0]+(bl[0]-aa[0])*e,aa[1]+(bl[1]-aa[1])*e,aa[2]+(bl[2]-aa[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(s),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:i,uniforms:n}=cu(s,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=i,this.cloudUniforms=n,n.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const a=hu(vl);this.cloudMesh=new B(a,i),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:s}=cu(new q(...aa),t,Ac,1);this.cirrusMaterial=e,this.cirrusUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new B(hu(vl*1.04),e),this.cirrusMesh.renderOrder=hf-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const s=e<0;t.scale.y=s?-1:1,t.renderOrder=s?_o.deckOrder(!0,0,1):hf}cloudLayerOffset(){const e=((this.weather.cloudBaseM??Yf)-this.observerElevationM)*yl;return Math.sign(e||1)*Math.max(Math.abs(e),Py)}updateCloudLighting(t,e){const s=[this.cloudUniforms,this.cirrusUniforms].filter(l=>l!==void 0);if(s.length===0&&!this.layeredClouds)return;const i=this.cloudBeamDirection,[n,a,o]=this.cloudBeam.map(l=>l/Math.PI),r=this.lightningLevel*Tl*this.relativeScale/Math.PI,c=new q(e[0]+xi.r*r,e[1]+xi.g*r,e[2]+xi.b*r);this.layeredClouds?.setLighting(i.clone(),new q(n,a,o),c,c),this.layeredClouds?.setLightFromBelow(this.townsUnderClouds());const h=Math.max(0,i.y);for(const l of s)l.sunDir.value.copy(i),l.sunColor.value.setRGB(n*h,a*h,o*h),l.ambientColor.value.copy(c)}static TOWNS_UNDER_OVERCAST=10;static TOWNS_KELVINS=3e3;townsUnderClouds(){const t=U.artificialZenithNanolamberts(this.lightPollution)*st.CANDELAS_PER_NANOLAMBERT;if(t<=0)return[0,0,0];const e=t*N.TOWNS_UNDER_OVERCAST*this.relativeScale,s=Ia.ofTemperature(N.TOWNS_KELVINS);return[s[0]*e,s[1]*e,s[2]*e]}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return Hy(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,Sl],[this.rainSplashSystem?.points,oa],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:El[this.weather.precipitationType].poolSize]];for(const[e,s]of t)e&&s!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(s));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=ff(xl(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=El[t],s=e.poolSize,i=Dl(9001),n=new Float32Array(s*3),a=new Float32Array(s),o=new Float32Array(s),r=new Float32Array(s),c=new Float32Array(s),h=new Float32Array(s),l=new Float32Array(s),d=new Float32Array(s),f=new Float32Array(s),m=new Float32Array(s);for(let y=0;y<s;y++){const w=i()*Math.PI*2,b=i()*e.radiusM;n[y*3]=Math.cos(w)*b,n[y*3+1]=ao+i()*(e.topYM-ao),n[y*3+2]=Math.sin(w)*b,a[y]=i()*Math.PI*2,o[y]=.7+i()*.6,r[y]=.6+i()*.8,c[y]=.4+i()*1.2}const p=new le;p.setAttribute("position",new Ot(n,3)),p.setDrawRange(0,this.precipitationCount(s));const g={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new q(...this.baseFogColor)},uTexture:{value:jy(t)},uNearFocusDistance:{value:Mf},uHazeDistance:{value:e.radiusM*vf}},M=new Lt({uniforms:g,vertexShader:sw,fragmentShader:iw,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const v=new Us(p,M);v.renderOrder=wl,this.scene.add(v),this.precipitationPoints=v,this.precipitationPositions=n,this.precipitationPhase=a,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=r,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=l,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=m}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const s=this.weather.precipitationType;if(s==="none"||s==="rain")return;const i=El[s];if(this.precipitationUniforms?.uColor.value.copy(N.litBySky(i.color,this.baseFogColor)),e<=0)return;const n=this.weather.windDirectionDeg*Mt,a=Math.sin(n)*this.weather.windSpeed*i.driftSensitivity,o=-Math.cos(n)*this.weather.windSpeed*i.driftSensitivity,r=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,l=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,m=this.precipitationBounceHeight,p=this.precipitationBounceDuration,g=this.precipitationBounceVelX,M=this.precipitationBounceVelZ,v=s==="snow"&&l&&d,y=s==="hail"&&f&&m&&p&&g&&M;for(let w=0,b=0;w<r.length;w+=3,b++){if(y&&f[b]>0){if(f[b]-=e,f[b]<=0){const S=Math.random()*Math.PI*2,x=Math.sqrt(Math.random())*i.radiusM;r[w]=Math.cos(S)*x,r[w+1]=i.topYM,r[w+2]=Math.sin(S)*x,f[b]=0}else{const S=1-f[b]/p[b];r[w+1]=ao+Math.sin(Math.PI*S)*m[b],r[w]=xc(r[w]+(a+g[b])*e,i.radiusM),r[w+2]=xc(r[w+2]+(o+M[b])*e,i.radiusM)}continue}let E=0,A=0;if(v){const S=Gy*l[b],x=By*d[b];E=Math.sin(t*S*Math.PI*2+c[b])*x,A=Math.sin(t*S*Math.PI*2+c[b]+Math.PI/2)*x}if(r[w]+=(a+E)*e,r[w+1]-=i.fallSpeedMPerS*h[b]*e,r[w+2]+=(o+A)*e,r[w]=xc(r[w],i.radiusM),r[w+2]=xc(r[w+2],i.radiusM),r[w+1]<ao){if(y){m[b]=Af*(.2+Math.random()*1.6),p[b]=Vy*(.5+Math.random()),f[b]=p[b];const T=Math.random()*Math.PI*2,I=Wy*(m[b]/Af);g[b]=Math.cos(T)*I,M[b]=Math.sin(T)*I,r[w+1]=ao;continue}const S=Math.random()*Math.PI*2,x=Math.sqrt(Math.random())*i.radiusM;r[w]=Math.cos(S)*x,r[w+1]=i.topYM,r[w+2]=Math.sin(S)*x}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=xl(this.weather.precipitationIntensity);this.rainSystem=SM({count:Sl,radiusM:hr,heightM:Ly,bottomYM:lf,overallSpeed:Ny,color:df.clone(),opacity:.85,visibleCount:this.precipitationCount(Sl),speedStreak:ff(t),pixelSize:wf,seed:9001,nearFocusDistanceM:Mf,hazeDistanceM:hr*vf,hazeColor:new q(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=wl,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=Dl(4242),e=new Float32Array(oa*3),s=new Float32Array(oa),i=new Float32Array(oa),n=new Float32Array(oa);for(let h=0;h<oa;h++){const l=t()*Math.PI*2,d=Math.sqrt(t())*hr;e[h*3]=Math.cos(l)*d,e[h*3+1]=lf,e[h*3+2]=Math.sin(l)*d,i[h]=Sf(mf,pf),s[h]=t()*i[h],n[h]=s[h]/i[h]}const a=new le;a.setAttribute("position",new Ot(e,3));const o=new Ot(n,1);a.setAttribute("aLife",o),a.setDrawRange(0,this.precipitationCount(oa));const r=new Lt({uniforms:{uMaxSize:{value:Fy},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:gf.clone()},uTexture:{value:Qy()}},vertexShader:tw,fragmentShader:ew,transparent:!0,depthWrite:!1}),c=new Us(a,r);c.renderOrder=wl,this.scene.add(c),this.rainSplashSystem={points:c,positions:e,life:s,duration:i,lifeAttribute:o}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*Mt;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-xl(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const s=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=s.x/Math.max(s.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(N.litBySky(df,this.baseFogColor));const s=this.rainSplashSystem?.points.material?.uniforms?.uColor;s&&s.value.copy(N.litBySky(gf,this.baseFogColor));const i=this.weather.windDirectionDeg*Mt,n=Math.sin(i)*this.weather.windSpeed,a=-Math.cos(i)*this.weather.windSpeed,o=hr,r=h=>(h%(o*2)+o*3)%(o*2)-o;e.uniforms.uWindOffset.value.set(r(e.uniforms.uWindOffset.value.x+n*t),r(e.uniforms.uWindOffset.value.y+a*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const c=Math.abs(this.rainCameraDirection.y);if(Math.abs(c-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=c;const h=bf+(1-bf)*(1-c),l=Ef+(1-Ef)*(1-c);e.uniforms.uUvSquash.value=l,e.uniforms.uPixelSize.value=wf*h*(.5+.5*l)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:s,life:i,duration:n,lifeAttribute:a}=e,o=a.array;for(let r=0,c=0;r<s.length;r+=3,c++){if(i[c]+=t,i[c]>=n[c]){const h=Math.random()*Math.PI*2,l=Math.sqrt(Math.random())*hr;s[r]=Math.cos(h)*l,s[r+2]=Math.sin(h)*l,n[c]=Sf(mf,pf),i[c]=0}o[c]=i[c]/n[c]}e.points.geometry.attributes.position.needsUpdate=!0,a.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,s=0;if(this.lightningArmed)for(const r of this.lightningFlashes){if(r.t>t)break;const c=De.brightnessAt(r,t);c>s&&(e=r,s=c)}const i=e?Math.min(1,Math.max(.1,($y/e.distanceM)**2)):0,n=s*i*(e?.cloudToGround?1:.6);if(n===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const r=this.scene.fog,c=n*Tl*this.relativeScale/Math.PI;r.color.setRGB(this.airlight[0]+xi.r*c,this.airlight[1]+xi.g*c,this.airlight[2]+xi.b*c)}const a=this.skyMesh?.material?.color;if(a){const r=n*Xy;a.setRGB(1+r*xi.r,1+r*xi.g,1+r*xi.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*Tl*this.relativeScale,e){const{x:r,y:c,z:h}=Vt(25,e.azimuthDeg,de);this.lightningLight.position.set(r,c,h)}this.lightningBolt||(this.lightningBolt=new Hn(de*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,s,o),this.render()}buildCompassLabels(){this.compassSprites=Ty.map(t=>{const e=Da.point(t,this.compassPoints),s=new kc({map:nw(e),depthTest:!1,fog:!1}),i=new to(s),{x:n,y:a,z:o}=Vt(0,t,nf);return i.position.set(n,a,o),i.scale.set(Sc,Sc,1),i.renderOrder=Ry,i.layers.set(dl),i.visible=this.compassForced,this.celestialGroup.add(i),i}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=af*Math.PI/360,s=Sc*Math.tan(t)/Math.tan(e);for(const i of this.compassSprites)i.scale.set(s,s,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const s of Array.isArray(e)?e:[e]){const i=s.map;i&&i.dispose(),s.dispose()}}}const Mt=Math.PI/180;function Oi(u,t,e){return Math.max(t,Math.min(e,u))}function Sf(u,t){return u+Math.random()*(t-u)}function xc(u,t){return(u%(t*2)+t*3)%(t*2)-t}let Tc,Dc;function jy(u){switch(u){case"snow":return Zy();case"hail":return Jy()}}function Zy(){if(Tc)return Tc;const u=64,t=document.createElement("canvas");t.width=u,t.height=u;const e=t.getContext("2d"),s=e.createRadialGradient(u/2,u/2,0,u/2,u/2,u/2);return s.addColorStop(0,"rgba(255,255,255,0.95)"),s.addColorStop(.5,"rgba(255,255,255,0.55)"),s.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=s,e.fillRect(0,0,u,u),Tc=new Qn(t),Tc}function Jy(){if(Dc)return Dc;const u=64,t=document.createElement("canvas");t.width=u,t.height=u;const e=t.getContext("2d"),s=e.createRadialGradient(u/2,u/2,0,u/2,u/2,u/2);return s.addColorStop(0,"rgba(255,255,255,1)"),s.addColorStop(.55,"rgba(255,255,255,0.95)"),s.addColorStop(.8,"rgba(255,255,255,0.4)"),s.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=s,e.fillRect(0,0,u,u),Dc=new Qn(t),Dc}let Ic;function Qy(){if(Ic)return Ic;const u=64,t=document.createElement("canvas");t.width=u,t.height=u;const e=t.getContext("2d"),s=e.createRadialGradient(u/2,u/2,0,u/2,u/2,u/2);return s.addColorStop(0,"rgba(255,255,255,0)"),s.addColorStop(.4,"rgba(255,255,255,0)"),s.addColorStop(.6,"rgba(255,255,255,0.9)"),s.addColorStop(.8,"rgba(255,255,255,0.25)"),s.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=s,e.fillRect(0,0,u,u),Ic=new Qn(t),Ic}const tw=`
|
|
4933
|
+
`,transparent:!0,blending:rs,depthWrite:!1,side:Ai,fog:!1});this.object=new B(new Ge(qu.RADIUS,128,32,0,Math.PI*2,0,At.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let s=0;s<At.STEPS;s++){for(let i=0;i<3;i++)this.texels[s*4+i]=Xe.toHalfFloat(Math.min(e[s*3+i],6e4));this.texels[s*4+3]=Xe.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class ch{constructor(t){this.generator=t}static SIZE=128;target=new Cl(ch.SIZE,{type:oe,generateMipmaps:!0,minFilter:Go,magFilter:Xt});camera=new Zf(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,s,i=[]){const n=t.shadowMap.autoUpdate;let a=!1;e.traverse(r=>{const c=r;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(a=!0)}),t.shadowMap.autoUpdate=a?n:!1;const o=i.map(r=>r.visible);for(const r of i)r.visible=!1;this.camera.position.copy(s),this.camera.update(t,e),i.forEach((r,c)=>{r.visible=o[c]}),t.shadowMap.autoUpdate=n,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class ds{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){ds.install(),this.generator=new Zp(t),this.eye=new ch(this.generator)}static decor;refresh(t,e,s,i,n,a,o,r=[],c,h=ds.REFRESH_MS){for(const g of[...this.probes.keys()])i.some(M=>M.id===g&&M.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const l=[{probe:this.eye}];for(const g of i){if(!g.shiny)continue;let M=this.probes.get(g.id);M||(M=new ch(this.generator),this.probes.set(g.id,M)),l.push({probe:M,reflector:g})}const d=performance.now(),f=()=>l.filter(({probe:g})=>g.capturedVersion!==o),m=f().filter(({probe:g})=>d-g.capturedAtMs>=h);if(m.length>0){const g=m.reduce((M,v)=>v.probe.capturedAtMs<M.probe.capturedAtMs?v:M);if(g.reflector){const M=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,M,[g.reflector.holder,...n]),ds.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,s,[...n,...r]),c?.(g.probe.sharp),ds.decor=g.probe.filtered;for(const M of a)ds.reflectOn(M,g.probe);for(const M of i)M.shiny||ds.reflectOn(M.holder,g.probe)}g.probe.capturedVersion=o}const p=f();if(p.length!==0)return Math.max(16,Math.min(...p.map(({probe:g})=>h-(d-g.capturedAtMs))))}scratch=new D;static reflectOn(t,e={filtered:ds.decor}){t.traverse(s=>{const i=s.material;for(const n of Array.isArray(i)?i:i?[i]:[])n instanceof ps?e.sharp&&n.setSurroundings(e.sharp):n instanceof un&&e.filtered&&n.envMap!==e.filtered&&(n.envMap=e.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(ds.installed)return;ds.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!yi.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}yi.lights_fragment_maps=yi.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const yp=0,cv=1,hv=2,k0=2,tl=1.25,L0=1,gs=32,Fe=gs/4,wp=65535,_c=Math.pow(2,-24),ju=Symbol("SKIP_GENERATION"),bp={strategy:yp,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[ju]:!1};function ve(u,t,e){return e.min.x=t[u],e.min.y=t[u+1],e.min.z=t[u+2],e.max.x=t[u+3],e.max.y=t[u+4],e.max.z=t[u+5],e}function wu(u){let t=-1,e=-1/0;for(let s=0;s<3;s++){const i=u[s+3]-u[s];i>e&&(e=i,t=s)}return t}function N0(u,t){t.set(u)}function C0(u,t,e){let s,i;for(let n=0;n<3;n++){const a=n+3;s=u[n],i=t[n],e[n]=s<i?s:i,s=u[a],i=t[a],e[a]=s>i?s:i}}function ic(u,t,e){for(let s=0;s<3;s++){const i=t[u+2*s],n=t[u+2*s+1],a=i-n,o=i+n;a<e[s]&&(e[s]=a),o>e[s+3]&&(e[s+3]=o)}}function er(u){const t=u[3]-u[0],e=u[4]-u[1],s=u[5]-u[2];return 2*(t*e+e*s+s*t)}function Ae(u,t){return t[u+15]===wp}function Ze(u,t){return t[u+6]}function Ms(u,t){return t[u+14]}function He(u){return u+Fe}function Ue(u,t){const e=t[u+6];return u+e*Fe}function Zu(u,t){return t[u+7]}function el(u,t,e,s,i){let n=1/0,a=1/0,o=1/0,r=-1/0,c=-1/0,h=-1/0,l=1/0,d=1/0,f=1/0,m=-1/0,p=-1/0,g=-1/0;const M=u.offset||0;for(let v=(t-M)*6,y=(t+e-M)*6;v<y;v+=6){const w=u[v+0],b=u[v+1],E=w-b,A=w+b;E<n&&(n=E),A>r&&(r=A),w<l&&(l=w),w>m&&(m=w);const S=u[v+2],x=u[v+3],T=S-x,I=S+x;T<a&&(a=T),I>c&&(c=I),S<d&&(d=S),S>p&&(p=S);const R=u[v+4],O=u[v+5],P=R-O,k=R+O;P<o&&(o=P),k>h&&(h=k),R<f&&(f=R),R>g&&(g=R)}s[0]=n,s[1]=a,s[2]=o,s[3]=r,s[4]=c,s[5]=h,i[0]=l,i[1]=d,i[2]=f,i[3]=m,i[4]=p,i[5]=g}const hn=32,lv=(u,t)=>u.candidate-t.candidate,Pn=new Array(hn).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),nc=new Float32Array(6);function uv(u,t,e,s,i,n){let a=-1,o=0;if(n===yp)a=wu(t),a!==-1&&(o=(t[a]+t[a+3])/2);else if(n===cv)a=wu(u),a!==-1&&(o=dv(e,s,i,a));else if(n===hv){const r=er(u);let c=tl*i;const h=e.offset||0,l=(s-h)*6,d=(s+i-h)*6;for(let f=0;f<3;f++){const m=t[f],M=(t[f+3]-m)/hn;if(i<hn/4){const v=[...Pn];v.length=i;let y=0;for(let b=l;b<d;b+=6,y++){const E=v[y];E.candidate=e[b+2*f],E.count=0;const{bounds:A,leftCacheBounds:S,rightCacheBounds:x}=E;for(let T=0;T<3;T++)x[T]=1/0,x[T+3]=-1/0,S[T]=1/0,S[T+3]=-1/0,A[T]=1/0,A[T+3]=-1/0;ic(b,e,A)}v.sort(lv);let w=i;for(let b=0;b<w;b++){const E=v[b];for(;b+1<w&&v[b+1].candidate===E.candidate;)v.splice(b+1,1),w--}for(let b=l;b<d;b+=6){const E=e[b+2*f];for(let A=0;A<w;A++){const S=v[A];E>=S.candidate?ic(b,e,S.rightCacheBounds):(ic(b,e,S.leftCacheBounds),S.count++)}}for(let b=0;b<w;b++){const E=v[b],A=E.count,S=i-E.count,x=E.leftCacheBounds,T=E.rightCacheBounds;let I=0;A!==0&&(I=er(x)/r);let R=0;S!==0&&(R=er(T)/r);const O=L0+tl*(I*A+R*S);O<c&&(a=f,c=O,o=E.candidate)}}else{for(let w=0;w<hn;w++){const b=Pn[w];b.count=0,b.candidate=m+M+w*M;const E=b.bounds;for(let A=0;A<3;A++)E[A]=1/0,E[A+3]=-1/0}for(let w=l;w<d;w+=6){let A=~~((e[w+2*f]-m)/M);A>=hn&&(A=hn-1);const S=Pn[A];S.count++,ic(w,e,S.bounds)}const v=Pn[hn-1];N0(v.bounds,v.rightCacheBounds);for(let w=hn-2;w>=0;w--){const b=Pn[w],E=Pn[w+1];C0(b.bounds,E.rightCacheBounds,b.rightCacheBounds)}let y=0;for(let w=0;w<hn-1;w++){const b=Pn[w],E=b.count,A=b.bounds,x=Pn[w+1].rightCacheBounds;E!==0&&(y===0?N0(A,nc):C0(A,nc,nc)),y+=E;let T=0,I=0;y!==0&&(T=er(nc)/r);const R=i-y;R!==0&&(I=er(x)/r);const O=L0+tl*(T*y+I*R);O<c&&(a=f,c=O,o=b.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:a,pos:o}}function dv(u,t,e,s){let i=0;const n=u.offset;for(let a=t,o=t+e;a<o;a++)i+=u[(a-n)*6+s*2];return i/e}class sl{constructor(){this.boundingData=new Float32Array(6)}}function fv(u,t,e,s,i,n){let a=s,o=s+i-1;const r=n.pos,c=n.axis*2,h=e.offset||0;for(;;){for(;a<=o&&e[(a-h)*6+c]<r;)a++;for(;a<=o&&e[(o-h)*6+c]>=r;)o--;if(a<o){for(let l=0;l<t;l++){let d=u[a*t+l];u[a*t+l]=u[o*t+l],u[o*t+l]=d}for(let l=0;l<6;l++){const d=a-h,f=o-h,m=e[d*6+l];e[d*6+l]=e[f*6+l],e[f*6+l]=m}a++,o--}else return a}}let Ep,zc,bu,Ap;const mv=Math.pow(2,32);function Eu(u){return"count"in u?1:1+Eu(u.left)+Eu(u.right)}function pv(u,t,e){return Ep=new Float32Array(e),zc=new Uint32Array(e),bu=new Uint16Array(e),Ap=new Uint8Array(e),Au(u,t)}function Au(u,t){const e=u/4,s=u/2,i="count"in t,n=t.boundingData;for(let a=0;a<6;a++)Ep[e+a]=n[a];if(i)return t.buffer?(Ap.set(new Uint8Array(t.buffer),u),u+t.buffer.byteLength):(zc[e+6]=t.offset,bu[s+14]=t.count,bu[s+15]=wp,u+gs);{const{left:a,right:o,splitAxis:r}=t,c=u+gs;let h=Au(c,a);const l=u/gs,f=h/gs-l;if(f>mv)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return zc[e+6]=f,zc[e+7]=r,Au(h,o)}}function gv(u,t,e,s,i,n){const{maxDepth:a,verbose:o,targetLeafSize:r,_strictLeafSize:c=1/0,strategy:h,onProgress:l}=i,d=u.primitiveBuffer,f=u.primitiveBufferStride,m=new Float32Array(6);let p=!1;const g=new sl;return el(t,e,s,g.boundingData,m),v(g,e,s,m),g;function M(y){l&&l((y-n.offset)/n.count)}function v(y,w,b,E=null,A=0){!p&&A>=a&&(p=!0,o&&console.warn(`BVH: Max depth of ${a} reached when generating BVH. Consider increasing maxDepth.`));const S=b>c;if(b<=r&&!S||A>=a)return M(w+b),y.offset=w,y.count=b,y;const x=uv(y.boundingData,E,t,w,b,h);let T=x.axis===-1?-1:fv(d,f,t,w,b,x);if(x.axis===-1||T===w||T===w+b){if(!S)return M(w+b),y.offset=w,y.count=b,y;x.axis=Math.max(0,wu(y.boundingData)),T=w+Math.max(1,Math.floor(b/2))}y.splitAxis=x.axis;const I=new sl,R=w,O=T-w;y.left=I,el(t,R,O,I.boundingData,m),v(I,R,O,m,A+1);const P=new sl,k=T,_=b-O;return y.right=P,el(t,k,_,P.boundingData,m),v(P,k,_,m,A+1),y}}function Mv(u,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=u.getRootRanges(t.range),i=s[0],n=s[s.length-1],a={offset:i.offset,count:n.offset+n.count-i.offset},o=new Float32Array(6*a.count);o.offset=a.offset,u.computePrimitiveBounds(a.offset,a.count,o),u._roots=s.map(r=>{const c=gv(u,o,r.offset,r.count,t,a),h=Eu(c),l=new e(gs*h);return pv(0,c,l),l})}class Ju{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class vv{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=s=>{e&&t.push(e),e=s,this.float32Array=new Float32Array(s),this.uint16Array=new Uint16Array(s),this.uint32Array=new Uint32Array(s)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const re=new vv;let Xn,xo;const Ba=[],ac=new Ju(()=>new ee);function yv(u,t,e,s,i,n){Xn=ac.getPrimitive(),xo=ac.getPrimitive(),Ba.push(Xn,xo),re.setBuffer(u._roots[t]);const a=Su(0,u.geometry,e,s,i,n);re.clearBuffer(),ac.releasePrimitive(Xn),ac.releasePrimitive(xo),Ba.pop(),Ba.pop();const o=Ba.length;return o>0&&(xo=Ba[o-1],Xn=Ba[o-2]),a}function Su(u,t,e,s,i=null,n=0,a=0){const{float32Array:o,uint16Array:r,uint32Array:c}=re;let h=u*2;if(Ae(h,r)){const d=Ze(u,c),f=Ms(h,r);return ve(u,o,Xn),s(d,f,!1,a,n+u/Fe,Xn)}else{let T=function(R){const{uint16Array:O,uint32Array:P}=re;let k=R*2;for(;!Ae(k,O);)R=He(R),k=R*2;return Ze(R,P)},I=function(R){const{uint16Array:O,uint32Array:P}=re;let k=R*2;for(;!Ae(k,O);)R=Ue(R,P),k=R*2;return Ze(R,P)+Ms(k,O)};const d=He(u),f=Ue(u,c);let m=d,p=f,g,M,v,y;if(i&&(v=Xn,y=xo,ve(m,o,v),ve(p,o,y),g=i(v),M=i(y),M<g)){m=f,p=d;const R=g;g=M,M=R,v=y}v||(v=Xn,ve(m,o,v));const w=Ae(m*2,r),b=e(v,w,g,a+1,n+m/Fe);let E;if(b===k0){const R=T(m),P=I(m)-R;E=s(R,P,!0,a+1,n+m/Fe,v)}else E=b&&Su(m,t,e,s,i,n,a+1);if(E)return!0;y=xo,ve(p,o,y);const A=Ae(p*2,r),S=e(y,A,M,a+1,n+p/Fe);let x;if(S===k0){const R=T(p),P=I(p)-R;x=s(R,P,!0,a+1,n+p/Fe,y)}else x=S&&Su(p,t,e,s,i,n,a+1);return!!x}}const Or=new re.constructor,hh=new re.constructor,Un=new Ju(()=>new ee),Va=new ee,Wa=new ee,il=new ee,nl=new ee;let al=!1;function wv(u,t,e,s){if(al)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");al=!0;const i=u._roots,n=t._roots;let a,o=0,r=0;const c=new Oe().copy(e).invert();for(let h=0,l=i.length;h<l;h++){Or.setBuffer(i[h]),r=0;const d=Un.getPrimitive();ve(0,Or.float32Array,d),d.applyMatrix4(c);for(let f=0,m=n.length;f<m&&(hh.setBuffer(n[f]),a=ui(0,0,e,c,s,o,r,0,0,d),hh.clearBuffer(),r+=n[f].byteLength/gs,!a);f++);if(Un.releasePrimitive(d),Or.clearBuffer(),o+=i[h].byteLength/gs,a)break}return al=!1,a}function ui(u,t,e,s,i,n=0,a=0,o=0,r=0,c=null,h=!1){let l,d;h?(l=hh,d=Or):(l=Or,d=hh);const f=l.float32Array,m=l.uint32Array,p=l.uint16Array,g=d.float32Array,M=d.uint32Array,v=d.uint16Array,y=u*2,w=t*2,b=Ae(y,p),E=Ae(w,v);let A=!1;if(E&&b)h?A=i(Ze(t,M),Ms(t*2,v),Ze(u,m),Ms(u*2,p),r,a+t/Fe,o,n+u/Fe):A=i(Ze(u,m),Ms(u*2,p),Ze(t,M),Ms(t*2,v),o,n+u/Fe,r,a+t/Fe);else if(E){const S=Un.getPrimitive();ve(t,g,S),S.applyMatrix4(e);const x=He(u),T=Ue(u,m);ve(x,f,Va),ve(T,f,Wa);const I=S.intersectsBox(Va),R=S.intersectsBox(Wa);A=I&&ui(t,x,s,e,i,a,n,r,o+1,S,!h)||R&&ui(t,T,s,e,i,a,n,r,o+1,S,!h),Un.releasePrimitive(S)}else{const S=He(t),x=Ue(t,M);ve(S,g,il),ve(x,g,nl);const T=c.intersectsBox(il),I=c.intersectsBox(nl);if(T&&I)A=ui(u,S,e,s,i,n,a,o,r+1,c,h)||ui(u,x,e,s,i,n,a,o,r+1,c,h);else if(T)if(b)A=ui(u,S,e,s,i,n,a,o,r+1,c,h);else{const R=Un.getPrimitive();R.copy(il).applyMatrix4(e);const O=He(u),P=Ue(u,m);ve(O,f,Va),ve(P,f,Wa);const k=R.intersectsBox(Va),_=R.intersectsBox(Wa);A=k&&ui(S,O,s,e,i,a,n,r,o+1,R,!h)||_&&ui(S,P,s,e,i,a,n,r,o+1,R,!h),Un.releasePrimitive(R)}else if(I)if(b)A=ui(u,x,e,s,i,n,a,o,r+1,c,h);else{const R=Un.getPrimitive();R.copy(nl).applyMatrix4(e);const O=He(u),P=Ue(u,m);ve(O,f,Va),ve(P,f,Wa);const k=R.intersectsBox(Va),_=R.intersectsBox(Wa);A=k&&ui(x,O,s,e,i,a,n,r,o+1,R,!h)||_&&ui(x,P,s,e,i,a,n,r,o+1,R,!h),Un.releasePrimitive(R)}}return A}const ol=new class{constructor(){let u=null,t=null,e=null,s=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,a)=>{if(s)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=a,this.buffer=u=n._roots[a],this.uint16Array=e=new Uint16Array(u),this.uint32Array=t=new Uint32Array(u)},this.reset=()=>{this.root=null,this.buffer=u=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=n=>{let a=n*2;for(;!Ae(a,e);)n=He(n),a=n*2;return Ze(n,t)},this.getRangeEnd=n=>{let a=n*2;for(;!Ae(a,e);)n=Ue(n,t),a=n*2;return Ze(n,t)+Ms(a,e)};const i=(n,a,o)=>{const r=a*2,c=Ae(r,e);if(!n(o,c,a)&&!c){const l=He(a),d=Ue(a,t);i(n,l,o+1),i(n,d,o+1)}};this.traverseBuffer=n=>{if(s)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");s=!0;try{i(n,0,0)}finally{s=!1}},this.traverse=n=>{this.traverseBuffer((a,o,r)=>{if(o){const c=r*2,h=t[r+6],l=e[c+14];return n(a,o,new Float32Array(u,r*4,6),h,l)}else{const c=Zu(r,t);return n(a,o,new Float32Array(u,r*4,6),c)}})}}},_0=new ee,Ka=new Float32Array(6);class bv{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...bp,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),Mv(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,s,i){let n=1/0,a=1/0,o=1/0,r=-1/0,c=-1/0,h=-1/0;for(let l=t,d=t+e;l<d;l++){this.writePrimitiveBounds(l,Ka,0);const[f,m,p,g,M,v]=Ka;f<n&&(n=f),g>r&&(r=g),m<a&&(a=m),M>c&&(c=M),p<o&&(o=p),v>h&&(h=v)}return s[i+0]=n,s[i+1]=a,s[i+2]=o,s[i+3]=r,s[i+4]=c,s[i+5]=h,s}computePrimitiveBounds(t,e,s){const i=s.offset||0;for(let n=t,a=t+e;n<a;n++){this.writePrimitiveBounds(n,Ka,0);const[o,r,c,h,l,d]=Ka,f=(o+h)/2,m=(r+l)/2,p=(c+d)/2,g=(h-o)/2,M=(l-r)/2,v=(d-c)/2,y=(n-i)*6;s[y+0]=f,s[y+1]=g+(Math.abs(f)+g)*_c,s[y+2]=m,s[y+3]=M+(Math.abs(m)+M)*_c,s[y+4]=p,s[y+5]=v+(Math.abs(p)+v)*_c}return s}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let s=0,i=e.length;s<i;s++)e[s]+=t;else{const s=this._roots;for(let i=0;i<s.length;i++){const n=s[i],a=new Uint32Array(n),o=new Uint16Array(n),r=n.byteLength/gs;for(let c=0;c<r;c++){const h=Fe*c,l=2*h;Ae(l,o)&&(a[h+6]+=t)}}}}traverse(t,e=0){ol.setBVH(this,e),ol.traverse(t),ol.reset()}refit(){const t=this._roots;for(let e=0,s=t.length;e<s;e++){const i=t[e],n=new Uint32Array(i),a=new Uint16Array(i),o=new Float32Array(i),r=i.byteLength/gs;for(let c=r-1;c>=0;c--){const h=c*Fe,l=h*2;if(Ae(l,a)){const f=Ze(h,n),m=Ms(l,a);this.writePrimitiveRangeBounds(f,m,Ka,0),o.set(Ka,h)}else{const f=He(h),m=Ue(h,n);for(let p=0;p<3;p++){const g=o[f+p],M=o[f+p+3],v=o[m+p],y=o[m+p+3];o[h+p]=g<v?g:v,o[h+p+3]=M>y?M:y}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(s=>{ve(0,new Float32Array(s),_0),t.union(_0)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:s,intersectsRange:i,intersectsPrimitive:n,scratchPrimitive:a,iterate:o}=t;if(i&&n){const l=i;i=(d,f,m,p,g)=>l(d,f,m,p,g)?!0:o(d,f,this,n,m,p,a)}else i||(n?i=(l,d,f,m)=>o(l,d,this,n,f,m,a):i=(l,d,f)=>f);let r=!1,c=0;const h=this._roots;for(let l=0,d=h.length;l<d;l++){const f=h[l];if(r=yv(this,l,s,i,e,c),r)break;c+=f.byteLength/gs}return r}bvhcast(t,e,s){let{intersectsRanges:i}=s;return wv(this,t,e,i)}}function Ev(){return typeof SharedArrayBuffer<"u"}function Qu(u){return u.index?u.index.count:u.attributes.position.count}function Rh(u){return Qu(u)/3}function Av(u,t=ArrayBuffer){return u>65535?new Uint32Array(new t(4*u)):new Uint16Array(new t(2*u))}function Sv(u,t){if(!u.index){const e=u.attributes.position.count,s=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=Av(e,s);u.setIndex(new Ot(i,1));for(let n=0;n<e;n++)i[n]=n}}function xv(u,t,e){const s=Qu(u)/e,i=t||u.drawRange,n=i.start/e,a=(i.start+i.count)/e,o=Math.max(0,n),r=Math.min(s,a)-o;return{offset:Math.floor(o),count:Math.floor(r)}}function Tv(u,t){return u.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function z0(u,t,e){const s=xv(u,t,e),i=Tv(u,e);if(!i.length)return[s];const n=[],a=s.offset,o=s.offset+s.count,r=Qu(u)/e,c=[];for(const d of i){const{offset:f,count:m}=d,p=f,g=isFinite(m)?m:r-f,M=f+g;p<o&&M>a&&(c.push({pos:Math.max(a,p),isStart:!0}),c.push({pos:Math.min(o,M),isStart:!1}))}c.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,l=null;for(const d of c){const f=d.pos;h!==0&&f!==l&&n.push({offset:l,count:f-l}),h+=d.isStart?1:-1,l=f}return n}function Dv(u,t){const e=u[u.length-1],s=e.offset+e.count>2**16,i=u.reduce((c,h)=>c+h.count,0),n=s?4:2,a=t?new SharedArrayBuffer(i*n):new ArrayBuffer(i*n),o=s?new Uint32Array(a):new Uint16Array(a);let r=0;for(let c=0;c<u.length;c++){const{offset:h,count:l}=u[c];for(let d=0;d<l;d++)o[r+d]=h+d;r+=l}return o}class Iv extends bv{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Ev())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?s=>this._indirectBuffer[s]:s=>s,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...bp,...e},e[ju]||this.init(e)}init(t){const{geometry:e,primitiveStride:s}=this;if(t.indirect){const i=z0(e,t.range,s),n=Dv(i,t.useSharedArrayBuffer);this._indirectBuffer=n}else Sv(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new ee))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:z0(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class An{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let s=1/0,i=-1/0;for(let n=0,a=t.length;n<a;n++){const r=t[n][e];s=r<s?r:s,i=r>i?r:i}this.min=s,this.max=i}setFromPoints(t,e){let s=1/0,i=-1/0;for(let n=0,a=e.length;n<a;n++){const o=e[n],r=t.dot(o);s=r<s?r:s,i=r>i?r:i}this.min=s,this.max=i}isSeparated(t){return this.min>t.max||t.min>this.max}}An.prototype.setFromBox=(function(){const u=new D;return function(e,s){const i=s.min,n=s.max;let a=1/0,o=-1/0;for(let r=0;r<=1;r++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){u.x=i.x*r+n.x*(1-r),u.y=i.y*c+n.y*(1-c),u.z=i.z*h+n.z*(1-h);const l=e.dot(u);a=Math.min(l,a),o=Math.max(l,o)}this.min=a,this.max=o}})();const Rv=(function(){const u=new D,t=new D,e=new D;return function(i,n,a){const o=i.start,r=u,c=n.start,h=t;e.subVectors(o,c),u.subVectors(i.end,i.start),t.subVectors(n.end,n.start);const l=e.dot(h),d=h.dot(r),f=h.dot(h),m=e.dot(r),g=r.dot(r)*f-d*d;let M,v;g!==0?M=(l*d-m*f)/g:M=0,v=(l+M*d)/f,a.x=M,a.y=v}})(),td=(function(){const u=new ht,t=new D,e=new D;return function(i,n,a,o){Rv(i,n,u);let r=u.x,c=u.y;if(r>=0&&r<=1&&c>=0&&c<=1){i.at(r,a),n.at(c,o);return}else if(r>=0&&r<=1){c<0?n.at(0,o):n.at(1,o),i.closestPointToPoint(o,!0,a);return}else if(c>=0&&c<=1){r<0?i.at(0,a):i.at(1,a),n.closestPointToPoint(a,!0,o);return}else{let h;r<0?h=i.start:h=i.end;let l;c<0?l=n.start:l=n.end;const d=t,f=e;if(i.closestPointToPoint(l,!0,t),n.closestPointToPoint(h,!0,e),d.distanceToSquared(l)<=f.distanceToSquared(h)){a.copy(d),o.copy(l);return}else{a.copy(h),o.copy(f);return}}}})(),Ov=(function(){const u=new D,t=new D,e=new yh,s=new bn;return function(n,a){const{radius:o,center:r}=n,{a:c,b:h,c:l}=a;if(s.start=c,s.end=h,s.closestPointToPoint(r,!0,u).distanceTo(r)<=o||(s.start=c,s.end=l,s.closestPointToPoint(r,!0,u).distanceTo(r)<=o)||(s.start=h,s.end=l,s.closestPointToPoint(r,!0,u).distanceTo(r)<=o))return!0;const p=a.getPlane(e);if(Math.abs(p.distanceToPoint(r))<=o){const M=p.projectPoint(r,t);if(a.containsPoint(M))return!0}return!1}})(),Pv=["x","y","z"],mn=1e-15,F0=mn*mn;function Zs(u){return Math.abs(u)<mn}class Ei extends eo{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new D),this.satBounds=new Array(4).fill().map(()=>new An),this.points=[this.a,this.b,this.c],this.plane=new yh,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new bn,this.needsUpdate=!0}intersectsSphere(t){return Ov(t,this)}update(){const t=this.a,e=this.b,s=this.c,i=this.points,n=this.satAxes,a=this.satBounds,o=n[0],r=a[0];this.getNormal(o),r.setFromPoints(o,i);const c=n[1],h=a[1];c.subVectors(t,e),h.setFromPoints(c,i);const l=n[2],d=a[2];l.subVectors(e,s),d.setFromPoints(l,i);const f=n[3],m=a[3];f.subVectors(s,t),m.setFromPoints(f,i);const p=c.length(),g=l.length(),M=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,p<mn?g<mn||M<mn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(s)):g<mn?M<mn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):M<mn&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(s),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}Ei.prototype.closestPointToSegment=(function(){const u=new D,t=new D,e=new bn;return function(i,n=null,a=null){const{start:o,end:r}=i,c=this.points;let h,l=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(c[d]),e.end.copy(c[f]),td(e,i,u,t),h=u.distanceToSquared(t),h<l&&(l=h,n&&n.copy(u),a&&a.copy(t))}return this.closestPointToPoint(o,u),h=o.distanceToSquared(u),h<l&&(l=h,n&&n.copy(u),a&&a.copy(o)),this.closestPointToPoint(r,u),h=r.distanceToSquared(u),h<l&&(l=h,n&&n.copy(u),a&&a.copy(r)),Math.sqrt(l)}})();Ei.prototype.intersectsTriangle=(function(){const u=new Ei,t=new An,e=new An,s=new D,i=new D,n=new D,a=new D,o=new bn,r=new bn,c=new D,h=new ht,l=new ht;function d(y,w,b,E){const A=s;!y.isDegenerateIntoPoint&&!y.isDegenerateIntoSegment?A.copy(y.plane.normal):A.copy(w.plane.normal);const S=y.satBounds,x=y.satAxes;for(let R=1;R<4;R++){const O=S[R],P=x[R];if(t.setFromPoints(P,w.points),O.isSeparated(t)||(a.copy(A).cross(P),t.setFromPoints(a,y.points),e.setFromPoints(a,w.points),t.isSeparated(e)))return!1}const T=w.satBounds,I=w.satAxes;for(let R=1;R<4;R++){const O=T[R],P=I[R];if(t.setFromPoints(P,y.points),O.isSeparated(t)||(a.crossVectors(A,P),t.setFromPoints(a,y.points),e.setFromPoints(a,w.points),t.isSeparated(e)))return!1}return b&&(E||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),b.start.set(0,0,0),b.end.set(0,0,0)),!0}function f(y,w,b,E,A,S,x,T,I,R,O){let P=x/(x-T);R.x=E+(A-E)*P,O.start.subVectors(w,y).multiplyScalar(P).add(y),P=x/(x-I),R.y=E+(S-E)*P,O.end.subVectors(b,y).multiplyScalar(P).add(y)}function m(y,w,b,E,A,S,x,T,I,R,O){if(A>0)f(y.c,y.a,y.b,E,w,b,I,x,T,R,O);else if(S>0)f(y.b,y.a,y.c,b,w,E,T,x,I,R,O);else if(T*I>0||x!=0)f(y.a,y.b,y.c,w,b,E,x,T,I,R,O);else if(T!=0)f(y.b,y.a,y.c,b,w,E,T,x,I,R,O);else if(I!=0)f(y.c,y.a,y.b,E,w,b,I,x,T,R,O);else return!0;return!1}function p(y,w,b,E){const A=w.degenerateSegment,S=y.plane.distanceToPoint(A.start),x=y.plane.distanceToPoint(A.end);return Zs(S)?Zs(x)?d(y,w,b,E):(b&&(b.start.copy(A.start),b.end.copy(A.start)),y.containsPoint(A.start)):Zs(x)?(b&&(b.start.copy(A.end),b.end.copy(A.end)),y.containsPoint(A.end)):y.plane.intersectLine(A,s)!=null?(b&&(b.start.copy(s),b.end.copy(s)),y.containsPoint(s)):!1}function g(y,w,b){const E=w.a;return Zs(y.plane.distanceToPoint(E))&&y.containsPoint(E)?(b&&(b.start.copy(E),b.end.copy(E)),!0):!1}function M(y,w,b){const E=y.degenerateSegment,A=w.a;return E.closestPointToPoint(A,!0,s),A.distanceToSquared(s)<F0?(b&&(b.start.copy(A),b.end.copy(A)),!0):!1}function v(y,w,b,E){if(y.isDegenerateIntoSegment)if(w.isDegenerateIntoSegment){const A=y.degenerateSegment,S=w.degenerateSegment,x=i,T=n;A.delta(x),S.delta(T);const I=s.subVectors(S.start,A.start),R=x.x*T.y-x.y*T.x;if(Zs(R))return!1;const O=(I.x*T.y-I.y*T.x)/R,P=-(x.x*I.y-x.y*I.x)/R;if(O<0||O>1||P<0||P>1)return!1;const k=A.start.z+x.z*O,_=S.start.z+T.z*P;return Zs(k-_)?(b&&(b.start.copy(A.start).addScaledVector(x,O),b.end.copy(A.start).addScaledVector(x,O)),!0):!1}else return w.isDegenerateIntoPoint?M(y,w,b):p(w,y,b,E);else{if(y.isDegenerateIntoPoint)return w.isDegenerateIntoPoint?w.a.distanceToSquared(y.a)<F0?(b&&(b.start.copy(y.a),b.end.copy(y.a)),!0):!1:w.isDegenerateIntoSegment?M(w,y,b):g(w,y,b);if(w.isDegenerateIntoPoint)return g(y,w,b);if(w.isDegenerateIntoSegment)return p(y,w,b,E)}}return function(w,b=null,E=!1){this.needsUpdate&&this.update(),w.isExtendedTriangle?w.needsUpdate&&w.update():(u.copy(w),u.update(),w=u);const A=v(this,w,b,E);if(A!==void 0)return A;const S=this.plane,x=w.plane;let T=x.distanceToPoint(this.a),I=x.distanceToPoint(this.b),R=x.distanceToPoint(this.c);Zs(T)&&(T=0),Zs(I)&&(I=0),Zs(R)&&(R=0);const O=T*I,P=T*R;if(O>0&&P>0)return!1;let k=S.distanceToPoint(w.a),_=S.distanceToPoint(w.b),rt=S.distanceToPoint(w.c);Zs(k)&&(k=0),Zs(_)&&(_=0),Zs(rt)&&(rt=0);const lt=k*_,St=k*rt;if(lt>0&&St>0)return!1;i.copy(S.normal),n.copy(x.normal);const K=i.cross(n);let mt=0,xt=Math.abs(K.x);const Ht=Math.abs(K.y);Ht>xt&&(xt=Ht,mt=1),Math.abs(K.z)>xt&&(mt=2);const ue=Pv[mt],ce=this.a[ue],li=this.b[ue],Be=this.c[ue],L=w.a[ue],Ve=w.b[ue],_a=w.c[ue];if(m(this,ce,li,Be,O,P,T,I,R,h,o))return d(this,w,b,E);if(m(w,L,Ve,_a,lt,St,k,_,rt,l,r))return d(this,w,b,E);if(h.y<h.x){const gt=h.y;h.y=h.x,h.x=gt,c.copy(o.start),o.start.copy(o.end),o.end.copy(c)}if(l.y<l.x){const gt=l.y;l.y=l.x,l.x=gt,c.copy(r.start),r.start.copy(r.end),r.end.copy(c)}return h.y<l.x||l.y<h.x?!1:(b&&(l.x>h.x?b.start.copy(r.start):b.start.copy(o.start),l.y<h.y?b.end.copy(r.end):b.end.copy(o.end)),!0)}})();Ei.prototype.distanceToPoint=(function(){const u=new D;return function(e){return this.closestPointToPoint(e,u),e.distanceTo(u)}})();Ei.prototype.distanceToTriangle=(function(){const u=new D,t=new D,e=["a","b","c"],s=new bn,i=new bn;return function(a,o=null,r=null){const c=o||r?s:null;if(this.intersectsTriangle(a,c,!0))return(o||r)&&(o&&c.getCenter(o),r&&c.getCenter(r)),0;let h=1/0;for(let l=0;l<3;l++){let d;const f=e[l],m=a[f];this.closestPointToPoint(m,u),d=m.distanceToSquared(u),d<h&&(h=d,o&&o.copy(u),r&&r.copy(m));const p=this[f];a.closestPointToPoint(p,u),d=p.distanceToSquared(u),d<h&&(h=d,o&&o.copy(p),r&&r.copy(u))}for(let l=0;l<3;l++){const d=e[l],f=e[(l+1)%3];s.set(this[d],this[f]);for(let m=0;m<3;m++){const p=e[m],g=e[(m+1)%3];i.set(a[p],a[g]),td(s,i,u,t);const M=u.distanceToSquared(t);M<h&&(h=M,o&&o.copy(u),r&&r.copy(t))}}return Math.sqrt(h)}})();class As{constructor(t,e,s){this.isOrientedBox=!0,this.min=new D,this.max=new D,this.matrix=new Oe,this.invMatrix=new Oe,this.points=new Array(8).fill().map(()=>new D),this.satAxes=new Array(3).fill().map(()=>new D),this.satBounds=new Array(3).fill().map(()=>new An),this.alignedSatBounds=new Array(3).fill().map(()=>new An),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),s&&this.matrix.copy(s)}set(t,e,s){this.min.copy(t),this.max.copy(e),this.matrix.copy(s),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}As.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,s=this.max,i=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let l=0;l<=1;l++){const d=1*c|2*h|4*l,f=i[d];f.x=c?s.x:e.x,f.y=h?s.y:e.y,f.z=l?s.z:e.z,f.applyMatrix4(t)}const n=this.satBounds,a=this.satAxes,o=i[0];for(let c=0;c<3;c++){const h=a[c],l=n[c],d=1<<c,f=i[d];h.subVectors(o,f),l.setFromPoints(h,i)}const r=this.alignedSatBounds;r[0].setFromPointsField(i,"x"),r[1].setFromPointsField(i,"y"),r[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();As.prototype.intersectsBox=(function(){const u=new An;return function(e){this.needsUpdate&&this.update();const s=e.min,i=e.max,n=this.satBounds,a=this.satAxes,o=this.alignedSatBounds;if(u.min=s.x,u.max=i.x,o[0].isSeparated(u)||(u.min=s.y,u.max=i.y,o[1].isSeparated(u))||(u.min=s.z,u.max=i.z,o[2].isSeparated(u)))return!1;for(let r=0;r<3;r++){const c=a[r],h=n[r];if(u.setFromBox(c,e),h.isSeparated(u))return!1}return!0}})();As.prototype.intersectsTriangle=(function(){const u=new Ei,t=new Array(3),e=new An,s=new An,i=new D;return function(a){this.needsUpdate&&this.update(),a.isExtendedTriangle?a.needsUpdate&&a.update():(u.copy(a),u.update(),a=u);const o=this.satBounds,r=this.satAxes;t[0]=a.a,t[1]=a.b,t[2]=a.c;for(let d=0;d<3;d++){const f=o[d],m=r[d];if(e.setFromPoints(m,t),f.isSeparated(e))return!1}const c=a.satBounds,h=a.satAxes,l=this.points;for(let d=0;d<3;d++){const f=c[d],m=h[d];if(e.setFromPoints(m,l),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=r[d];for(let m=0;m<4;m++){const p=h[m];if(i.crossVectors(f,p),e.setFromPoints(i,t),s.setFromPoints(i,l),e.isSeparated(s))return!1}}return!0}})();As.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();As.prototype.distanceToPoint=(function(){const u=new D;return function(e){return this.closestPointToPoint(e,u),e.distanceTo(u)}})();As.prototype.distanceToBox=(function(){const u=["x","y","z"],t=new Array(12).fill().map(()=>new bn),e=new Array(12).fill().map(()=>new bn),s=new D,i=new D;return function(a,o=0,r=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(a))return(r||c)&&(a.getCenter(i),this.closestPointToPoint(i,s),a.closestPointToPoint(s,i),r&&r.copy(s),c&&c.copy(i)),0;const h=o*o,l=a.min,d=a.max,f=this.points;let m=1/0;for(let g=0;g<8;g++){const M=f[g];i.copy(M).clamp(l,d);const v=M.distanceToSquared(i);if(v<m&&(m=v,r&&r.copy(M),c&&c.copy(i),v<h))return Math.sqrt(v)}let p=0;for(let g=0;g<3;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){const y=(g+1)%3,w=(g+2)%3,b=M<<y|v<<w,E=1<<g|M<<y|v<<w,A=f[b],S=f[E];t[p].set(A,S);const T=u[g],I=u[y],R=u[w],O=e[p],P=O.start,k=O.end;P[T]=l[T],P[I]=M?l[I]:d[I],P[R]=v?l[R]:d[I],k[T]=d[T],k[I]=M?l[I]:d[I],k[R]=v?l[R]:d[I],p++}for(let g=0;g<=1;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){i.x=g?d.x:l.x,i.y=M?d.y:l.y,i.z=v?d.z:l.z,this.closestPointToPoint(i,s);const y=i.distanceToSquared(s);if(y<m&&(m=y,r&&r.copy(s),c&&c.copy(i),y<h))return Math.sqrt(y)}for(let g=0;g<12;g++){const M=t[g];for(let v=0;v<12;v++){const y=e[v];td(M,y,s,i);const w=s.distanceToSquared(i);if(w<m&&(m=w,r&&r.copy(s),c&&c.copy(i),w<h))return Math.sqrt(w)}}return Math.sqrt(m)}})();class kv extends Ju{constructor(){super(()=>new Ei)}}const oi=new kv,sr=new D,rl=new D;function Lv(u,t,e={},s=0,i=1/0){const n=s*s,a=i*i;let o=1/0,r=null;if(u.shapecast({boundsTraverseOrder:h=>(sr.copy(t).clamp(h.min,h.max),sr.distanceToSquared(t)),intersectsBounds:(h,l,d)=>d<o&&d<a,intersectsTriangle:(h,l)=>{h.closestPointToPoint(t,sr);const d=t.distanceToSquared(sr);return d<o&&(rl.copy(sr),o=d,r=l),d<n}}),o===1/0)return null;const c=Math.sqrt(o);return e.point?e.point.copy(rl):e.point=rl.clone(),e.distance=c,e.faceIndex=r,e}const oc=parseInt(em)>=169,Nv=parseInt(em)<=161,sa=new D,ia=new D,na=new D,rc=new ht,cc=new ht,hc=new ht,H0=new D,U0=new D,G0=new D,ir=new D;function Cv(u,t,e,s,i,n,a,o){let r;if(n===Ai?r=u.intersectTriangle(s,e,t,!0,i):r=u.intersectTriangle(t,e,s,n!==tn,i),r===null)return null;const c=u.origin.distanceTo(i);return c<a||c>o?null:{distance:c,point:i.clone()}}function B0(u,t,e,s,i,n,a,o,r,c,h){sa.fromBufferAttribute(t,n),ia.fromBufferAttribute(t,a),na.fromBufferAttribute(t,o);const l=Cv(u,sa,ia,na,ir,r,c,h);if(l){if(s){rc.fromBufferAttribute(s,n),cc.fromBufferAttribute(s,a),hc.fromBufferAttribute(s,o),l.uv=new ht;const f=eo.getInterpolation(ir,sa,ia,na,rc,cc,hc,l.uv);oc||(l.uv=f)}if(i){rc.fromBufferAttribute(i,n),cc.fromBufferAttribute(i,a),hc.fromBufferAttribute(i,o),l.uv1=new ht;const f=eo.getInterpolation(ir,sa,ia,na,rc,cc,hc,l.uv1);oc||(l.uv1=f),Nv&&(l.uv2=l.uv1)}if(e){H0.fromBufferAttribute(e,n),U0.fromBufferAttribute(e,a),G0.fromBufferAttribute(e,o),l.normal=new D;const f=eo.getInterpolation(ir,sa,ia,na,H0,U0,G0,l.normal);l.normal.dot(u.direction)>0&&l.normal.multiplyScalar(-1),oc||(l.normal=f)}const d={a:n,b:a,c:o,normal:new D,materialIndex:0};if(eo.getNormal(sa,ia,na,d.normal),l.face=d,l.faceIndex=n,oc){const f=new D;eo.getBarycoord(ir,sa,ia,na,f),l.barycoord=f}}return l}function V0(u){return u&&u.isMaterial?u.side:u}function Oh(u,t,e,s,i,n,a){const o=s*3;let r=o+0,c=o+1,h=o+2;const{index:l,groups:d}=u;u.index&&(r=l.getX(r),c=l.getX(c),h=l.getX(h));const{position:f,normal:m,uv:p,uv1:g}=u.attributes;if(Array.isArray(t)){const M=s*3;for(let v=0,y=d.length;v<y;v++){const{start:w,count:b,materialIndex:E}=d[v];if(M>=w&&M<w+b){const A=V0(t[E]),S=B0(e,f,m,p,g,r,c,h,A,n,a);if(S)if(S.faceIndex=s,S.face.materialIndex=E,i)i.push(S);else return S}}}else{const M=V0(t),v=B0(e,f,m,p,g,r,c,h,M,n,a);if(v)if(v.faceIndex=s,v.face.materialIndex=0,i)i.push(v);else return v}return null}function Pe(u,t,e,s){const i=u.a,n=u.b,a=u.c;let o=t,r=t+1,c=t+2;e&&(o=e.getX(o),r=e.getX(r),c=e.getX(c)),i.x=s.getX(o),i.y=s.getY(o),i.z=s.getZ(o),n.x=s.getX(r),n.y=s.getY(r),n.z=s.getZ(r),a.x=s.getX(c),a.y=s.getY(c),a.z=s.getZ(c)}function _v(u,t,e,s,i,n,a,o){const{geometry:r,_indirectBuffer:c}=u;for(let h=s,l=s+i;h<l;h++)Oh(r,t,e,h,n,a,o)}function zv(u,t,e,s,i,n,a){const{geometry:o,_indirectBuffer:r}=u;let c=1/0,h=null;for(let l=s,d=s+i;l<d;l++){let f;f=Oh(o,t,e,l,null,n,a),f&&f.distance<c&&(h=f,c=f.distance)}return h}function Fv(u,t,e,s,i,n,a){const{geometry:o}=e,{index:r}=o,c=o.attributes.position;for(let h=u,l=t+u;h<l;h++){let d;if(d=h,Pe(a,d*3,r,c),a.needsUpdate=!0,s(a,d,i,n))return!0}return!1}function Hv(u,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=u.geometry,s=e.index?e.index.array:null,i=e.attributes.position;let n,a,o,r,c=0;const h=u._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),o=new Uint16Array(n),r=new Float32Array(n),l(0,c),c+=n.byteLength;function l(d,f,m=!1){const p=d*2;if(Ae(p,o)){const g=Ze(d,a),M=Ms(p,o);let v=1/0,y=1/0,w=1/0,b=-1/0,E=-1/0,A=-1/0;for(let S=3*g,x=3*(g+M);S<x;S++){let T=s[S];const I=i.getX(T),R=i.getY(T),O=i.getZ(T);I<v&&(v=I),I>b&&(b=I),R<y&&(y=R),R>E&&(E=R),O<w&&(w=O),O>A&&(A=O)}return r[d+0]!==v||r[d+1]!==y||r[d+2]!==w||r[d+3]!==b||r[d+4]!==E||r[d+5]!==A?(r[d+0]=v,r[d+1]=y,r[d+2]=w,r[d+3]=b,r[d+4]=E,r[d+5]=A,!0):!1}else{const g=He(d),M=Ue(d,a);let v=m,y=!1,w=!1;if(t){if(!v){const T=g/Fe+f/gs,I=M/Fe+f/gs;y=t.has(T),w=t.has(I),v=!y&&!w}}else y=!0,w=!0;const b=v||y,E=v||w;let A=!1;b&&(A=l(g,f,v));let S=!1;E&&(S=l(M,f,v));const x=A||S;if(x)for(let T=0;T<3;T++){const I=g+T,R=M+T,O=r[I],P=r[I+3],k=r[R],_=r[R+3];r[d+T]=O<k?O:k,r[d+T+3]=P>_?P:_}return x}}}function Jn(u,t,e,s,i){let n,a,o,r,c,h;const l=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,m=e.origin.x,p=e.origin.y,g=e.origin.z;let M=t[u],v=t[u+3],y=t[u+1],w=t[u+3+1],b=t[u+2],E=t[u+3+2];return l>=0?(n=(M-m)*l,a=(v-m)*l):(n=(v-m)*l,a=(M-m)*l),d>=0?(o=(y-p)*d,r=(w-p)*d):(o=(w-p)*d,r=(y-p)*d),n>r||o>a||((o>n||isNaN(n))&&(n=o),(r<a||isNaN(a))&&(a=r),f>=0?(c=(b-g)*f,h=(E-g)*f):(c=(E-g)*f,h=(b-g)*f),n>h||c>a)?!1:((c>n||n!==n)&&(n=c),(h<a||a!==a)&&(a=h),n<=i&&a>=s)}function Uv(u,t,e,s,i,n,a,o){const{geometry:r,_indirectBuffer:c}=u;for(let h=s,l=s+i;h<l;h++){let d=c?c[h]:h;Oh(r,t,e,d,n,a,o)}}function Gv(u,t,e,s,i,n,a){const{geometry:o,_indirectBuffer:r}=u;let c=1/0,h=null;for(let l=s,d=s+i;l<d;l++){let f;f=Oh(o,t,e,r?r[l]:l,null,n,a),f&&f.distance<c&&(h=f,c=f.distance)}return h}function Bv(u,t,e,s,i,n,a){const{geometry:o}=e,{index:r}=o,c=o.attributes.position;for(let h=u,l=t+u;h<l;h++){let d;if(d=e.resolveTriangleIndex(h),Pe(a,d*3,r,c),a.needsUpdate=!0,s(a,d,i,n))return!0}return!1}function Vv(u,t,e,s,i,n,a){re.setBuffer(u._roots[t]),xu(0,u,e,s,i,n,a),re.clearBuffer()}function xu(u,t,e,s,i,n,a){const{float32Array:o,uint16Array:r,uint32Array:c}=re,h=u*2;if(Ae(h,r)){const d=Ze(u,c),f=Ms(h,r);_v(t,e,s,d,f,i,n,a)}else{const d=He(u);Jn(d,o,s,n,a)&&xu(d,t,e,s,i,n,a);const f=Ue(u,c);Jn(f,o,s,n,a)&&xu(f,t,e,s,i,n,a)}}const Wv=["x","y","z"];function Kv(u,t,e,s,i,n){re.setBuffer(u._roots[t]);const a=Tu(0,u,e,s,i,n);return re.clearBuffer(),a}function Tu(u,t,e,s,i,n){const{float32Array:a,uint16Array:o,uint32Array:r}=re;let c=u*2;if(Ae(c,o)){const l=Ze(u,r),d=Ms(c,o);return zv(t,e,s,l,d,i,n)}else{const l=Zu(u,r),d=Wv[l],m=s.direction[d]>=0;let p,g;m?(p=He(u),g=Ue(u,r)):(p=Ue(u,r),g=He(u));const v=Jn(p,a,s,i,n)?Tu(p,t,e,s,i,n):null;if(v){const b=v.point[d];if(m?b<=a[g+l]:b>=a[g+l+3])return v}const w=Jn(g,a,s,i,n)?Tu(g,t,e,s,i,n):null;return v&&w?v.distance<=w.distance?v:w:v||w||null}}const lc=new ee,Ya=new Ei,$a=new Ei,nr=new Oe,W0=new As,uc=new As;function Yv(u,t,e,s){re.setBuffer(u._roots[t]);const i=Du(0,u,e,s);return re.clearBuffer(),i}function Du(u,t,e,s,i=null){const{float32Array:n,uint16Array:a,uint32Array:o}=re;let r=u*2;if(i===null&&(e.boundingBox||e.computeBoundingBox(),W0.set(e.boundingBox.min,e.boundingBox.max,s),i=W0),Ae(r,a)){const h=t.geometry,l=h.index,d=h.attributes.position,f=e.index,m=e.attributes.position,p=Ze(u,o),g=Ms(r,a);if(nr.copy(s).invert(),e.boundsTree)return ve(u,n,uc),uc.matrix.copy(nr),uc.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>uc.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(s),v.b.applyMatrix4(s),v.c.applyMatrix4(s),v.needsUpdate=!0;for(let y=p*3,w=(g+p)*3;y<w;y+=3)if(Pe($a,y,l,d),$a.needsUpdate=!0,v.intersectsTriangle($a))return!0;return!1}});{const M=Rh(e);for(let v=p*3,y=(g+p)*3;v<y;v+=3){Pe(Ya,v,l,d),Ya.a.applyMatrix4(nr),Ya.b.applyMatrix4(nr),Ya.c.applyMatrix4(nr),Ya.needsUpdate=!0;for(let w=0,b=M*3;w<b;w+=3)if(Pe($a,w,f,m),$a.needsUpdate=!0,Ya.intersectsTriangle($a))return!0}}}else{const h=He(u),l=Ue(u,o);return ve(h,n,lc),!!(i.intersectsBox(lc)&&Du(h,t,e,s,i)||(ve(l,n,lc),i.intersectsBox(lc)&&Du(l,t,e,s,i)))}}const dc=new Oe,cl=new As,ar=new As,$v=new D,Xv=new D,qv=new D,jv=new D;function Zv(u,t,e,s={},i={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),cl.set(t.boundingBox.min,t.boundingBox.max,e),cl.needsUpdate=!0;const o=u.geometry,r=o.attributes.position,c=o.index,h=t.attributes.position,l=t.index,d=oi.getPrimitive(),f=oi.getPrimitive();let m=$v,p=Xv,g=null,M=null;i&&(g=qv,M=jv);let v=1/0,y=null,w=null;return dc.copy(e).invert(),ar.matrix.copy(dc),u.shapecast({boundsTraverseOrder:b=>cl.distanceToBox(b),intersectsBounds:(b,E,A)=>A<v&&A<a?(E&&(ar.min.copy(b.min),ar.max.copy(b.max),ar.needsUpdate=!0),!0):!1,intersectsRange:(b,E)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:S=>ar.distanceToBox(S),intersectsBounds:(S,x,T)=>T<v&&T<a,intersectsRange:(S,x)=>{for(let T=S,I=S+x;T<I;T++){Pe(f,3*T,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let R=b,O=b+E;R<O;R++){Pe(d,3*R,c,r),d.needsUpdate=!0;const P=d.distanceToTriangle(f,m,g);if(P<v&&(p.copy(m),M&&M.copy(g),v=P,y=R,w=T),P<n)return!0}}}});{const A=Rh(t);for(let S=0,x=A;S<x;S++){Pe(f,3*S,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=b,I=b+E;T<I;T++){Pe(d,3*T,c,r),d.needsUpdate=!0;const R=d.distanceToTriangle(f,m,g);if(R<v&&(p.copy(m),M&&M.copy(g),v=R,y=T,w=S),R<n)return!0}}}}}),oi.releasePrimitive(d),oi.releasePrimitive(f),v===1/0?null:(s.point?s.point.copy(p):s.point=p.clone(),s.distance=v,s.faceIndex=y,i&&(i.point?i.point.copy(M):i.point=M.clone(),i.point.applyMatrix4(dc),p.applyMatrix4(dc),i.distance=p.sub(i.point).length(),i.faceIndex=w),s)}function Jv(u,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=u.geometry,s=e.index?e.index.array:null,i=e.attributes.position;let n,a,o,r,c=0;const h=u._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),o=new Uint16Array(n),r=new Float32Array(n),l(0,c),c+=n.byteLength;function l(d,f,m=!1){const p=d*2;if(Ae(p,o)){const g=Ze(d,a),M=Ms(p,o);let v=1/0,y=1/0,w=1/0,b=-1/0,E=-1/0,A=-1/0;for(let S=g,x=g+M;S<x;S++){const T=3*u.resolveTriangleIndex(S);for(let I=0;I<3;I++){let R=T+I;R=s?s[R]:R;const O=i.getX(R),P=i.getY(R),k=i.getZ(R);O<v&&(v=O),O>b&&(b=O),P<y&&(y=P),P>E&&(E=P),k<w&&(w=k),k>A&&(A=k)}}return r[d+0]!==v||r[d+1]!==y||r[d+2]!==w||r[d+3]!==b||r[d+4]!==E||r[d+5]!==A?(r[d+0]=v,r[d+1]=y,r[d+2]=w,r[d+3]=b,r[d+4]=E,r[d+5]=A,!0):!1}else{const g=He(d),M=Ue(d,a);let v=m,y=!1,w=!1;if(t){if(!v){const T=g/Fe+f/gs,I=M/Fe+f/gs;y=t.has(T),w=t.has(I),v=!y&&!w}}else y=!0,w=!0;const b=v||y,E=v||w;let A=!1;b&&(A=l(g,f,v));let S=!1;E&&(S=l(M,f,v));const x=A||S;if(x)for(let T=0;T<3;T++){const I=g+T,R=M+T,O=r[I],P=r[I+3],k=r[R],_=r[R+3];r[d+T]=O<k?O:k,r[d+T+3]=P>_?P:_}return x}}}function Qv(u,t,e,s,i,n,a){re.setBuffer(u._roots[t]),Iu(0,u,e,s,i,n,a),re.clearBuffer()}function Iu(u,t,e,s,i,n,a){const{float32Array:o,uint16Array:r,uint32Array:c}=re,h=u*2;if(Ae(h,r)){const d=Ze(u,c),f=Ms(h,r);Uv(t,e,s,d,f,i,n,a)}else{const d=He(u);Jn(d,o,s,n,a)&&Iu(d,t,e,s,i,n,a);const f=Ue(u,c);Jn(f,o,s,n,a)&&Iu(f,t,e,s,i,n,a)}}const ty=["x","y","z"];function ey(u,t,e,s,i,n){re.setBuffer(u._roots[t]);const a=Ru(0,u,e,s,i,n);return re.clearBuffer(),a}function Ru(u,t,e,s,i,n){const{float32Array:a,uint16Array:o,uint32Array:r}=re;let c=u*2;if(Ae(c,o)){const l=Ze(u,r),d=Ms(c,o);return Gv(t,e,s,l,d,i,n)}else{const l=Zu(u,r),d=ty[l],m=s.direction[d]>=0;let p,g;m?(p=He(u),g=Ue(u,r)):(p=Ue(u,r),g=He(u));const v=Jn(p,a,s,i,n)?Ru(p,t,e,s,i,n):null;if(v){const b=v.point[d];if(m?b<=a[g+l]:b>=a[g+l+3])return v}const w=Jn(g,a,s,i,n)?Ru(g,t,e,s,i,n):null;return v&&w?v.distance<=w.distance?v:w:v||w||null}}const fc=new ee,Xa=new Ei,qa=new Ei,or=new Oe,K0=new As,mc=new As;function sy(u,t,e,s){re.setBuffer(u._roots[t]);const i=Ou(0,u,e,s);return re.clearBuffer(),i}function Ou(u,t,e,s,i=null){const{float32Array:n,uint16Array:a,uint32Array:o}=re;let r=u*2;if(i===null&&(e.boundingBox||e.computeBoundingBox(),K0.set(e.boundingBox.min,e.boundingBox.max,s),i=K0),Ae(r,a)){const h=t.geometry,l=h.index,d=h.attributes.position,f=e.index,m=e.attributes.position,p=Ze(u,o),g=Ms(r,a);if(or.copy(s).invert(),e.boundsTree)return ve(u,n,mc),mc.matrix.copy(or),mc.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>mc.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(s),v.b.applyMatrix4(s),v.c.applyMatrix4(s),v.needsUpdate=!0;for(let y=p,w=g+p;y<w;y++)if(Pe(qa,3*t.resolveTriangleIndex(y),l,d),qa.needsUpdate=!0,v.intersectsTriangle(qa))return!0;return!1}});{const M=Rh(e);for(let v=p,y=g+p;v<y;v++){const w=t.resolveTriangleIndex(v);Pe(Xa,3*w,l,d),Xa.a.applyMatrix4(or),Xa.b.applyMatrix4(or),Xa.c.applyMatrix4(or),Xa.needsUpdate=!0;for(let b=0,E=M*3;b<E;b+=3)if(Pe(qa,b,f,m),qa.needsUpdate=!0,Xa.intersectsTriangle(qa))return!0}}}else{const h=He(u),l=Ue(u,o);return ve(h,n,fc),!!(i.intersectsBox(fc)&&Ou(h,t,e,s,i)||(ve(l,n,fc),i.intersectsBox(fc)&&Ou(l,t,e,s,i)))}}const pc=new Oe,hl=new As,rr=new As,iy=new D,ny=new D,ay=new D,oy=new D;function ry(u,t,e,s={},i={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),hl.set(t.boundingBox.min,t.boundingBox.max,e),hl.needsUpdate=!0;const o=u.geometry,r=o.attributes.position,c=o.index,h=t.attributes.position,l=t.index,d=oi.getPrimitive(),f=oi.getPrimitive();let m=iy,p=ny,g=null,M=null;i&&(g=ay,M=oy);let v=1/0,y=null,w=null;return pc.copy(e).invert(),rr.matrix.copy(pc),u.shapecast({boundsTraverseOrder:b=>hl.distanceToBox(b),intersectsBounds:(b,E,A)=>A<v&&A<a?(E&&(rr.min.copy(b.min),rr.max.copy(b.max),rr.needsUpdate=!0),!0):!1,intersectsRange:(b,E)=>{if(t.boundsTree){const A=t.boundsTree;return A.shapecast({boundsTraverseOrder:S=>rr.distanceToBox(S),intersectsBounds:(S,x,T)=>T<v&&T<a,intersectsRange:(S,x)=>{for(let T=S,I=S+x;T<I;T++){const R=A.resolveTriangleIndex(T);Pe(f,3*R,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let O=b,P=b+E;O<P;O++){const k=u.resolveTriangleIndex(O);Pe(d,3*k,c,r),d.needsUpdate=!0;const _=d.distanceToTriangle(f,m,g);if(_<v&&(p.copy(m),M&&M.copy(g),v=_,y=O,w=T),_<n)return!0}}}})}else{const A=Rh(t);for(let S=0,x=A;S<x;S++){Pe(f,3*S,l,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=b,I=b+E;T<I;T++){const R=u.resolveTriangleIndex(T);Pe(d,3*R,c,r),d.needsUpdate=!0;const O=d.distanceToTriangle(f,m,g);if(O<v&&(p.copy(m),M&&M.copy(g),v=O,y=T,w=S),O<n)return!0}}}}}),oi.releasePrimitive(d),oi.releasePrimitive(f),v===1/0?null:(s.point?s.point.copy(p):s.point=p.clone(),s.distance=v,s.faceIndex=y,i&&(i.point?i.point.copy(M):i.point=M.clone(),i.point.applyMatrix4(pc),p.applyMatrix4(pc),i.distance=p.sub(i.point).length(),i.faceIndex=w),s)}function Y0(u,t,e){return u===null?null:(u.point.applyMatrix4(t.matrixWorld),u.distance=u.point.distanceTo(e.ray.origin),u.object=t,u)}const gc=new As,Mc=new sm,$0=new D,X0=new Oe,q0=new D,ll=["getX","getY","getZ"];class lh extends Iv{static serialize(t,e={}){e={cloneBuffers:!0,...e};const s=t.geometry,i=t._roots,n=t._indirectBuffer,a=s.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(o.roots=i.map(r=>r.slice()),o.index=a?a.array.slice():null,o.indirectBuffer=n?n.slice():null):(o.roots=i,o.index=a?a.array:null,o.indirectBuffer=n),o}static deserialize(t,e,s={}){s={setIndex:!0,indirect:!!t.indirectBuffer,...s};const{index:i,roots:n,indirectBuffer:a}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),r(n));const o=new lh(e,{...s,[ju]:!0});if(o._roots=n,o._indirectBuffer=a||null,s.setIndex){const c=e.getIndex();if(c===null){const h=new Ot(t.index,1,!1);e.setIndex(h)}else c.array!==i&&(c.array.set(i),c.needsUpdate=!0)}return o;function r(c){for(let h=0;h<c.length;h++){const l=c[h],d=new Uint32Array(l),f=new Uint16Array(l);for(let m=0,p=l.byteLength/gs;m<p;m++){const g=Fe*m,M=2*g;Ae(M,f)||(d[g+6]=d[g+6]/Fe-m)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,s){const i=this.geometry,n=this._indirectBuffer,a=i.attributes.position,o=i.index?i.index.array:null,c=(n?n[t]:t)*3;let h=c+0,l=c+1,d=c+2;o&&(h=o[h],l=o[l],d=o[d]);for(let f=0;f<3;f++){const m=a[ll[f]](h),p=a[ll[f]](l),g=a[ll[f]](d);let M=m;p<M&&(M=p),g<M&&(M=g);let v=m;p>v&&(v=p),g>v&&(v=g),e[s+f]=M,e[s+f+3]=v}return e}computePrimitiveBounds(t,e,s){const i=this.geometry,n=this._indirectBuffer,a=i.attributes.position,o=i.index?i.index.array:null,r=a.normalized;if(t<0||e+t-s.offset>s.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const c=a.array,h=a.offset||0;let l=3;a.isInterleavedBufferAttribute&&(l=a.data.stride);const d=["getX","getY","getZ"],f=s.offset;for(let m=t,p=t+e;m<p;m++){const M=(n?n[m]:m)*3,v=(m-f)*6;let y=M+0,w=M+1,b=M+2;o&&(y=o[y],w=o[w],b=o[b]),r||(y=y*l+h,w=w*l+h,b=b*l+h);for(let E=0;E<3;E++){let A,S,x;r?(A=a[d[E]](y),S=a[d[E]](w),x=a[d[E]](b)):(A=c[y+E],S=c[w+E],x=c[b+E]);let T=A;S<T&&(T=S),x<T&&(T=x);let I=A;S>I&&(I=S),x>I&&(I=x);const R=(I-T)/2,O=E*2;s[v+O+0]=T+R,s[v+O+1]=R+(Math.abs(T)+R)*_c}}return s}raycastObject3D(t,e,s=[]){const{material:i}=t;if(i===void 0)return;X0.copy(t.matrixWorld).invert(),Mc.copy(e.ray).applyMatrix4(X0),q0.setFromMatrixScale(t.matrixWorld),$0.copy(Mc.direction).multiply(q0);const n=$0.length(),a=e.near/n,o=e.far/n;if(e.firstHitOnly===!0){let r=this.raycastFirst(Mc,i,a,o);r=Y0(r,t,e),r&&s.push(r)}else{const r=this.raycast(Mc,i,a,o);for(let c=0,h=r.length;c<h;c++){const l=Y0(r[c],t,e);l&&s.push(l)}}return s}refit(t=null){return(this.indirect?Jv:Hv)(this,t)}raycast(t,e=md,s=0,i=1/0){const n=this._roots,a=[],o=this.indirect?Qv:Vv;for(let r=0,c=n.length;r<c;r++)o(this,r,e,t,a,s,i);return a}raycastFirst(t,e=md,s=0,i=1/0){const n=this._roots;let a=null;const o=this.indirect?ey:Kv;for(let r=0,c=n.length;r<c;r++){const h=o(this,r,e,t,s,i);h!=null&&(a==null||h.distance<a.distance)&&(a=h)}return a}intersectsGeometry(t,e){let s=!1;const i=this._roots,n=this.indirect?sy:Yv;for(let a=0,o=i.length;a<o&&(s=n(this,a,t,e),!s);a++);return s}shapecast(t){const e=oi.getPrimitive(),s=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?Bv:Fv});return oi.releasePrimitive(e),s}bvhcast(t,e,s){let{intersectsRanges:i,intersectsTriangles:n}=s;const a=oi.getPrimitive(),o=this.geometry.index,r=this.geometry.attributes.position,c=this.indirect?m=>{const p=this.resolveTriangleIndex(m);Pe(a,p*3,o,r)}:m=>{Pe(a,m*3,o,r)},h=oi.getPrimitive(),l=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?m=>{const p=t.resolveTriangleIndex(m);Pe(h,p*3,l,d)}:m=>{Pe(h,m*3,l,d)};if(n){if(!(t instanceof lh))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const m=(p,g,M,v,y,w,b,E)=>{for(let A=M,S=M+v;A<S;A++){f(A),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let x=p,T=p+g;x<T;x++)if(c(x),a.needsUpdate=!0,n(a,h,x,A,y,w,b,E))return!0}return!1};if(i){const p=i;i=function(g,M,v,y,w,b,E,A){return p(g,M,v,y,w,b,E,A)?!0:m(g,M,v,y,w,b,E,A)}}else i=m}return super.bvhcast(t,e,{intersectsRanges:i})}intersectsBox(t,e){return gc.set(t.min,t.max,e),gc.needsUpdate=!0,this.shapecast({intersectsBounds:s=>gc.intersectsBox(s),intersectsTriangle:s=>gc.intersectsTriangle(s)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,s={},i={},n=0,a=1/0){return(this.indirect?ry:Zv)(this,t,e,s,i,n,a)}closestPointToPoint(t,e={},s=0,i=1/0){return Lv(this,t,e,s,i)}}class Ri{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new zl;static install(){if(Ri.installed)return;Ri.installed=!0;const t=B.prototype.raycast;B.prototype.raycast=function(e,s){const i=Ri.treeOf(this,e);i!==null&&(i?i.raycastObject3D(this,e,s):t.call(this,e,s))}}static treeOf(t,e){const s=t.geometry,i=s?.attributes.position;if(!(i instanceof Ot)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||s.morphAttributes.position)return;const n=s.index;if((n?n.count:i.count)/3<Ri.MIN_TRIANGLES||s.drawRange.start!==0||s.drawRange.count!==1/0)return;s.boundingSphere===null&&s.computeBoundingSphere();const a=Ri.sphere.copy(s.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(a))return null;const o=Ri.trees.get(s);if(o){if(!o.bvh)return;if(o.position===i&&o.positionVersion===i.version&&o.index===n&&o.indexVersion===(n?.version??0))return o.bvh;Ri.trees.set(s,{positionVersion:-1,index:null,indexVersion:-1});return}const r=new lh(s,{indirect:!0});return Ri.trees.set(s,{bvh:r,position:i,positionVersion:i.version,index:n,indexVersion:n?.version??0}),r}}function cy(u,t){return JSON.stringify(u.cloudLayers)===JSON.stringify(t.cloudLayers)&&u.cloudCover===t.cloudCover&&u.cloudDarkness===t.cloudDarkness&&u.cloudBaseM===t.cloudBaseM&&u.highCloudCover===t.highCloudCover&&u.iceCrystalAlignment===t.iceCrystalAlignment&&u.rareIceCrystals===t.rareIceCrystals&&u.lowerCloudCover===t.lowerCloudCover&&u.relativeHumidity===t.relativeHumidity&&u.visibilityKm===t.visibilityKm&&u.precipitationType===t.precipitationType&&u.precipitationIntensity===t.precipitationIntensity&&u.precipitationAmount===t.precipitationAmount&&u.windDirectionDeg===t.windDirectionDeg&&u.windSpeed===t.windSpeed&&u.storm===t.storm}const vc=900,ul=Ca.decorDepth,j0=Ca.dazzle,dl=Ca.hud,yc=.5,wc=it.GROUND_RADIUS_M;function Z0(u){return it.groundRadiusFor(u)}const fl=.5,ml=850,bc=.03,hy=.015,de=850,ja=300,sn=120,ly=700,pl=.03,uy=3.5,Ec=20,gl=.04,dy=.26,J0=4,Ml=1.5,Q0=-1,fy=.01,Fc=-4,my=2,py=20,Ac=2600,gy=.97,My=.38,cr=Fc,vy=8,yy=2,tf=1500,wy=.7,by=.3,Ey=.32,Ay=.65,ef=2.4,Sy=.9,xy=400,Ty=[0,45,90,135,180,225,270,315],Dy=2,Iy=16,sf=4e3,nf=880,Sc=40,af=60,Ry=10,of=1,Oy=it.REBUILD_DISTANCE_M,rf=.265,cf=[[0,0],...Array.from({length:8},(u,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*rf,Math.sin(e)*rf]})],vl=700,yl=250/Yf,Py=12,hf=5,wl=6,aa=[.92,.92,.95],bl=[.15,.15,.19],El={snow:{fallSpeedMPerS:2,size:.3,color:new q(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new q(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},ao=0,Al=0,ky=150,Sl=3e3,hr=20,Ly=15,lf=ao,Ny=40,uf=1,Cy=9;function xl(u){return uf+(Cy-uf)*u}const df=new q(.75,.82,.92),_y=10,zy=.5;function ff(u){return Oi(u/_y,zy,1)}const oa=200,mf=.18,pf=.32,Fy=.35,gf=new q(.85,.9,.98),Mf=5,vf=.85,yf=.01;function Hy(u,t,e=1){return Math.round(u*(yf+(1-yf)*t)*e)}function Uy(u,t){return JSON.stringify(u.cloudLayers)===JSON.stringify(t.cloudLayers)&&u.cloudCover===t.cloudCover&&u.cloudDarkness===t.cloudDarkness&&u.cloudBaseM===t.cloudBaseM&&u.highCloudCover===t.highCloudCover&&u.iceCrystalAlignment===t.iceCrystalAlignment&&u.lowerCloudCover===t.lowerCloudCover}const wf=230,bf=.7,Ef=.05,Gy=.6,By=.7,Vy=.15,Af=.35,Wy=3,Ky=1/12,Yy=.5,xi=new q(.82,.86,1),$y=2500,Xy=1.6,Tl=15,qy={Venus:new q(1,.96,.85),Mars:new q(1,.55,.4),Jupiter:new q(.95,.87,.72),Saturn:new q(.92,.86,.68)};class N{renderer;scene=new js;phenomena=new Rs(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Ft;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let s=!0;const i=()=>{s&&(s=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=e===void 0?void 0:setTimeout(i,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(n),i()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+sf,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),sf+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ct;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ht;decorModelProvider=new gp;decorModelToken=0;decorModelCredits=new Map;emitterLights=new ys(this.scene,()=>this.relativeScale,{halfExtentM:sn,depthHalfRangeM:ja,biasM:pl,normalBiasM:gl,mapSize:1024});bodySystem=new G(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??N.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*N.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;skyEventCloudLights=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Uc(16777215,0);celestialLightTarget=new Jf;skyLight=new Jp(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new Pc;weather=Fp;observerElevationM=0;siteElevationM=0;air=new us;groundRadius=wc;terrainRadius=wc;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new D;cloudFieldOffset=new D;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new D;rainLastVerticalFacing=-1;rainViewportSize=new ht;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Uc(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new Pc;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new Pc;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=wt.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Ur;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Gm()){Ar.install(),Sr.install(),Ri.install(),this.renderer=new Qp({canvas:t,antialias:!0}),this.resolution=new zt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=tg,this.camera=new Gc(60,t.width/Math.max(t.height,1),.1,vc*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-sn,this.celestialLight.shadow.camera.right=sn,this.celestialLight.shadow.camera.top=sn,this.celestialLight.shadow.camera.bottom=-sn,this.celestialLight.shadow.camera.near=de-ja,this.celestialLight.shadow.camera.far=de+ja,this.celestialLight.shadow.bias=-pl/(2*ja),this.celestialLight.shadow.normalBias=gl,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(xi),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const s=new st(this.renderer,()=>{this.skyColoursStale=!0,this.render()});s.supported?this.scatteredSky=s:s.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.lastBodies&&this.setBodies(...this.lastBodies),this.render()}lastBodies;setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*yl,0,t.z*yl);for(const s of[this.cloudUniforms,this.cirrusUniforms])s?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Mt,s=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Mt;t.headingDeg!==void 0?this.camera.rotation.set(s,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Mt,e,"YXZ"):this.camera.rotation.set(s,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(Z0(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/wc),this.camera.far=Math.max(vc*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseStatedElevationM=t.elevationM,this.poseAltitudeM=t.altitudeM,this.poseElevationM=t.altitudeM!==void 0?Math.max(0,t.altitudeM-this.siteElevationM-this.groundYUnder(0,0)):t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=N.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return it.decorReachFor(t,e)}placeTerrain(t,e,s,i){const n=(a,o)=>{const r=ot(o.lat,o.lng,t,e);a.position.x=r.x-s,a.position.z=r.z+i};if(this.terrainMesh&&this.terrainMeshOrigin&&n(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&n(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const a=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=a}this.lookPatch&&n(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=of+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=it.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const s=(t.headingDeg??0)*Math.PI/180,i=t.lat+e.distanceM*Math.cos(s)/111320,n=t.lng+e.distanceM*Math.sin(s)/(111320*Math.cos(t.lat*Math.PI/180)),a=this.lookPatchAsked;if(a){const c=ot(i,n,a.lat,a.lng);if(Math.hypot(c.x,c.z)<a.radiusM*N.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:i,lng:n,radiusM:e.radiusM};const o=++this.lookPatchToken,r=this.terrainProviders;Kh(i,n,{elevation:r.elevation,imagery:r.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:c})=>{if(o!==this.lookPatchToken||this.terrainProviders!==r||!this.terrainMesh){this.disposeMesh(c);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),c.renderOrder=N.LOOK_PATCH_RENDER_ORDER,c.position.y=this.terrainMesh.position.y;const h=c.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:c,origin:{lat:i,lng:n},radiusM:e.radiusM};const l=ot(i,n,t.lat,t.lng);c.position.x=l.x,c.position.z=l.z,this.scene.add(c),this.compileNextFrameOffThread(),this.render()},c=>console.warn("No sharp ground under what is looked at:",c))}setTerrainOrigin(t,e,s){if(t===void 0||e===void 0)return;const i=this.terrainProviders.patches;let n;if(i){if(!i.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:s},this.patchesAwaited!==i){this.patchesAwaited=i;const d=this.terrainProviders;this.awaitArrival(i.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),N.TERRAIN_PATIENCE_MS)}return}const l=i.nearest(t,e);l&&(t=l.lat,e=l.lng,n=l.radiusM)}const a=n??Math.max(it.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-a)<a*.1){const{x:l,z:d}=ot(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(l*l+d*d)<Oy*(a/wc))return}const o=this.terrainRadius,r=this.terrainMeshOrigin;r!==void 0&&Math.hypot(ot(t,e,r.lat,r.lng).x,ot(t,e,r.lat,r.lng).z)<=o||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=a;const h=++this.terrainBuildToken;this.awaitArrival(Kh(t,e,this.terrainProviders,a,{route:this.observerRoute}),N.TERRAIN_PATIENCE_MS).then(({mesh:l,attribution:d,originElevationM:f,water:m,waterLater:p})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(l,t,e);const g=this.terrainMesh,M=this.terrainMeshOrigin,v=M?ot(t,e,M.lat,M.lng):void 0;g&&v&&Math.hypot(v.x,v.z)<=o&&(l.position.y=g.position.y+this.groundYOfPatch(g,v.x,v.z)),g&&M&&v&&Math.hypot(v.x,v.z)<=o?this.crossfadeTerrain(l,g,M):this.disposeMesh(this.terrainMesh),l.renderOrder=of,this.terrainMesh=l,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(l),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,a),this.buildWater(t,e,a,m,p),this.buildRailways(t,e,a),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,a,l,f),this.render(),s?.()}).catch(l=>{console.warn("Terrain build failed, keeping the flat ground fallback:",l),s?.()})}buildFarRing(t,e,s,i,n){i.geometry.computeBoundingBox();const a=i.position.y+(i.geometry.boundingBox?.min.y??0),o=this.camera.position.y-a,r=this.skyEventReachM({lat:t,lng:e}),c=it.farRingRadiusFor(this.weather.visibilityKm);if(!it.needsFarRing(s,o,r,c)){this.dropFarRing();return}if(this.farRing&&this.farRingRadiusM===c){const{x:p,z:g}=ot(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,g)<s*N.FAR_RING_KEPT_SHARE)return}const h=this.terrainProviders.patches,l=h?.farRingOf?.(t,e);if(h&&!l){this.dropFarRing();return}const d=l?.radiusM??c,f=++this.farRingToken,m=this.terrainProviders;this.awaitArrival(Kh(t,e,{elevation:m.elevation,imagery:m.imagery},d,void 0,{innerM:s*N.FAR_RING_OPEN_SHARE,referenceElevationM:n,gridSize:it.farRingGridFor(d)}),N.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(f!==this.farRingToken||this.terrainProviders!==m){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=f,p.renderOrder=N.FAR_RING_RENDER_ORDER,p.position.y=i.position.y-N.FAR_RING_DROP_M;const g=p.material;g.polygonOffset=!0,g.polygonOffsetFactor=2,g.polygonOffsetUnits=8,g.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=d,this.applyGroundDepthWrite(),this.scene.add(p),p.position.x=i.position.x,p.position.z=i.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,s){if(this.grassReference){const a=ot(this.grassReference.lat,this.grassReference.lng,e,s);Math.hypot(a.x,a.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:s};const i=ot(this.grassReference.lat,this.grassReference.lng,e,s);t.material.userData?.grassOrigin?.set(i.x,i.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,s){this.stopTerrainFade();const i=t.material;i.opacity=0,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-4;const n=performance.now(),a=()=>{const o=Math.min(1,(performance.now()-n)/N.TERRAIN_CROSSFADE_MS);if(i.opacity=o*o*(3-2*o),this.render(),o<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(a);return}i.polygonOffset=!1,i.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:s,frameId:requestAnimationFrame(a)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=it.ROADS_MAX_RADIUS_M;buildRoads(t,e,s){const i=this.terrainProviders.roads;if(!i||s>N.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===t&&n.lng===e&&n.radiusM===s){this.drapeRoads(n.ways,t,e,i.contemporary);return}n&&Math.hypot(ot(t,e,n.lat,n.lng).x,ot(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,t,e,i.contemporary),this.awaitArrival(i.getRoads(xr(t,e,s)),N.ROADS_PATIENCE_MS).then(a=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:s,ways:a},this.drapeRoads(a,t,e,i.contemporary))}).catch(a=>{console.warn("Roads unavailable, drawing none:",a)})}buildWater(t,e,s,i,n){const a=this.terrainProviders.water;if(!a||s>N.ROADS_MAX_RADIUS_M){this.clearWater();return}if(i){this.waterSurfaces={lat:t,lng:e,radiusM:s,surfaces:i},this.awaitArrival(this.drapeWater(i,t,e,s),N.ROADS_PATIENCE_MS).catch(r=>console.warn("Water not drawn:",r));return}const o=this.waterSurfaces;if(o&&o.lat===t&&o.lng===e&&o.radiusM===s){this.drapeWater(o.surfaces,t,e,s);return}o&&Math.hypot(ot(t,e,o.lat,o.lng).x,ot(t,e,o.lat,o.lng).z)<=o.radiusM&&this.drapeWater(o.surfaces,t,e,s),this.awaitArrival((n??a.getWater(xr(t,e,s))).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:s,surfaces:r},this.drapeWater(r,t,e,s)}),N.ROADS_PATIENCE_MS).catch(r=>{console.warn("Water unavailable, drawing none:",r)})}async drapeWater(t,e,s,i){if(t.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.set(t,e,s,(o,r)=>this.groundYOfPatch(a,o,r),i,this.patchSpacingM(a)),ds.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=H(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BNxlYNtW.js");return{WaterSystem:t}},__vite__mapDeps([38,4,6]),import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,s){const i=this.terrainProviders.railways;if(!i||s>N.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===t&&n.lng===e&&n.radiusM===s){this.drapeRailways(n.lines,t,e,s);return}n&&Math.hypot(ot(t,e,n.lat,n.lng).x,ot(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,t,e,s),this.awaitArrival(i.getRailways(xr(t,e,s)).then(a=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:s,lines:a},this.drapeRailways(a,t,e,s)}),N.ROADS_PATIENCE_MS).catch(a=>{console.warn("Railways unavailable, drawing none:",a)})}async drapeRailways(t,e,s,i){if(!this.railwaySystem&&!t.some(o=>o.level>=0))return;const n=await this.loadRailwaySystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.setGroundSpacing(this.patchSpacingM(a)),n.set(t,e,s,(o,r)=>this.groundYOfPatch(a,o,r),i),ds.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=H(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-KlBj8mLP.js");return{RailwaySystem:t}},__vite__mapDeps([39,4,6]),import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,s)=>this.groundYOfPatch(t,e,s)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=H(async()=>{const{TraceSystem:t}=await import("./TraceSystem-DYmjmB9_.js");return{TraceSystem:t}},__vite__mapDeps([40,4,6,1,2,3,5,7,8,9,10]),import.meta.url).then(({TraceSystem:t})=>{const e=new t(dl);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,s=this.terrainMeshOrigin;!t||!e||!s||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,s.lat,s.lng,this.siteElevationM,(i,n)=>this.groundYOfPatch(e,i,n)))}buildingFootprints(t,e){const s=this.decorOriginInRoads(t,e);return this.decorObjects.filter(i=>i.kind==="building"&&!i.observerSide&&!i.track).map(i=>{const n=C.naturalSize(i.kind,i.floors),a=(i.headingDeg??0)*Math.PI/180;return{x:s.x+i.eastM,z:s.z-i.northM,alongX:Math.sin(a),alongZ:-Math.cos(a),halfAlongM:(i.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(i.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(t,e){const s=this.decorReferencePose;return s?.lat!==void 0&&s.lng!==void 0?ot(s.lat,s.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const s=this.decorOriginInRoads(t,e);return this.decorObjects.filter(i=>i.kind==="streetlight"&&!i.lamp?.supposed&&!i.track).map(i=>({x:s.x+i.eastM,z:s.z-i.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const s=this.decorOriginInRoads(t,e);for(const i of this.decorObjects){if(i.kind!=="streetlight"||!i.lamp?.supposed||i.track)continue;const n=s.x+i.eastM,a=s.z-i.northM,o=this.roadSystem.atKerb(n,a);(o.x!==n||o.z!==a)&&this.lampNudges.set(i.id,{eastM:o.x-n,northM:-(o.z-a)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((s,i)=>{const n=e[i];if(s.id!==n.id||(s.track?.length??-1)!==(n.track?.length??-1))return!1;const a=new Set([...Object.keys(s),...Object.keys(n)]);for(const o of a)if(!(o==="eastM"||o==="northM"||o==="track")&&s[o]!==n[o])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,s=this.terrainProviders.roads;if(!e||!s)return;const i=this.wallsOf(t,e.lat,e.lng),n=this.roadWalls;n?.lat===e.lat&&n.lng===e.lng&&n.walls.length===i.length&&n.walls.every((o,r)=>o.what===i[r].what&&Math.hypot(o.x-i[r].x,o.z-i[r].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,s.contemporary)}wallsOf(t,e,s){const i=this.decorOriginInRoads(e,s);return t.filter(n=>n.kind==="building"||n.kind==="streetlight").map(n=>({what:`${n.kind}:${n.lamp?.supposed?"s":""}${n.headingDeg??0}:${n.sizeM?.widthM??""}:${n.sizeM?.lengthM??""}`,x:i.x+n.eastM,z:i.z-n.northM}))}roadWalls;drapeRoads(t,e,s,i){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(t,e,s,(a,o)=>this.groundYOfPatch(n,a,o),i,this.terrainRadius,new Jt(this.buildingFootprints(e,s),this.surveyedLamps(e,s))),this.roadWalls={lat:e,lng:s,walls:this.wallsOf(this.decorObjects,e,s)},this.lampsToKerb(e,s),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,s]=this.sunArriving,i=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/i,1,s/i),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?_e.LENS_K:_e.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(cy(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const s=!Uy(e,t),i=e.precipitationType!==t.precipitationType,n=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;e.visibilityKm!==t.visibilityKm&&this.terrainMesh&&this.terrainMeshOrigin&&it.farRingRadiusFor(t.visibilityKm)!==it.farRingRadiusFor(e.visibilityKm)&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),(e.relativeHumidity!==t.relativeHumidity||e.visibilityKm!==t.visibilityKm||i||n)&&this.restateHaze(),s&&(this.buildClouds(),this.buildCirrus()),i?this.buildPrecipitation():n&&this.updatePrecipitationDensity(),this.lastAstronomy&&(s&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(s||i||n)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=Yy,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(N.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=N.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=N.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const s of this.decorGroups.values())s.removeFromParent(),C.dispose(s);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(s=>s.kind==="streetlight").sort((s,i)=>Math.hypot(s.eastM,s.northM)-Math.hypot(i.eastM,i.northM)).slice(0,vy);for(const s of t){const i=C.build(s,s.lit??!1);this.scene.add(i),this.decorGroups.set(s.id,i),s.kind==="streetlight"&&e.includes(s)&&this.addStreetlightLight(s.id,i,e.indexOf(s)<yy,s.lamp),s.model&&s.id.startsWith(Nt.ID_PREFIX)?(this.pendingTrafficModels.set(s.id,s),this.awaitArrival(this.loadDecorModel(s,this.decorModelToken,!0))):this.reuseLoadedDecorModel(s,i)||this.awaitArrival(this.loadDecorModel(s,this.decorModelToken))}this.decorLamps=N.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(s=>s.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=H(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-D2AR5Zgy.js");return{ContrailSystem:t}},__vite__mapDeps([41,4,42]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),s=this.lastAstronomy?.sun,i=N.CONTRAIL_SCATTERING,n=this.skyLight.color,a=[n.r*i*.5,n.g*i*.5,n.b*i*.5];if(e&&s){const o=ms.litFraction(e.sunElevationDeg,e.heightM);if(o>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),c=At.illuminanceOf(s.magnitude)*this.relativeScale;for(let h=0;h<3;h++)a[h]+=i*c*r[h]*o}}return a}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,s){if(this.skyEventsStart=s,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let i=!1;const n=new Set;for(const a of fu){const o=vn.of(a);n.add(o.key);const r=vn.eventsOf(t,o);let c=this.skyEventLayers.get(o.key);if(c?.kind!==o&&c&&(this.disposeSkyEventLayer(o.key,c),c=void 0),!(!c&&r.length===0)){if(!c)c={kind:o,events:r},this.skyEventLayers.set(o.key,c);else if(c.events===r)continue;c.events=r,i||=o.reachM!==void 0,this.loadSkyEventSimulation(c)}}for(const[a,o]of this.skyEventLayers)n.has(a)||(this.disposeSkyEventLayer(a,o),i||=o.kind.reachM!==void 0);i&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const s=e();(s.inSky?this.celestialGroup:this.scene).add(s.object),t.simulation=s,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[]),this.skyEventCloudLight(t,[])}skyEventCloudLight(t,e){e.length===0?this.skyEventCloudLights.delete(t):this.skyEventCloudLights.set(t,e),this.layeredClouds?.setLights([...this.skyEventCloudLights.values()].flat(),this.camera.position)}skyEventClouds(){const t=this.layeredClouds?.volumes??[];if(t.length===0)return;const e=this.camera.position,s={x:0,y:0,z:0};return{bottomY:Math.min(...t.map(i=>i.uniforms.baseM.value)),topY:Math.max(...t.map(i=>i.uniforms.baseM.value+i.uniforms.thicknessM.value)),extinctionAt:(i,n,a)=>{s.x=i-e.x,s.y=n-e.y,s.z=a-e.z;let o=0;for(const r of t)o+=r.densityAt(s);return o*.006},dim:i=>nh.apply(i,t)}}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(s=>this.farEmitterOf(s.position,s.magnitude)).filter(s=>s!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const s=`skyEvent:${t}:`,i=new Set;for(const n of e){const a=s+n.key,{x:o,y:r,z:c}=Vt(n.position.altitudeDeg,n.position.azimuthDeg,de),[h,l,d]=this.arrivingIlluminance(n.position,n.magnitude,this.cloudTransmission(n.position));this.setGlare(a,o,r,c,[h*n.fade,l*n.fade,d*n.fade],0,N.POINT_VEIL_HOLD_DEG),i.add(a)}for(const n of[...this.glareSprites.keys()])n.startsWith(s)&&!i.has(n)&&this.disposeGlare(n)}skyEventReachM(t){let e=0;for(const s of this.skyEventLayers.values())s.events.length>0&&s.kind.reachM&&(e=Math.max(e,s.kind.reachM(s.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,s={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},i=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,n=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Er(-90,this.instrumentMagnitudeGain);let a;for(const[o,r]of this.skyEventLayers)r.simulation&&(a??={observer:s,date:i,magnitudeLimit:n,cloudTransmission:c=>this.cloudTransmission(c),arrivingIlluminance:(c,h,l)=>this.arrivingIlluminance(c,h,l),transmittanceFromSpace:c=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,c.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(c,h,l)=>this.transmittanceTo(c,h,l),groundYAt:(c,h)=>this.groundYUnder(c,h),clouds:this.skyEventClouds(),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Mt)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Mt)*this.weather.windSpeed}},r.simulation.update(r.events,this.decorTime,{...a,lightFrom:c=>this.skyEventLight(o,c),glareFrom:c=>this.skyEventGlare(o,c),lightClouds:c=>this.skyEventCloudLight(o,c)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?Vt(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}directionToDecor(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const s=new ee().setFromObject(e);if(s.isEmpty())return;const i=s.getCenter(new D),n=this.camera.getWorldPosition(new D),a=i.x-n.x,o=n.z-i.z,r=i.y-n.y,c=Math.hypot(a,o);if(!(c===0&&r===0))return{azimuthDeg:(Math.atan2(a,o)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(r,c)*180/Math.PI}}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,s=this.groundYUnder(t,e),i=this.bodyEastScale,n=this.farRing?.mesh??(this.terrainMesh&&this.terrainRadius>it.ROADS_MAX_RADIUS_M?this.terrainMesh:void 0),a=n?(o,r)=>it.curvatureDropM(Math.hypot(o-n.position.x,r-n.position.z)):void 0;return{heightAt:(o,r)=>this.groundYUnder(t+o*i,e-r)-s,...a?{dropAt:(o,r)=>a(t+o*i,e-r)-a(t,e)}:{}}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*Mt)/Math.cos(t.lat*Mt)}bodyMaskedByDecor(t,e){const s=this.decorGroups.get(e);return s?this.bodySystem.maskedShare(t,s):void 0}setBodies(t,e=0,s=t.map(a=>a.id),i=[],n){this.lastBodies=[t,e,s,i,n];const{x:a,z:o}=this.bodyOrigin,r=this.scatteredSky,c=this.bodyEastScale;Math.abs(c-1)>1e-9&&(t=t.map(l=>({...l,eastM:l.eastM*c}))),this.bodySystem.set(t,{originX:a,originZ:o,originGroundY:this.groundYUnder(a,o),eye:this.camera.position,groundYAt:(l,d)=>this.groundYUnder(l,d),wind:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(l,d,f)=>this.transmittanceTo(l,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y),daylight:this.daylightOnBodies(),sunAloft:this.sunAloft()},e,r?Object.assign((l,d)=>r.relativeOfLuminance(l,d),{recorded:r.recorded}):void 0,s),this.bodySystem.setSmoke(i,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}daylightOnBodies(){const t=this.celestialLight.color,e=this.celestialLight.intensity,s=this.skyLight.color,i=this.skyLight.groundColor,n=this.skyLight.intensity;return{towardSun:this.lightDirection,sun:[t.r*e,t.g*e,t.b*e],round:[(s.r+i.r)/2*n,(s.g+i.g)/2*n,(s.b+i.b)/2*n],sky:[s.r*n,s.g*n,s.b*n],ground:[i.r*n,i.g*n,i.b*n]}}sunAloft(){const t=this.lastAstronomy?.sun;if(!t)return;const{x:e,y:s,z:i}=Vt(t.altitudeDeg,t.azimuthDeg,1),n=new D(e,s,i),a=At.illuminanceOf(t.magnitude)*this.relativeScale,o=Math.sin(t.altitudeDeg*Mt),r=Math.cos(t.altitudeDeg*Mt),c=Math.sin(t.azimuthDeg*Mt),h=Math.cos(t.azimuthDeg*Mt),l=this.sceneSunBeam;let d;return{towardSun:n,beamAt:(f,m,p)=>{const g=this.siteElevationM+Math.max(0,p),M=(c*f+h*m)/N.EARTH_RADIUS_M,v=Math.asin(Math.max(-1,Math.min(1,o+r*M)))/Mt,y=ms.litFraction(v,g);if(y<=0)return;const w=this.air.transmittanceFromSpace(g,v),b=g>=N.ABOVE_CLOUD_M?1:d??=this.cloudTransmission(t),E=[0,0,0];for(let A=0;A<3;A++)E[A]=Math.max(0,a*w[A]*y*b-l[A]);return E[0]>0||E[1]>0||E[2]>0?E:void 0}}}static EARTH_RADIUS_M=6371e3;plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,s=this.skyLight.color,i=this.skyLight.groundColor,n=this.skyLight.intensity,a=(o,r,c)=>(o*e+(r+c)/2*n)/Math.PI;return[a(t.r,s.r,i.r),a(t.g,s.g,i.g),a(t.b,s.b,i.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,s=this.modelUrl(t)??e?.url,i=t.credit??e?.credit;if(!(!s||!i))return{scene:await Qh(s),credit:i,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const s=this.loadedDecorModels.get(t.id);return!s||s.ref!==JSON.stringify(Bc(t))||!C.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,s),!0)}applyLoadedDecorModel(t,e,s){const i=Mp(s.scene);i.traverse(n=>{n instanceof B&&(n.userData.sharedModel=!0)}),C.applyModelParameters(i,t.modelParameters,s.bindings),C.applyModel(e,t,i,{headingOffsetDeg:s.headingOffsetDeg,depictedSizeM:s.depictedSizeM}),this.mirrors.adopt(i),this.decorModelCredits.set(t.id,s.credit)}mirrors=new Is;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,s=!1){const i=s?hg[t.kind]:Bc(t);if(!(!i||!C.usesModel(t)))try{const n=i.url?void 0:i.id?await this.decorModelProvider.entry(i.id):void 0,a=this.modelUrl(i)??n?.url,o=i.credit??n?.credit;if(!a||!o)return;const r=s||t.kind==="tree"?await this.standInScene(a):await Qh(a);if(e!==this.decorModelToken||s&&!this.pendingTrafficModels.has(t.id))return;const c=this.decorGroups.get(t.id);if(!c)return;!s&&t.kind!=="tree"&&(G.glaze(r),ds.reflectOn(r));const h={ref:JSON.stringify(i),scene:r,headingOffsetDeg:i.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:o,bindings:n?.parameters?.bindings};s||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,c,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${t.id}":`,n)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=Qh(t).then(s=>(/jungle-jim-realistic-trees/.test(t)||ds.reflectOn(s),s)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,s=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=s;const i=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?ot(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},n=this.decorObjects.find(m=>m.observerSide!==void 0&&Bo(m.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,n?0:this.gaitOffset.eastM,n?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),n||(i.x-=this.gaitOffset.eastM,i.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const a={x:0,z:0};let o=0,r;if(n){const m=wi(n,s),p=C.occupantView(n,m.headingDeg),g=-(m.headingDeg??0)*Mt,M=p.x*Math.cos(g)+p.z*Math.sin(g),v=-p.x*Math.sin(g)+p.z*Math.cos(g),y=m.eastM+i.x,w=-m.northM+i.z;a.x=-(y+M),a.z=-(w+v),this.camera.position.y=this.groundYUnder(y,w)+p.eyeY,r=p.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Mt,-(p.headingDeg+this.indoorLookYawDeg)*Mt,0,"YXZ")}this.bodyOrigin={x:i.x+a.x,z:i.z+a.z};const c=this.findCabin(s,i,a);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(s,i,a);const h=this.terraces.map(m=>[m.x,m.z,m.cos,m.sin,m.halfWidthM,m.halfLengthM,m.levelY].map(p=>p.toFixed(3)).join(",")).join(";");!n&&this.terraces.length>0&&(this.poseAltitudeM!==void 0&&(this.poseElevationM=Math.max(0,this.poseAltitudeM-this.siteElevationM-this.groundYUnder(0,0))),this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const m of this.decorObjects){if(m.kind==="terrace")continue;const p=this.decorGroups.get(m.id);if(!p)continue;const g=wi(m,s),M=this.lampNudges.get(m.id),v=g.eastM+(M?.eastM??0)+i.x+a.x,y=-(g.northM+(M?.northM??0))+i.z+a.z,w=this.terrainMesh,b=`${w?.geometry.uuid}:${(v-(w?.position.x??0)).toFixed(3)}:${(y-(w?.position.z??0)).toFixed(3)}:${(w?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(p.userData.footprintKey!==b){if(m.kind==="wire"){const O=C.wireGround(m,v,y,g.headingDeg,(P,k)=>this.groundYUnder(P,k));p.userData.footprintGroundY=O.startY,C.shearWire(p,C.sizeOf(m).lengthM,O.dropM)}else if(m.kind==="crossing"){const O=this.groundYUnder(v,y),P=-(g.headingDeg??0)*Mt,k=Math.cos(P),_=Math.sin(P);p.userData.footprintGroundY=O,ft.drape(C.bodyOf(p),(rt,lt)=>this.groundYUnder(v+rt*k+lt*_,y-rt*_+lt*k)-O)}else p.userData.footprintGroundY=this.groundUnderFootprint(m,v,y,g.headingDeg,g.altitudeM);p.userData.footprintKey=b}const A=g.altitudeM>N.AIRBORNE_M&&Math.hypot(v,y)<N.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseStatedElevationM:p.userData.footprintGroundY,S=m.id.startsWith(Nt.ID_PREFIX)?N.trafficHeight(g.altitudeM,p.userData.footprintGroundY):A+g.altitudeM;if(p.position.set(v,S,y),m.kind==="crop"){const O=Math.hypot(v,y);p.visible=O<=ky}const x=this.decorPresence.get(m.id),T=x!==void 0&&(s<x.fromMs||s>x.untilMs);x&&(p.visible=!T);const I=this.decorSunlight.get(m.id);I&&!T&&this.lightFromAbove(p,I),g.headingDeg!==void 0&&(p.rotation.y=-g.headingDeg*Mt);const R=lg(m,s);if(R!==void 0&&N.turnHead(p,g.headingDeg??0,R),m.kind==="crop"&&p.visible){const O=this.terrainMesh,P=[O?.geometry.uuid,v-(O?.position.x??0),y-(O?.position.z??0),p.position.y-(O?.position.y??0),g.headingDeg,g.altitudeM].map(k=>typeof k=="number"?k.toFixed(4):k).join(":");p.userData.cropGroundKey!==P&&(C.fitCropToGround(p,(k,_)=>this.groundYUnder(k,_)+g.altitudeM),p.userData.cropGroundKey=P)}if(!T){const O=p.position.distanceTo(this.camera.position);o=Math.max(o,O),O<N.trafficModelRangeM(m)&&this.pendingTrafficModels.delete(m.id)&&this.loadDecorModel(m,this.decorModelToken)}}if(n&&r!==void 0){const m=this.decorGroups.get(n.id);m&&(this.camera.position.y=m.position.y+r)}this.updateContrails(),this.updateSkyEvents();const l=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(vc*1.2,this.groundRadius*2.5,o*1.2,l*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const s=this.terrainYUnder(t,e);let i=s;for(const n of this.terraces){const a=t-n.x,o=e-n.z,r=a*n.cos-o*n.sin,c=a*n.sin+o*n.cos;if(Math.abs(r)<=n.halfWidthM&&Math.abs(c)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(r))/n.bankM)),l=h*h*(3-2*h);i=Math.max(i,l*n.levelY+(1-l)*Math.min(n.levelY,s))}}return i}placeTerraces(t,e,s){this.terraces=[];const i=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const a=this.decorGroups.get(n.id);if(!a)continue;const o=wi(n,t),r=o.eastM+e.x+s.x,c=-o.northM+e.z+s.z,h=C.sizeOf(n),l=-(o.headingDeg??0)*Mt,d=Math.cos(l),f=Math.sin(l),m=`${i?.geometry.uuid}:${(r-(i?.position.x??0)).toFixed(3)}:${(c-(i?.position.z??0)).toFixed(3)}:${(i?.position.y??0).toFixed(3)}:${o.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;a.position.set(r,0,c),o.headingDeg!==void 0&&(a.rotation.y=l),a.userData.terraceKey!==m&&(a.userData.terraceLevelY=C.fitTerrace(a,n,(p,g)=>this.terrainYUnder(r+p*d+g*f,c-p*f+g*d)),a.userData.terraceKey=m),this.terraces.push({x:r,z:c,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:a.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const s=this.terrainMesh;return s?s.position.y+this.groundYOfPatch(s,t-s.position.x,e-s.position.z):Al}horizonAltitudeDeg(t){const e=this.camera.position,s=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;s!==this.horizonFor&&(this.horizonFor=s,this.horizonByBearing.fill(Number.NaN));const i=this.horizonByBearing.length,n=Math.round((t%360+360)%360/(360/i))%i;let a=this.horizonByBearing[n];return Number.isNaN(a)&&(a=this.horizonByBearing[n]=this.marchHorizon(n*360/i)),a}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+N.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const s=this.camera.position,i=t*Math.PI/180,n=Math.sin(i),a=-Math.cos(i),o=this.farRing?.mesh,r=Math.max(this.terrainRadius,o?this.farRingRadiusM:0),c=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let l=c;l<=r;l=Math.max(l+c,l*1.02)){const d=s.x+n*l,f=s.z+a*l,m=l<=this.terrainRadius?this.terrainYUnder(d,f):o.position.y+this.groundYOfPatch(o,d-o.position.x,f-o.position.z);h=Math.max(h,Math.atan2(m-s.y,l))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,s){const i=t.geometry.getAttribute("position"),n=Math.round(Math.sqrt(i.count));if(n<2||n*n!==i.count)return Al;const a=i.getX(0),o=i.getX(n-1),r=i.getZ(0),c=i.getZ((n-1)*n),h=Oi((e-a)/(o-a)*(n-1),0,n-1),l=Oi((s-r)/(c-r)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(l))return Al;const d=Math.min(Math.floor(h),n-2),f=Math.min(Math.floor(l),n-2),m=h-d,p=l-f,g=(b,E)=>i.getY(b*n+E),M=g(f,d),v=g(f,d+1),y=g(f+1,d),w=g(f+1,d+1);return m+p<=1?M+(v-M)*m+(y-M)*p:w+(y-w)*(1-m)+(v-w)*(1-p)}groundUnderFootprint(t,e,s,i,n=0){return C.groundUnderFootprint(t,e,s,i,(a,o)=>this.groundYUnder(a,o),n)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;poseStatedElevationM=0;poseAltitudeM;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=Cs.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,s,i,n){const a=t&&e!==void 0&&e>0&&s!==void 0&&s>0?{kind:t.kind,iso:i??t.iso,autoExposure:t.autoExposure===!0&&i===void 0,maxIso:t.maxIso,metering:n??t.metering??"average",exposureSeconds:e,fNumber:s,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}:void 0;JSON.stringify(a)!==JSON.stringify(this.medium)&&(this.medium=a,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),s=t?Cs.NONE:this.perception??Cs.NONE;if(ne.uColorVision.value.set(...s.colorMatrix),ne.uContrast.value=s.contrastGain,!t){ne.uMedium.value=0;return}const i=t.kind==="sensor"&&t.development==="computational";ne.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:i?4:3;const n=t.autoExposure?this.frameLight:void 0,a=t.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,o=a===void 0?void 0:this.meteredBodies(),r=a===void 0?void 0:a+o.mean,c=d=>zn.middleGreys(1/e,t.exposureSeconds,d,t.fNumber,this.filterTransmittance);let h=r!==void 0&&r>0?1/(e*r):void 0;h!==void 0&&t.metering==="highlights"&&o.brightest>0&&(h=Math.min(h,N.HIGHLIGHT_KEPT_AT/(.18*e*o.brightest))),h!==void 0&&t.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,N.ZONE_KEPT_AT/(.18*e*n.brightest)));const l=h!==void 0?Math.min(h,t.maxIso!==void 0?c(t.maxIso):1/0):c(t.iso);ne.uMediumExposure.value=l,ne.uPhoneStrength.value=i&&r!==void 0&&r>0?fi.strengthFor(fi.MID_GREY*l*e*r):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,s=2*Math.atan(Math.tan(e/2)*t.aspect),i=4*Math.asin(Math.sin(s/2)*Math.sin(e/2)),n=new D;let a=0,o=0;for(const{position:r,luminanceCdM2:c,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(r).project(t),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(a+=c*h,o=Math.max(o,c*Math.min(1,h/(N.HIGHLIGHT_SHARE*i))**2));return{mean:a/i,brightest:o}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),s=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/s)}bloomSize=new ht;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,s=this.siteElevationM+t.position.y;return this.air.transmittance(e,s,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const s=this.lampBloomRadiusRad();for(const i of this.decorObjects){const n=this.decorGroups.get(i.id);if(n&&i.lights?.length&&C.setLights(n,i.lights,t,n.position.distanceTo(this.camera.position),e,this.relativeScale,s,this.lampTransmittance(n),this.camera.position),i.kind!=="streetlight"&&i.kind!=="vehicle")continue;const a=this.decorGroups.get(i.id);if(!a)continue;const o=i.kind==="vehicle"?om(i,t):void 0,r=o!==void 0?Hl.lamps(o):Lu(i,t,this.lastAstronomy?.sun.altitudeDeg);C.setLit(a,i.kind,r,this.relativeScale,i.lamp);const c=this.streetlightLights.get(i.id);c&&(c.visible=r),o!==void 0&&(this.headlightSettings.set(i.id,o),this.aimDecorBeam(i,a,o))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=H(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-D5-78PFB.js");return{HeadlightSystem:t}},__vite__mapDeps([43,4,7]),import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),s=this.decorGroups.get(t.id);e!==void 0&&s&&this.aimDecorBeam(t,s,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,s=this.air.transmittance(t,t,e)[1];return s>0?-Math.log(Math.min(1,s))/e:.05}aimDecorBeam(t,e,s){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const i=new D(0,0,-1).transformDirection(e.matrixWorld);if(i.y=0,i.lengthSq()<1e-9)return;i.normalize();const n=C.sizeOf(t).lengthM,a=e.getWorldPosition(new D).addScaledVector(i,n/2-by);a.y+=wy;const o=C.sizeOf(t).widthM;this.headlightSystem.aim(t.id,s,a,i,o*Ey,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?Hl.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,s=t.headingDeg*Math.PI/180,i=new D(Math.sin(s),0,-Math.cos(s)),n=new D(i.x*ef,this.camera.position.y-Sy,i.z*ef);this.headlightSystem.aim("observer",e,n,i,Ay,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,s,i){const n=C.bodyOf(e),a=n.children.find(c=>c.userData.emissive);if(!a)return;const o=tf*C.lampShare(i),r=new jf(16764006,o*this.relativeScale,xy);i?.colorTemperatureK&&r.color.setRGB(...C.lampHue(i)),r.userData.candela=o,r.position.copy(a.position).multiply(n.scale),r.castShadow=s,r.shadow.mapSize.set(512,512),r.shadow.bias=-.002,e.add(r),this.streetlightLights.set(t,r)}applyWindowGlow(){const t=this.lastAstronomy;C.setLitWindowShare(t?ts.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const s=a=>{const o=Ls.luminanceOf(a);if(!(o>0))return[0,0,0];const r=W.relativeOfResponse(o)/o;return[a[0]*r,a[1]*r,a[2]*r]},i=s(t.zenith),n=s(t.horizon);return{zenith:i,horizon:n,airlight:n,skyIrradiance:[i[0]*Math.PI,i[1]*Math.PI,i[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=be.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,J0,new q(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<Fc){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const s=J0/de*(180/Math.PI),i=s/e.sunRadiusDeg,n=Vt(t.sun.altitudeDeg,t.sun.azimuthDeg,1),a=Vt(t.moon.altitudeDeg,t.moon.azimuthDeg,1),o=Math.acos(Oi(n.x*a.x+n.y*a.y+n.z*a.z,-1,1)),r=o>1e-9?Oi(e.separationDeg*i*Mt/o,0,2):0,c=Math.sin(o),[h,l]=o>1e-9?[Math.sin((1-r)*o)/c,Math.sin(r*o)/c]:[1,0],d={x:n.x*h+a.x*l,y:n.y*h+a.y*l,z:n.z*h+a.z*l},f=e.moonRadiusDeg*i;this.eclipseDiscs={sun:new D(n.x,n.y,n.z).normalize(),moon:new D(d.x,d.y,d.z).normalize(),sunRadiusRad:s*Mt,moonRadiusRad:f*Mt};const m=.01,p=(v,y)=>Vt(t.sun.altitudeDeg+v,t.sun.azimuthDeg+y,1),g={x:p(m,0).x-p(-m,0).x,y:p(m,0).y-p(-m,0).y,z:p(m,0).z-p(-m,0).z},M={x:p(0,m).x-p(0,-m).x,y:p(0,m).y-p(0,-m).y,z:p(0,m).z-p(0,-m).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:i,up:g,right:M}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new So(s*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateSkyEvents());const e=this.scatteredSky?.ambient??N.relativeSkyOf(sh(t.sun.altitudeDeg),this.relativeScale),s=e,i=this.lightUnderClouds(t),n=a=>i?[0,1,2].map(o=>a[o]*i.through+i.radiance[o]*(1-i.through)):[a[0],a[1],a[2]];this.baseFogColor=[s.horizon[0],s.horizon[1],s.horizon[2]],this.airlight=n(s.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Z.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const a of this.streetlightLights.values())a.intensity=(a.userData.candela??tf)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,s.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const s=(this.hazeOpticalDepth()??$.DEFAULT_AEROSOL_OPTICAL_DEPTH)*$.aerosolDensity(this.siteElevationM+this.observerElevationM),i=this.cloudTransmission(t),n=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=At.aureoleScale(s,At.airMass(t.altitudeDeg))*i,o=At.coronaScale(n),r=At.illuminanceOf(t.magnitude),c=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),o.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(c===this.lunarDiffractionKey)return;this.lunarDiffractionKey=c,this.lunarDiffraction||(this.lunarDiffraction=new qu,this.celestialGroup.add(this.lunarDiffraction.object));const h=At.profile(At.HAZE_COARSE_MODE),l=At.profile(At.CLOUD_DROPLETS),d=rp(t.altitudeDeg),f=new Float32Array(At.STEPS*3);let m=0;for(let v=0;v<At.STEPS;v++){const y=v*3,w=[0,1,2].map(E=>r*d[E]*(a*h[y+E]+o*l[y+E])),b=Ls.shown(w,Ls.luminanceOf(w),(E,A)=>e.relativeOfLuminance(E,A));f.set(b,y),m=Math.max(m,Ls.response(b))}const{x:p,y:g,z:M}=Vt(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:p,y:g,z:M}:void 0,f)}applyAir(){this.scene.fog instanceof jn||(this.scene.fog=new jn),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,s){const i=this.camera.position;return this.air.transmittance(this.siteElevationM+i.y,this.siteElevationM+e,Math.hypot(t-i.x,e-i.y,s-i.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}hazeOpticalDepth(){return us.aerosolOpticalDepthOf(this.weather,this.siteElevationM)}restateHaze(){this.air=us.of(this.weather,this.siteElevationM),this.applyAir();const t=this.hazeOpticalDepth(),e=ya.OPTICAL_DEPTH_STEP;this.scatteredSky?.setConditions({aerosolOpticalDepth:t===void 0?void 0:Math.round(t/e)*e}),this.pumpScatteredSky()}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.weather.visibilityKm!==void 0&&this.restateHaze(),this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,s,i]=this.air.transmittance(t,t,N.UMBRA_PATH_M),n=.2126*e+.7152*s+.0722*i;return n>0?[(.4124*e+.3576*s+.1805*i)/n,1,(.0193*e+.1192*s+.9505*i)/n]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:be.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?be.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:U.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?Iy:Dy),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new IM(ml),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Er(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,s=>this.cloudTransmission(s),(s,i)=>this.arrivingIlluminance(s,i,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}decorSkyPoint(t){const e=this.decorGroups.get(t);if(!e?.visible)return;const s=new D().copy(e.position).sub(this.camera.position),i=s.length();if(i===0)return;const n=(Math.atan2(s.x,-s.z)*180/Math.PI+360)%360,a=Math.asin(s.y/i)*180/Math.PI;return{sky:{azimuthDeg:n,altitudeDeg:a,distanceKm:i/1e3},altitudeM:this.siteElevationM+e.position.y}}flightScreenPoint(t){const e=Nt.declaredIdOf(t);if(e!==void 0){const i=this.decorGroups.get(e);if(!i?.visible)return;const n=new D().copy(i.position).sub(this.camera.position),a=this.screenPointOf(n.clone().normalize());return a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY,n.length())?a:void 0}const s=`${Nt.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(s))continue;const a=this.screenPointOf(new D().copy(n.position).sub(this.camera.position).normalize());if(a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY))return a}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.direction,i=Math.cos(bc*this.camera.fov*Math.PI/180);let n,a=i;const o=new D;for(const[r,c]of this.decorGroups){if(!c.visible||!r.startsWith(Nt.ID_PREFIX))continue;o.copy(c.position).sub(this.camera.position).normalize();const h=o.dot(s);h>a&&(a=h,n=r)}return n&&!this.groundHides(t,e)?n:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=Math.cos(bc*this.camera.fov*Math.PI/180),i=this.satelliteField.nearest(this.raycaster.ray.direction,s);return i&&this.groundHides(t,e)?void 0:i}updateCelestialLight(t,e){const s=this.relativeScale,i=t.sun.altitudeDeg>=cr,n=!i&&t.moon.altitudeDeg>=cr,a=i?t.sun:t.moon,o=[0,0,0],r=Math.max(0,Math.sin(Math.max(a.altitudeDeg,0)*Mt)),c=this.siteElevationM+this.observerElevationM;let h=a,l=i||n?P0.directFraction(a.altitudeDeg,c):0;i&&l<=0&&t.moon.altitudeDeg>=cr&&(h=t.moon,l=P0.directFraction(h.altitudeDeg,c));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Mt)),f=i||n?this.cloudTransmission(a):1,m=-Math.log(Math.max(f,1e-6)),p=Math.max(0,1/(1+.1125*m)-f),g=[0,0,0];if(i||n){const E=At.illuminanceOf(a.magnitude)*s,A=this.air.transmittanceFromSpace(c,a.altitudeDeg);for(let I=0;I<3;I++)g[I]=E*A[I]*p*r,this.cloudBeam[I]=E*A[I];const{x:S,y:x,z:T}=Vt(a.altitudeDeg,a.azimuthDeg,1);if(this.cloudBeamDirection.set(S,x,T),l>0){const I=At.illuminanceOf(h.magnitude)*s,R=h===a?A:this.air.transmittanceFromSpace(c,h.altitudeDeg),O=h===a?f:this.cloudTransmission(h);for(let P=0;P<3;P++)o[P]=I*R[P]*O*l}}else this.cloudBeam.fill(0);const M=this.surroundings;if(M)this.skyLight.color.setRGB(M.up[0]*s,M.up[1]*s,M.up[2]*s),this.skyLight.groundColor.setRGB(M.down[0]*s,M.down[1]*s,M.down[2]*s);else{const E=this.skyCloudTransmission(),A=e.skyIrradiance,S=[0,1,2].map(T=>A[T]*E+g[T]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const x=J.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(x*(S[0]+o[0]*d),x*(S[1]+o[1]*d),x*(S[2]+o[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[o[0],o[1],o[2]]:[0,0,0],!i&&!n||l<=0){this.celestialLight.intensity=0;return}const{x:v,y,z:w}=Vt(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(v,y,w),this.celestialLight.shadow.normalBias=gl*Oi(y/dy,.1,1),this.placeShadowFrustum();const b=Math.max(o[0],o[1],o[2],1e-30);this.celestialLight.color.setRGB(o[0]/b,o[1]/b,o[2]/b),this.celestialLight.intensity=b,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const s=this.lastAstronomy?.sun,i=[0,0,0];if(s){const n=ms.litFraction(e.sunElevationDeg,e.heightM);if(n>0){const a=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),o=At.illuminanceOf(s.magnitude)*this.relativeScale,r=e.heightM>=N.ABOVE_CLOUD_M?1:this.cloudTransmission(s);for(let c=0;c<3;c++)i[c]=Math.max(0,o*a[c]*n*r-this.sceneSunBeam[c])}}t.traverse(n=>{const a=n.material;if(!(a instanceof ci||a instanceof un)||n.userData.emissive)return;a.map&&!a.emissiveMap&&(a.emissiveMap=a.map,a.needsUpdate=!0);const o=N.MEAN_COSINE/Math.PI;a.emissive.setRGB(a.color.r*i[0]*o,a.color.g*i[1]*o,a.color.b*i[2]*o)})}lightDirection=new D(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,s=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,i=this.shadowAxisX.crossVectors(this.shadowUp,t);i.lengthSq()<1e-8&&i.set(1,0,0),i.normalize();const n=this.shadowAxisY.crossVectors(t,i).normalize(),a=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),o=c=>{const h=a.dot(c)/s;return(h-Math.round(h))*s},r=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(i,o(i)).addScaledVector(n,o(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(r).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const s=e.camera,i=uy;s.left=-i,s.right=i,s.top=i,s.bottom=-i,this.shadowHalfExtentM=i,this.shadowLightDistanceM=Ec+5,s.near=this.shadowLightDistanceM-Ec,s.far=this.shadowLightDistanceM+Ec,s.updateProjectionMatrix(),e.bias=-.004/(2*Ec),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(s=>{const i=s.material;for(const n of Array.isArray(i)?i:i?[i]:[]){const a=n;a.isMeshStandardMaterial&&a.envMapIntensity!==N.CABIN_SKY_SHARE&&(a.envMapIntensity=N.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(ly,Math.max(sn,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const s=this.celestialLight.shadow,i=s.camera;i.left=-e,i.right=e,i.top=e,i.bottom=-e;const n=Math.max(ja,e*(ja/sn));this.shadowLightDistanceM=Math.max(de,n+10),i.near=this.shadowLightDistanceM-n,i.far=this.shadowLightDistanceM+n,i.updateProjectionMatrix(),s.bias=-pl/(2*n);const a=e>2*sn?2048:1024;s.mapSize.x!==a&&(s.mapSize.set(a,a),s.map?.dispose(),s.map=null),this.placeShadowFrustum()}shadowHalfExtentM=sn;shadowLightDistanceM=de;shadowUp=new D(0,1,0);shadowAxisX=new D;shadowAxisY=new D;shadowWorld=new D;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const s of[20,45,70]){const i=s*Mt,n=Math.sin(i)*Math.cos(i)*2;for(let a=0;a<360;a+=60)t+=n*this.cloudTransmission({altitudeDeg:s,azimuthDeg:a}),e+=n}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new D(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/W.semiSaturation(W.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,s){this.meteorSystem||(this.meteorSystem=new Ke,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,s)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const s=Math.max(this.relativeScale,1e-30),i=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:n,y:a,z:o}=Vt(t.altitudeDeg,t.azimuthDeg,1);return{direction:new D(n,a,o),lux:[i[0]/s,i[1]/s,i[2]/s],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const s=je.starPointsOf(t,e);s!==this.starPoints&&(this.starPoints=s,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=s),this.render())}magnitudeLimitOf(t){const e=U.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:U.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return Er(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor))}setInstrumentGain(t,e=!1,s=0){const i=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=i-2.5*s,this.filterTransmittance=10**-s,this.scatteredSky?.setInstrument(e,i,s)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.references?.release(),this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,s=performance.now()+N.COMPILE_WAIT_MS;return new Promise(i=>{const n=()=>{if(this.contextReleased)return i();for(const a of t){const o=e.get(a)?.currentProgram;(!o||o.isReady())&&t.delete(a)}t.size===0||performance.now()>s?i():setTimeout(n,10)};n()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.scatteredSky?.invalidate(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;if(this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e),!this.pixelRatioHeld){const s=this.resolution.ratioFor(t,e);s!==this.renderer.getPixelRatio()&&this.applyPixelRatio(s)}}this.drawIfDirty()}get maxPixelRatio(){return this.resolution.maximum}pixelRatioHeld=!1;holdPixelRatio(t){this.pixelRatioHeld=t!==void 0;const e=t??this.resolution.maximum;this.renderer.getPixelRatio()!==e&&this.applyPixelRatio(e)}async controlFrame(){await this.loadControlPasses(),this.render();const t=this.drawn;return this.drawIfDirty(),this.drawn===t?void 0:{image:this.renderer.domElement.toDataURL("image/png"),...this.drawControlPasses()}}async loadControlPasses(){if(this.controlPasses)return;const{ControlPasses:t}=await H(async()=>{const{ControlPasses:e}=await import("./ControlPasses-BpLNDq5G.js");return{ControlPasses:e}},__vite__mapDeps([44,4,1,2,3,5,6,7,8,9,10]),import.meta.url);this.controlPasses??=new t}drawControlPasses(){if(!this.controlPasses)throw new Error("The control passes are not loaded: see loadControlPasses");return this.controlPasses.draw({renderer:this.renderer,scene:this.scene,camera:this.camera,equidistant:this.usableEquidistantPass(),sky:[this.celestialGroup,...this.pointLayerHost.clouds(),...this.lensFlare?[this.lensFlare.mesh]:[]],isSolid:t=>N.isSolidSurface(t),drawPhenomena:t=>this.renderPhenomenaPass(t)})}controlPasses;cabinDecor(){return this.cabinGroups}enclosingDecor(){const t=this.camera.getWorldPosition(this.enclosingEye);return this.decorObjects.filter(e=>e.kind==="aircraft"||e.kind==="vehicle").map(e=>this.decorGroups.get(e.id)).filter(e=>e!==void 0&&this.enclosingBox.setFromObject(e).containsPoint(t))}enclosingEye=new D;enclosingBox=new ee;cabinGroups=[];findCabin(t,e,s){const i=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&Bo(n.kind))continue;const a=this.decorGroups.get(n.id);if(!a)continue;const o=wi(n,t),r=o.eastM+e.x+s.x,c=-o.northM+e.z+s.z,h=C.sizeOf(n),l=Math.max(h.widthM,h.lengthM)/2;Math.hypot(r,c)<l&&Math.abs(o.altitudeM-this.poseStatedElevationM-1.6)<l&&i.push(a)}return this.cabinGroups=i,i}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new ds(this.renderer);const e=["sun","moon"].flatMap(c=>this.bodyMeshes.get(c)??[]),s=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...e,...[...this.glareSprites.values()].map(c=>c.mesh),...this.bodySystem.group.children.filter(c=>c.name.startsWith("body-speck:"))],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof Us),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.enclosingDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object].filter(c=>c!==void 0),...[...this.skyEventLayers.values()].filter(c=>c.simulation?.hiddenFromEye).map(c=>c.simulation.object)],n=this.relativeScale,a=this.sceneVersion,o=this.recordingTimeMs,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,s,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],a,i,c=>this.measureSurroundings(c,n,a,o),t?0:ds.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}static adaptingLuminance(t,e){const s=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,N.GROUND_ADAPTATION_SHARE*s)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,s,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new yo,this.framePhotograph={texture:t,scale:e,atMs:i};const a=[n.sun,n.moon].filter(o=>o.altitudeDeg>-2).map(o=>Vt(o.altitudeDeg,o.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,a,o=>{const r=m=>m.map(p=>p/e);if(![...o.up,...o.down,o.logAverage].every(Number.isFinite)){this.eyeSettledVersion=s,this.skyHoldUntilMs&&this.redrawHeld();return}const c=this.surroundings,h={up:r(o.up),down:r(o.down)},l=(m,p)=>m.some((g,M)=>Math.abs(g-p[M])>.03*Math.max(Math.abs(g),Math.abs(p[M]),1e-12)),d=!c||l(c.up,h.up)||l(c.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(N.adaptingLuminance(Math.exp(o.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=s,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const s=t.sun.altitudeDeg>=cr?t.sun:t.moon.altitudeDeg>=cr?t.moon:void 0;if(!s)return;const i=this.relativeScale/Math.PI;return{through:this.cloudTransmission(s),radiance:[e.up[0]*i,e.up[1]*i,e.up[2]*i]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new di;const e=this.lastAstronomy?.sun,s=e&&e.altitudeDeg>-2?Vt(e.altitudeDeg,e.azimuthDeg,1):void 0,i=this.medium.exposureFollowMs??N.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,s,n=>{const a={mean:n.mean/t.scale,brightest:n.brightest/t.scale};if(!Number.isFinite(a.mean)||!Number.isFinite(a.brightest))return;const o=this.frameLight,r=t.atMs,c=o?r-o.atMs:1/0,h=c<0||c>N.EXPOSURE_JUMP_MS,l=h||c===0&&o?.jumped?1:1-Math.exp(-c/i),d=(p,g)=>p>0&&g>0?p*(g/p)**l:g,f={mean:d(o?.mean??0,a.mean),brightest:d(o?.brightest??0,a.brightest),atMs:r,jumped:h||c===0&&(o?.jumped??!1)};this.frameLight=f;const m=(p,g)=>Math.abs(p-g)>.01*Math.max(p,g);(!o||m(o.mean,f.mean)||m(o.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(ne.uRetinaOn.value=0,this.medium)return;const t=[];for(const o of this.emitterLights.farEmitters){const r=this.screenPointOf(o.direction);!r||Math.abs(r.ndcX)>1.2||Math.abs(r.ndcY)>1.2||t.push({ndcX:r.ndcX,ndcY:r.ndcY,lux:Ls.luminanceOf(o.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),s=e.x/Math.max(e.y,1),i={width:this.camera.fov*s,height:this.camera.fov},n=this.retina?.atMs;if((n===void 0||this.recordingTimeMs<n||this.recordingTimeMs-n>et.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new et,this.retina.replay(0,this.recordingTimeMs,o=>this.historicBleachingAt(o,s),i,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new et,this.retina.advance(this.recordingTimeMs,t,i)}this.retina.any&&(ne.uRetina.value=this.retina.texture,ne.uRetinaOn.value=1,ne.uRetinaViewport.value.copy(e))}retinaSize=new ht;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const s=this.retinaHistory?.(t);if(!s||s.views.length===0)return[];const i=s.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((i?.pitchDeg??0)*Mt,-(i?.headingDeg??0)*Mt,(i?.rollDeg??0)*Mt,"YXZ")).invert(),a=i?.fovDeg??this.camera.fov,o=[];for(const r of s.views){const c=this.farEmitterOf(r.head,r.magnitude);if(!c)continue;const h=this.screenPointIn(this.historicDirection.copy(c.direction).applyQuaternion(n),a,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||o.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:Ls.luminanceOf(c.lux)})}return o}historicQuaternion=new Oa;historicEuler=new $f;historicDirection=new D;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<N.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const s of t)s.traverse(i=>{i.userData.emissive===!0&&e.push(i)});return e}surroundings;animate(t,e){const s=Math.min(e/1e3,Ky);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,s),this.updateRain(s),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const s=e?Math.max(1,Math.round(t)):1;if(s===this.exposureInstants&&(s===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=s,this.exposureInstantAt=e,s===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),C.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const a=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...a):this.onMapSubjectBounds(a)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(a,o,r)=>this.directionAtScreenPoint(a,o,r),a=>this.screenPointOf(a)),this.references?.place(this.camera);const s=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;s>this.camera.far&&(this.camera.far=s,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[yu]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Is.INTERVAL_MS)),ne.uRodShare.value=this.scatteredSky?.rodShare??0,ne.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina(),this.waterSystem?.reflectBodies(this.renderer,this.scene,this.camera,vu,this.bodySystem.any,e&&Zt.supports(this.camera.fov,this.camera.aspect)?e.sourceFovDeg(this.camera.fov,this.camera.aspect):void 0);const i=!!this.references?.any||this.phenomena.any||this.compassSprites.some(a=>a.visible);ne.uHasOverlay.value=i?1:0;const n=i?a=>this.renderOverlayPasses(a):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const a=this.usableDepthOfFieldPass();a?a.render(this.renderer,this.scene,this.camera,n,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,a=>{this.lensFlare&&(this.lensFlare.mesh.visible=a?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Us&&e.userData.pointSource||e instanceof B&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(n=>n.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const s=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(dl),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=s,this.renderer.shadowMap.autoUpdate=i}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(vu),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=s}bodyCutOutMaterial=new $s({blending:Fo,blendSrc:gn,blendDst:gn,blendSrcAlpha:gn,blendDstAlpha:gn,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=s}setReferences(t,e){const s=t.map(i=>{const n=this.documentRelative(i.src);return n===i.src?i:{...i,src:n}});if(this.references){this.references.set(s,void 0,e);return}if(s.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:s,observerAt:e},this.referencesLoading??=H(async()=>{const{ReferenceSystem:i}=await import("./ReferenceSystem-Cv556rkv.js");return{ReferenceSystem:i}},__vite__mapDeps([45,4,46,6,47,1,2,3,5,7,8,9,10]),import.meta.url).then(({ReferenceSystem:i})=>{const n=new i(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=n,n.onFrame=()=>this.render(),this.referenceClock&&n.setTime(this.referenceClock);for(const[o,r]of this.referenceViews)n.setView(o,r);n.setShown(this.referencesShown);const a=this.pendingReferences;return this.pendingReferences=void 0,a&&n.set(a.references,void 0,a.observerAt),this.render(),n})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new D)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}get areReferencesShown(){return this.referencesShown}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const s=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const n=e?this.narrowTo(t,e):t,a=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),o=this.phenomena.furthestM;let r=0;for(const c of this.decorObjects){const h=this.decorGroups.get(c.id);if(!h)continue;const l=c.kind!=="crop"&&this.mayHide(h,t,a,o);N.markDecorDepth(h,l),l&&r++}r>0&&(t.layers.set(ul),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(yu),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=s,this.renderer.shadowMap.autoUpdate=i}phenomenaFrustum=new eg;phenomenaViewProjection=new Oe;occluderSphere=new zl;occluderEye=new D;localBounds=new WeakMap;mayHide(t,e,s,i){let n=0;t.traverse(()=>n++);let a=this.localBounds.get(t);if(!a||a.objects!==n){t.updateMatrixWorld(!0);const r=new ee().setFromObject(t);if(r.isEmpty())return!1;a={sphere:r.getBoundingSphere(new zl).applyMatrix4(new Oe().copy(t.matrixWorld).invert()),objects:n},this.localBounds.set(t,a)}const o=this.occluderSphere.copy(a.sphere).applyMatrix4(t.matrixWorld);return o.center.distanceTo(e.getWorldPosition(this.occluderEye))-o.radius>i?!1:s.intersectsSphere(o)}narrowTo(t,e){const s=this.renderer.getDrawingBufferSize(new ht),i=N.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*s.x-i)),a=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*s.y-i)),o=Math.min(s.x,Math.ceil((Math.min(1,e.x1)+1)/2*s.x+i)),r=Math.min(s.y,Math.ceil((Math.min(1,e.y1)+1)/2*s.y+i)),c=this.narrowCamera.copy(t);return t.getWorldPosition(c.position),t.getWorldQuaternion(c.quaternion),c.setViewOffset(s.x,s.y,n,s.y-r,Math.max(1,o-n),Math.max(1,r-a)),c.updateMatrixWorld(),c}narrowCamera=new Gc;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new $s({colorWrite:!1,side:tn});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,s){const i=t.getObjectByName("head");if(!i)return;const n=((s-e)%360+540)%360-180,a=Math.max(-85,Math.min(N.HEAD_TURN_LIMIT_DEG,n));i.rotation.y=-a*Mt}static isSolidSurface(t){if(!(t instanceof B))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==rs}static markDecorDepth(t,e){t.traverse(s=>{if(!(s instanceof B))return;e&&N.isSolidSurface(s)?s.layers.enable(ul):s.layers.disable(ul)})}startExposure(){this.cancelExposure(),this.references?.hold(this.camera),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new ht),e=Math.max(1,Math.round(t.x)),s=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new D2(e,s)),this.exposureAccumulation.resize(e,s),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const s=1/this.exposureInstants;this.resolution.beginDrawing();const i=performance.now()+N.EXPOSURE_BUDGET_MS,n=N.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let a=0;do{this.restateAt(t,this.exposureInstantsDone);const o=this.compassSprites.map(r=>r.visible);for(const r of this.compassSprites)r.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((r,c)=>{r.visible=o[c]})}e.add(this.renderer,s),this.exposureInstantsDone++,a++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<i&&a<n);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){ne.uRodShare.value=this.scatteredSky?.rodShare??0,ne.uHasOverlay.value=1,ne.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(o=>o.visible))return;const s=new js,i=new Ji(-1,1,1,-1,0,2),n=Sc/(nf*Math.tan(af*Mt/2));for(const o of this.compassSprites){if(!o.visible)continue;const r=o.getWorldPosition(new D).sub(this.camera.position).normalize(),c=this.screenPointOf(r);if(!c)continue;const h=new to(o.material);h.position.set(c.ndcX,c.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),s.add(h)}const a=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(s,i)}finally{this.renderer.autoClear=a}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new ee,s=new D,i=this.camera.getWorldDirection(new D),n=this.decorObjects.filter(o=>o.track?.length||o.kind==="aircraft"||o.kind==="vehicle").map(o=>this.decorGroups.get(o.id)),a=this.bodySystem.reflectors.map(o=>o.holder);for(const o of[...n,...a]){if(!o?.visible||(e.setFromObject(o),e.isEmpty())||e.distanceToPoint(this.camera.position)<N.MAP_SUBJECT_NEAREST_M)continue;let r=1/0,c=-1/0,h=1/0,l=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const m of[e.min.z,e.max.z]){if(s.set(d,f,m).sub(this.camera.position).normalize(),s.dot(i)<=0)continue;const p=this.screenPointOf(s);if(!p)continue;const g=(p.ndcX+1)/2,M=(1-p.ndcY)/2;r=Math.min(r,g),c=Math.max(c,g),h=Math.min(h,M),l=Math.max(l,M)}r=Math.max(r,0),c=Math.min(c,1),h=Math.max(h,0),l=Math.min(l,1),c>=r&&l>=h&&t.push({x:r,y:h,width:c-r,height:l-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}eyeOptics(){if(!this.eyeAsLens)return;const t=Math.max(1e-6,this.scatteredSky?.sceneAdaptation??1e3),e=4.9-3*Math.tanh(.4*Math.log10(t)),s=N.EYE_FOCAL_MM;return{focalLengthMm:s,fNumber:s/e,focusDistance:0,frameHeightMm:2*s*Math.tan(this.camera.fov*Mt/2)}}static EYE_FOCAL_MM=17;static EYE_LENS_MAX_FOV_DEG=20;get eyeAsLens(){return this.projectionKind==="equidistant"&&!this.lensOptics&&this.camera.fov<=N.EYE_LENS_MAX_FOV_DEG}usableDepthOfFieldPass(){const t=this.lensOptics??this.eyeOptics();if(!t)return;const e=this.renderer.getDrawingBufferSize(new ht),s=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new wo(s,i)),this.depthOfFieldPass.resize(s,i),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass.setAir(this.weather.visibilityKm!==void 0?this.weather.visibilityKm*1e3:void 0,this.camera.fov),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(t,e){return this.ghostPass?.holdsPictureAt(this.renderer,t,e)??!1}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,ne.uMediumExposure.value,this.sunBeyondPicture())}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new ht);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Qt(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new ht);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new Xu(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant"||this.eyeAsLens)return;const t=this.renderer.getDrawingBufferSize(new ht);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Zt(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,s){this.aimStraightAtScreenPoint(t,e,s),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,i=>{const n=N.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=i-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(t,e,s){const i=this.projectionKind==="equidistant"&&!this.eyeAsLens?this.equidistantPass:void 0;if(!i){t.setFromCamera(new ht(e,s),this.camera);return}const n=i.directionFor(e,s,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(n.x,n.y,n.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new D)}directionAtScreenPoint(t,e,s){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),s.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),s=this.renderer.getDrawingBufferSize(this.screenPointSize),i=s.x/Math.max(s.y,1);return this.screenPointIn(e,this.camera.fov,i)}screenPointIn(t,e,s){if(this.projectionKind==="equidistant"&&!this.eyeAsLens&&this.equidistantPass)return Zt.ndcFor(t,e,s);if(t.z>=0)return;const i=Math.tan(e/2*Mt);return{ndcX:t.x/-t.z/(s*i),ndcY:t.y/-t.z/i}}screenPointScratch=new D;screenPointQuaternion=new Oa;screenPointSize=new ht;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const s=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(s.x,s.y);const i=this.renderer.domElement.width,n=this.renderer.domElement.height;t.uniforms.uResolution.value.set(i,n),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const t=this.lensFlare;if(!t||!t.mesh.visible)return;const e=this.sunDiscRadiance.map(c=>Math.max(0,c-N.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const s=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,i=Math.PI*s*s,n=t.uniforms.uLensPosition.value,a=t.uniforms.uTanHalfFov.value,o=this.camera.aspect,r=wt.offFrameShare(Math.atan(Math.hypot(n.x*o,n.y)*a)*180/Math.PI,Math.atan(Math.hypot(o,1)*a)*180/Math.PI,this.ghostOptics.reachDeg);if(!(r<=0))return{x:n.x,y:n.y,radius:s,flux:[e[0]*i*r,e[1]*i*r,e[2]*i*r]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const s=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!s)return;const i=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(s.ndcX,s.ndcY),t.uniforms.uResolution.value.set(i.x,i.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(j0),this.camera.layers.set(j0),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of cf)this.isSunOccluded(e[0],e[1])||t++;return t/cf.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const s=this.decorGroups.get(e.id);s&&t.push(s)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,s=0){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),a=n.length();if(n.normalize(),e!==0||s!==0){const c=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const l=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,e*c).addScaledVector(l,s*c).normalize()}if(this.groundBlocks(this.camera.position,n,a)||this.cabinMask.hides(n))return!0;const o=this.cabinMask.any?i.filter(c=>!this.cabinGroups.includes(c)):i;if(o.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(o,!0).find(c=>!(c.object.material instanceof ps));return r!==void 0&&r.distance<a}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const s=e.mesh.getWorldPosition(this.veilTargetScratch),i=e.mesh.material.uniforms.uSourceDeg.value,n=i>.05?N.VEIL_SAMPLES:N.VEIL_SAMPLES.slice(0,1);let a=0;for(const[o,r]of n)this.isOccludedToward(s,o*i,r*i)||a++;e.share=a/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new Ts;veilTargetScratch=new D;groundBlocks(t,e,s,i=0){const n=this.groundMesh;if(n&&e.y<0){const g=(n.position.y-t.y)/e.y;if(g>i&&g<s){const M=t.x+e.x*g-n.position.x,v=t.z+e.z*g-n.position.z;if(Math.hypot(M,v)<=this.groundRadius)return!0}}const a=this.terrainMesh;if(!a)return!1;const o=a.geometry.getAttribute("position"),r=Math.round(Math.sqrt(o.count));if(r<2||r*r!==o.count)return!1;const c=[a.position.x+o.getX(0),a.position.x+o.getX(r-1)],h=[a.position.z+o.getZ(0),a.position.z+o.getZ((r-1)*r)],l=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(r-1);if(!(l>0))return!1;let d=i,f=s;for(const[g,M,v]of[[t.x,e.x,c],[t.z,e.z,h]]){const y=Math.min(v[0],v[1]),w=Math.max(v[0],v[1]);if(Math.abs(M)<1e-12){if(g<y||g>w)return!1;continue}const b=(y-g)/M,E=(w-g)/M;d=Math.max(d,Math.min(b,E)),f=Math.min(f,Math.max(b,E))}if(!(f>d))return!1;const m=Math.hypot(e.x,e.z),p=Math.min(4096,Math.max(8,Math.ceil((f-d)*m/(l/2))));for(let g=0;g<=p;g++){const M=d+(f-d)*g/p,v=t.x+e.x*M,y=t.y+e.y*M,w=t.z+e.z*M;if(y<=this.groundYUnder(v,w))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,s){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=yc;let i,n;for(const a of this.decorObjects){if(a.kind==="crop")continue;const o=this.decorGroups.get(a.id);if(!o)continue;const r=this.ufoOcclusionRaycaster.intersectObject(o,!0).find(c=>N.isSolidSurface(c.object));r&&(a.occludesSourceIds?.includes(s)?i=i===void 0?r.distance:Math.max(i,r.distance):n=n===void 0?r.distance:Math.min(n,r.distance))}return{behindM:i,inFrontM:n}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.origin,i=this.raycaster.ray.direction,n=fy*this.camera.fov*Math.PI/180,a=[...this.hitAreas.entries()].map(([h,l])=>{const d=l.getWorldPosition(new D).sub(s);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(l.scale.x/2,d.length())}}),o=this.eclipseDiscs,r=o?[{key:"sun",direction:o.sun,radiusRad:o.sunRadiusRad},{key:"moon",direction:o.moon,radiusRad:o.moonRadiusRad,inFront:!0}]:[],c=N.nearestBody(i,[...a.filter(h=>!o||h.key!=="sun"&&h.key!=="moon"),...r],n);if(c)return this.groundHides(t,e)?void 0:c}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.iceHalos.featureAt(this.raycaster.ray.direction);return s&&!this.groundHides(t,e)?s:void 0}static nearestBody(t,e,s){let i,n=1/0,a=1/0,o=!1;for(const r of e){const c=Math.acos(Oi(r.direction.dot(t),-1,1))-r.radiusRad;if(c>s)continue;const h=c<=0,l=n<=0,d=r.inFront===!0;(h!==l?h:h?d!==o?d:r.radiusRad<a:c<n)&&(i=r.key,n=c,a=r.radiusRad,o=d)}return i}pickInterpretationBodyAt(t,e){const s=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(s.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=this.raycaster.ray.origin,a=hy*this.camera.fov*Math.PI/180,o=[...this.decorGroups.values()],r=o.length>0?N.firstSolid(this.raycaster.intersectObjects(o,!0))?.distance:void 0;let c,h=1/0;const l=new ee,d=new D;for(const f of s){if(l.setFromObject(f),l.isEmpty())continue;l.getCenter(d);const m=l.getSize(new D).length()/2,p=d.clone().sub(n),g=p.length();if(g===0||p.dot(i)<=0||r!==void 0&&r<g-m)continue;const M=Math.acos(Math.min(1,p.normalize().dot(i))),v=Math.atan(m/g);if(v>a){const y=this.raycaster.intersectObject(f,!0)[0];if(!y||r!==void 0&&r<y.distance)continue}else if(M>a)continue;v<h&&(h=v,c=f.name.slice(5))}return c}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.direction,i=Math.cos(bc*this.camera.fov*Math.PI/180);let n,a=i;for(const o of this.namedStars){const r=o.direction.dot(s);r>a&&(a=r,n={star:o.star,altitudeDeg:o.altitudeDeg})}return n&&this.groundHides(t,e)?void 0:n}groundHides(t,e,s=1/0){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,s,yc)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let s=1/0,i=1/0,n=-1/0,a=-1/0;for(let o=0;o<8;o++){const r=this.bodyCornerScratch.set(o&1?e.max.x:e.min.x,o&2?e.max.y:e.min.y,o&4?e.max.z:e.min.z),c=this.screenPointOf(r.sub(this.camera.position).normalize());if(!c)return;s=Math.min(s,c.ndcX),n=Math.max(n,c.ndcX),i=Math.min(i,c.ndcY),a=Math.max(a,c.ndcY)}return{minX:s,minY:i,maxX:n,maxY:a}}bodyBoxScratch=new ee;bodyCornerScratch=new D;decorFrameScratch=new Oe;decorPartMatrix=new Oe;decorPartScratch=new ee;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const s=this.decorFrameScratch.copy(e.matrixWorld).invert(),i=this.bodyBoxScratch.makeEmpty();if(e.traverse(c=>{const h=c.geometry;!h||!c.visible||(h.boundingBox||h.computeBoundingBox(),h.boundingBox&&i.union(this.decorPartScratch.copy(h.boundingBox).applyMatrix4(this.decorPartMatrix.multiplyMatrices(s,c.matrixWorld))))}),i.isEmpty())return;let n=1/0,a=1/0,o=-1/0,r=-1/0;for(let c=0;c<8;c++){const h=this.bodyCornerScratch.set(c&1?i.max.x:i.min.x,c&2?i.max.y:i.min.y,c&4?i.max.z:i.min.z).applyMatrix4(e.matrixWorld),l=this.screenPointOf(h.sub(this.camera.position).normalize());if(!l)return;n=Math.min(n,l.ndcX),o=Math.max(o,l.ndcX),a=Math.min(a,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:n,minY:a,maxX:o,maxY:r}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,s,i=0){const n=this.decorGroups.get(t);if(!n)return;this.aimAtScreenPoint(this.raycaster,e,s);const a=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+i)),this.decorHitScratch);return a?{x:a.x,z:a.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Mt/2):0}decorGrabHeightAt(t,e,s){const i=this.decorGroups.get(t);if(!i)return 0;const n=this.bodyBoxScratch.setFromObject(i).max.y-i.position.y;this.aimAtScreenPoint(this.raycaster,e,s);const a=this.decorHitScratch.set(this.camera.position.x-i.position.x,0,this.camera.position.z-i.position.z);if(a.lengthSq()<1e-6)return 0;a.normalize();const o=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(a,i.position),r=this.raycaster.ray.intersectPlane(o,this.decorHitScratch);return r?Math.min(Math.max(r.y-i.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new yh;decorHitScratch=new D;static firstSolid(t){return t.find(e=>{const s=e.object.material;return!(Array.isArray(s)?s:[s]).some(n=>n&&(n.transparent&&n.opacity<N.SEE_THROUGH_BELOW||n instanceof ps))})}static SEE_THROUGH_BELOW=.9;pickPeakAt(t,e){const s=this.renderer.getDrawingBufferSize(new ht),i=this.camera.fov*Mt/Math.max(1,s.y),n=this.camera.getWorldPosition(new D);let a;for(const o of this.decorObjects){if(o.kind!=="peak")continue;const r=this.decorGroups.get(o.id);if(!r)continue;const c=r.getWorldPosition(new D);c.y=this.reliefYAt(c.x,c.z);const h=c.distanceTo(n),l=this.screenPointOf(c.clone().sub(n).normalize());if(!l)continue;const d=(t-l.ndcX)*s.x/2,f=(l.ndcY-e)*s.y/2,m=Math.max(10,(o.sizeM?.widthM??2e3)/2/Math.max(h,1)/i);if(f<-8||f>m*.6)continue;const p=m*Math.max(.15,f/(m*.6));if(Math.abs(d)>Math.max(10,p))continue;const g=Math.abs(d)+Math.abs(f);(!a||g<a.score)&&(a={id:o.id,score:g})}return a?.id}reliefYAt(t,e){const s=this.terrainMesh;if(s&&Math.hypot(t-s.position.x,e-s.position.z)<=this.terrainRadius)return this.terrainYUnder(t,e);const i=this.farRing?.mesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):0}pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const s=[...this.decorGroups.entries()],i=N.firstSolid(this.raycaster.intersectObjects(s.map(([,o])=>o),!0));if(!i)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<i.distance)return;let a=i.object;for(;a&&!s.some(([,o])=>o===a);)a=a.parent;return s.find(([,o])=>o===a)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const s=this.railwaySystem;if(!s||s.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray;s.group.updateMatrixWorld();const n=new sm().copy(i).applyMatrix4(new Oe().copy(s.group.matrixWorld).invert()),a=s.group.matrixWorld,o=(d,f)=>{const m=new D(d,0,f).applyMatrix4(a);return this.groundYUnder(m.x,m.z)-a.elements[13]};if(!s.mayMeet(n.origin,n.direction,o,N.RAILWAY_PICK_ABOVE_M))return;const r=N.firstSolid(this.raycaster.intersectObject(s.group,!0));if(!r||this.terrainMesh&&this.groundBlocks(i.origin,i.direction,r.distance-N.RAILWAY_GROUND_MARGIN_M,yc))return;const c=s.group.worldToLocal(r.point.clone()),h=s.lineAt(c.x,c.z);if(!h)return;const l=s.contactHeightM(h);return{line:h,distanceM:r.distance,...l!==void 0?{contactM:l}:{}}}pickSkyEventAt(t,e,s=()=>!0){const i=[...this.skyEventLayers.values()].filter(c=>c.simulation?.pick&&c.simulation.drawnCount>0&&s(c.kind,c.simulation));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,a={toleranceRad:N.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(bc*this.camera.fov*Math.PI/180),skyLightTowards:c=>this.skyLightTowards(c)};let o;for(const c of i){const h=c.simulation.pick(n.origin,n.direction,a);h&&(!o||(h.distanceM??1/0)<(o.distanceM??1/0))&&(o={kind:c.kind.key,...h})}if(!o)return;if(o.distanceM===void 0)return this.groundHides(t,e)?void 0:o;if(this.terrainMesh&&this.groundBlocks(n.origin,n.direction,o.distanceM-1,yc))return;const r=N.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<o.distanceM))return o}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const s=a=>.2126*a[0]+.7152*a[1]+.0722*a[2],i=Math.hypot(t.x,t.y,t.z)||1,n=Math.max(0,Math.min(1,t.y/i));return s(e.horizon)+(s(e.zenith)-s(e.horizon))*Math.sqrt(n)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const t of this.skyEventLayers.values())t.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())C.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const s=t&&e;if(t===this.animationsRunning&&s===this.framesDriven)return;const i=this.animationsRunning;this.animationsRunning=t,this.framesDriven=s,t&&!i&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),n&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new D;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<N.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new Ge(vc,32,16),s=e.attributes.position,i=e.getAttribute("color")??new qe(new Float32Array(s.count*3),3);for(let a=0;a<s.count;a++){const{altitudeDeg:o,azimuthDeg:r}=$u(s.getX(a),s.getY(a),s.getZ(a)),c=ap(o,r,t.azimuthDeg,t.altitudeDeg);i.setXYZ(a,c[0],c[1],c[2])}if(i.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",i);const n=new $s({vertexColors:!0,side:Ai,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new B(e,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=Z0(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new sg(this.groundRadius,48),s=new ci({color:new q(fl,fl,fl),fog:!0});jn.fadeRim(s,this.groundRadius*.75,this.groundRadius),this.groundMesh=new B(e,s),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const s=this.terrainMesh;let i=0;if(s){const a=s.geometry.getAttribute("position");i=1/0;for(let o=0;o<a.count;o++)Math.abs(a.getX(o)+s.position.x)>600||Math.abs(a.getZ(o)+s.position.z)>600||(i=Math.min(i,a.getY(o)+s.position.y));i=Number.isFinite(i)?Math.min(0,i)-1:0}const n=this.farRing?.mesh;if(n){const a=n.geometry.getAttribute("position");let o=1/0;for(let r=0;r<a.count;r++)Math.hypot(a.getX(r)+n.position.x,a.getZ(r)+n.position.z)>this.groundRadius||(o=Math.min(o,a.getY(r)+n.position.y));Number.isFinite(o)&&(i=Math.min(i,o-1))}this.groundMesh.position.y=i,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const s=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([a,o])=>`${a}=${Math.round(o.x/10)},${Math.round(o.z/10)}`).join(";")+(e?":water":""),i=this.cloudTransmissionMemo.get(s);if(i!==void 0)return i;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(s,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const s=Vt(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(s,e);let i=1;const n=this.lowerCloudCover();n>0&&(i*=1-bt.alphaAt(s,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*gy);const a=e?0:this.weather.highCloudCover??0;return a>0&&(i*=1-bt.iceAlphaAt(s,Ac,a,this.cloudFieldOffset)*My),Math.max(0,Math.min(1,i))}setBodyMesh(t,e,s,i,n){if(e.altitudeDeg<Fc){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1,ps.setDisc("sun",void 0));return}const{x:a,y:o,z:r}=Vt(e.altitudeDeg,e.azimuthDeg,de),c=this.cloudTransmission(e),h=this.arrivingIlluminance(e,n,c),l=N.unitLuminance(i);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(s/de)**2,m=[0,1,2].map(g=>l[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=m;const p=m.map(g=>Math.min(N.BRIGHTEST_RELATIVE,g));d instanceof B||(this.disposeMesh(d),d=new B(new Ge(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(p[0],p[1],p[2]),d.scale.setScalar(s),ps.setDisc("sun",{direction:[a/de,o/de,r/de],radiusRad:Math.atan(s/de),radiance:p})}else{if(!(d instanceof Us)){this.disposeMesh(d);const p=new le;p.setAttribute("position",new Ot(new Float32Array(3),3)),p.setAttribute("color",new Ot(new Float32Array(3),3)),d=new Us(p,Z.material(Ta[Ta.length-1].size,!1)),Z.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),m=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,l[0]*h[0]*m,l[1]*h[1]*m,l[2]*h[2]*m),f.needsUpdate=!0}if(d.position.set(a,o,r),this.setHitArea(t,a,o,r,s),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,a,o,r,h,s/de*(180/Math.PI),N.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(a*f,o*f+this.celestialGroup.position.y,r*f),this.lensFlare||(this.lensFlare=DM(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const s="moon";if(t.magnitude>e||t.altitudeDeg<Fc){this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s),ps.setDisc("moon",void 0);return}const{x:i,y:n,z:a}=Vt(t.altitudeDeg,t.azimuthDeg,de),o=this.cloudTransmission(t),r=this.arrivingIlluminance(t,t.magnitude,o),c=t.radiusDeg??Bi.MEAN_RADIUS_DEG,h=de*Math.tan(c*Mt),l=Math.max(Oi(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/de)**2,d=new q(...r.map(g=>Math.min(N.BRIGHTEST_RELATIVE,g/l))),f=Math.PI*(h/de)**2;ps.setDisc("moon",{direction:[i/de,n/de,a/de],radiusRad:c*Mt,radiance:r.map(g=>Math.min(N.BRIGHTEST_RELATIVE,g/f))});const m=`${t.phase.phaseFraction<.5}:${Math.round(Oi(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(s);p instanceof to?(p.userData.phaseKey!==m&&(p.material.map?.dispose(),p.material.map=xf(t.phase),p.userData.phaseKey=m),p.material.color.copy(d)):(this.disposeMesh(p),p=new to(new kc({map:xf(t.phase),color:d,fog:!1,blending:rs,depthWrite:!1})),p.userData.phaseKey=m,this.celestialGroup.add(p),this.bodyMeshes.set(s,p)),p.scale.set(h*2,h*2,1),p.position.set(i,n,a),this.setHitArea(s,i,n,a,h),this.setGlare(s,i,n,a,r,c)}bentLight(t,e,s=my){const[i,n,a]=this.arrivingIlluminance(t,e,1),o=Math.max(n,1e-30);return{scale:n/s,tint:[i/o,1,a/o]}}static litBySky(t,e){return N.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new q;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Z.CONE_SOLID_ANGLE/e)}pointScratch=new ht;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,s){const i=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),n=At.illuminanceOf(e)*s*this.relativeScale;return[i[0]*n,i[1]*n,i[2]*n]}static unitLuminance(t){const e=Ls.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,s,i,n){let a=this.hitAreas.get(t);if(!a){const r=new kc({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});a=new to(r),this.celestialGroup.add(a),this.hitAreas.set(t,a)}a.position.set(e,s,i);const o=n*2;a.scale.set(o,o,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,s,i,n,a,o=0){if(_e.radiusDeg(_e.K*Math.max(...n))<=Math.max(a,o)){this.disposeGlare(t);return}let r=this.glareSprites.get(t);r||(r=new _e(`veil:${t}`),this.celestialGroup.add(r.mesh),this.glareSprites.set(t,r)),r.shine({x:e,y:s,z:i},n,a,o)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const s=t&&`comet:${t.id}`;if(!t||!s||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==s&&this.disposeComet();const i=va(t.magnitude,e),n=Cc(i);this.cometKey=s,this.setBodyMesh(s,t.position,Ml*(.5+.5*i),new q(n,n,n),t.magnitude),this.cometTail||(this.cometTail=new Fs(de),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,i)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new ge,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const s=this.highCloudCover(),i=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(i?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),s===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:Ac},0);return}const n=this.lowerCloudCover(),a=dt.deckLitUntilDeg(dt.DECK_HEIGHT_M),o=t.altitudeDeg>-a?t:e,r=this.bentLight(o,o===t?st.SUN_MAGNITUDE:e.magnitude),c=dt.strength(s,n,o.altitudeDeg,a)*r.scale,{x:h,y:l,z:d}=Vt(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:l,z:d},o.altitudeDeg,c,r.tint,{cover:i?.cover??s,layerHeight:i?.layerHeight??Ac},i?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Hp,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Ma,this.celestialGroup.add(this.rainbow.object));const s=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,i=t.altitudeDeg>0,n=i?t:e,a=this.lowerCloudCover(),o=this.bentLight(n,i?st.SUN_MAGNITUDE:e.magnitude,py),r=zs.strength(s,a,n.altitudeDeg)*o.scale;if(r<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:l}=Vt(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:l},r,o.tint,i)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Fn,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:s,observer:i}=t.frame,n=pi.galactic(s,i),a=N.directionOf(n.centre),o=N.directionOf(n.rotation),r=N.directionOf(n.pole),c=new Pa().set(a.x,a.y,a.z,o.x,o.y,o.z,r.x,r.y,r.z),h=N.directionOf(pi.eclipticPole(s,i)),l=N.directionOf(t.sun),d=l.clone().addScaledVector(h,-l.dot(h)).normalize();this.skyGlow.update({galactic:c,eclipticPole:h,sunLongitude:d,sunDirection:l,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:N.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:U.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new D(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:s,z:i}=Vt(t.altitudeDeg,t.azimuthDeg,1);return new D(e,s,i).normalize()}buildNovae(t,e){const s=new Set;for(const i of t){if(i.magnitude>e)continue;const n=`nova:${i.id}`;s.add(n);const a=va(i.magnitude,e),o=Cc(a);this.setBodyMesh(n,i.position,Ml*(.5+.5*a),new q(o,o,o),i.magnitude)}for(const i of this.novaKeys)s.has(i)||(this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i));this.novaKeys=s}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const s=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const i of t){if(i.magnitude>e)continue;s.add(i.body);const n=va(i.magnitude,e),a=Cc(n),o=qy[i.body]??new q(1,1,1),r=new q(o.r*a,o.g*a,o.b*a),c=Ml*(.5+.5*n);this.setBodyMesh(i.body,i.position,c,r,i.magnitude)}for(const i of[...this.bodyMeshes.keys()])s.has(i)||(this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:s,date:i,observer:n}=t,a=new Mi(i,n),o=Dl(1337),r=[],c=this.siteElevationM+this.observerElevationM;for(let h=0;h<s.count;h++){const l=s.mag[h];if(l>e)break;const{altitudeDeg:d,azimuthDeg:f}=a.position(s.ra[h],s.dec[h]);if(d<Q0)continue;const{x:m,y:p,z:g}=Vt(d,f,ml);r.push({x:m,y:p,z:g,brightness:va(l,e),illuminance:this.air.transmittanceFromSpace(c,d).map(M=>M*At.illuminanceOf(l)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of Z2){if(h.mag>e)continue;const{altitudeDeg:l,azimuthDeg:d}=a.position(h.raHours,h.decDeg);if(l<Q0)continue;const{x:f,y:m,z:p}=Vt(l,d,ml);this.namedStars.push({star:h,direction:new D(f,m,p).normalize(),altitudeDeg:l})}this.starTiers=Ta.map((h,l)=>{const d=r.filter(b=>Dh(b.brightness)===l),f=new Float32Array(d.length*3),m=new Float32Array(d.length),p=new Float32Array(d.length*3),g=new Float32Array(d.length),M=new Float32Array(d.length);d.forEach((b,E)=>{f[E*3]=b.x,f[E*3+1]=b.y,f[E*3+2]=b.z,m[E]=b.brightness,p.set(b.illuminance,E*3),g[E]=b.phase,M[E]=b.speedFactor});const v=new le;v.setAttribute("position",new Ot(f,3)),v.setAttribute("seed",new Ot(g.map(b=>b/(2*Math.PI)),1));const y=new Ot(new Float32Array(d.length*3),3);v.setAttribute("color",y);let w=this.starTiers[l]?.points;return w?(w.geometry.dispose(),w.geometry=v):(w=new Us(v,Z.material(h.size)),Z.track(w),this.celestialGroup.add(w)),{points:w,colorAttribute:y,brightness:m,illuminance:p,phase:g,speedFactor:M}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Z.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const s of this.starTiers){const i=s.colorAttribute.array;for(let n=0;n<s.brightness.length;n++)i[n*3]=s.illuminance[n*3]*e,i[n*3+1]=s.illuminance[n*3+1]*e,i[n*3+2]=s.illuminance[n*3+2]*e;s.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new _o(this.celestialGroup,vl,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.skyEventCloudLights.size>0&&this.layeredClouds.setLights([...this.skyEventCloudLights.values()].flat(),this.camera.position),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,s=new q(aa[0]+(bl[0]-aa[0])*e,aa[1]+(bl[1]-aa[1])*e,aa[2]+(bl[2]-aa[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(s),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:i,uniforms:n}=cu(s,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=i,this.cloudUniforms=n,n.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const a=hu(vl);this.cloudMesh=new B(a,i),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:s}=cu(new q(...aa),t,Ac,1);this.cirrusMaterial=e,this.cirrusUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new B(hu(vl*1.04),e),this.cirrusMesh.renderOrder=hf-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const s=e<0;t.scale.y=s?-1:1,t.renderOrder=s?_o.deckOrder(!0,0,1):hf}cloudLayerOffset(){const e=((this.weather.cloudBaseM??Yf)-this.observerElevationM)*yl;return Math.sign(e||1)*Math.max(Math.abs(e),Py)}updateCloudLighting(t,e){const s=[this.cloudUniforms,this.cirrusUniforms].filter(l=>l!==void 0);if(s.length===0&&!this.layeredClouds)return;const i=this.cloudBeamDirection,[n,a,o]=this.cloudBeam.map(l=>l/Math.PI),r=this.lightningLevel*Tl*this.relativeScale/Math.PI,c=new q(e[0]+xi.r*r,e[1]+xi.g*r,e[2]+xi.b*r);this.layeredClouds?.setLighting(i.clone(),new q(n,a,o),c,c),this.layeredClouds?.setLightFromBelow(this.townsUnderClouds());const h=Math.max(0,i.y);for(const l of s)l.sunDir.value.copy(i),l.sunColor.value.setRGB(n*h,a*h,o*h),l.ambientColor.value.copy(c)}static TOWNS_UNDER_OVERCAST=10;static TOWNS_KELVINS=3e3;townsUnderClouds(){const t=U.artificialZenithNanolamberts(this.lightPollution)*st.CANDELAS_PER_NANOLAMBERT;if(t<=0)return[0,0,0];const e=t*N.TOWNS_UNDER_OVERCAST*this.relativeScale,s=Ia.ofTemperature(N.TOWNS_KELVINS);return[s[0]*e,s[1]*e,s[2]*e]}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return Hy(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,Sl],[this.rainSplashSystem?.points,oa],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:El[this.weather.precipitationType].poolSize]];for(const[e,s]of t)e&&s!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(s));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=ff(xl(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=El[t],s=e.poolSize,i=Dl(9001),n=new Float32Array(s*3),a=new Float32Array(s),o=new Float32Array(s),r=new Float32Array(s),c=new Float32Array(s),h=new Float32Array(s),l=new Float32Array(s),d=new Float32Array(s),f=new Float32Array(s),m=new Float32Array(s);for(let y=0;y<s;y++){const w=i()*Math.PI*2,b=i()*e.radiusM;n[y*3]=Math.cos(w)*b,n[y*3+1]=ao+i()*(e.topYM-ao),n[y*3+2]=Math.sin(w)*b,a[y]=i()*Math.PI*2,o[y]=.7+i()*.6,r[y]=.6+i()*.8,c[y]=.4+i()*1.2}const p=new le;p.setAttribute("position",new Ot(n,3)),p.setDrawRange(0,this.precipitationCount(s));const g={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new q(...this.baseFogColor)},uTexture:{value:jy(t)},uNearFocusDistance:{value:Mf},uHazeDistance:{value:e.radiusM*vf}},M=new Lt({uniforms:g,vertexShader:sw,fragmentShader:iw,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const v=new Us(p,M);v.renderOrder=wl,this.scene.add(v),this.precipitationPoints=v,this.precipitationPositions=n,this.precipitationPhase=a,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=r,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=l,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=m}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const s=this.weather.precipitationType;if(s==="none"||s==="rain")return;const i=El[s];if(this.precipitationUniforms?.uColor.value.copy(N.litBySky(i.color,this.baseFogColor)),e<=0)return;const n=this.weather.windDirectionDeg*Mt,a=Math.sin(n)*this.weather.windSpeed*i.driftSensitivity,o=-Math.cos(n)*this.weather.windSpeed*i.driftSensitivity,r=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,l=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,m=this.precipitationBounceHeight,p=this.precipitationBounceDuration,g=this.precipitationBounceVelX,M=this.precipitationBounceVelZ,v=s==="snow"&&l&&d,y=s==="hail"&&f&&m&&p&&g&&M;for(let w=0,b=0;w<r.length;w+=3,b++){if(y&&f[b]>0){if(f[b]-=e,f[b]<=0){const S=Math.random()*Math.PI*2,x=Math.sqrt(Math.random())*i.radiusM;r[w]=Math.cos(S)*x,r[w+1]=i.topYM,r[w+2]=Math.sin(S)*x,f[b]=0}else{const S=1-f[b]/p[b];r[w+1]=ao+Math.sin(Math.PI*S)*m[b],r[w]=xc(r[w]+(a+g[b])*e,i.radiusM),r[w+2]=xc(r[w+2]+(o+M[b])*e,i.radiusM)}continue}let E=0,A=0;if(v){const S=Gy*l[b],x=By*d[b];E=Math.sin(t*S*Math.PI*2+c[b])*x,A=Math.sin(t*S*Math.PI*2+c[b]+Math.PI/2)*x}if(r[w]+=(a+E)*e,r[w+1]-=i.fallSpeedMPerS*h[b]*e,r[w+2]+=(o+A)*e,r[w]=xc(r[w],i.radiusM),r[w+2]=xc(r[w+2],i.radiusM),r[w+1]<ao){if(y){m[b]=Af*(.2+Math.random()*1.6),p[b]=Vy*(.5+Math.random()),f[b]=p[b];const T=Math.random()*Math.PI*2,I=Wy*(m[b]/Af);g[b]=Math.cos(T)*I,M[b]=Math.sin(T)*I,r[w+1]=ao;continue}const S=Math.random()*Math.PI*2,x=Math.sqrt(Math.random())*i.radiusM;r[w]=Math.cos(S)*x,r[w+1]=i.topYM,r[w+2]=Math.sin(S)*x}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=xl(this.weather.precipitationIntensity);this.rainSystem=SM({count:Sl,radiusM:hr,heightM:Ly,bottomYM:lf,overallSpeed:Ny,color:df.clone(),opacity:.85,visibleCount:this.precipitationCount(Sl),speedStreak:ff(t),pixelSize:wf,seed:9001,nearFocusDistanceM:Mf,hazeDistanceM:hr*vf,hazeColor:new q(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=wl,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=Dl(4242),e=new Float32Array(oa*3),s=new Float32Array(oa),i=new Float32Array(oa),n=new Float32Array(oa);for(let h=0;h<oa;h++){const l=t()*Math.PI*2,d=Math.sqrt(t())*hr;e[h*3]=Math.cos(l)*d,e[h*3+1]=lf,e[h*3+2]=Math.sin(l)*d,i[h]=Sf(mf,pf),s[h]=t()*i[h],n[h]=s[h]/i[h]}const a=new le;a.setAttribute("position",new Ot(e,3));const o=new Ot(n,1);a.setAttribute("aLife",o),a.setDrawRange(0,this.precipitationCount(oa));const r=new Lt({uniforms:{uMaxSize:{value:Fy},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:gf.clone()},uTexture:{value:Qy()}},vertexShader:tw,fragmentShader:ew,transparent:!0,depthWrite:!1}),c=new Us(a,r);c.renderOrder=wl,this.scene.add(c),this.rainSplashSystem={points:c,positions:e,life:s,duration:i,lifeAttribute:o}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*Mt;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-xl(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const s=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=s.x/Math.max(s.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(N.litBySky(df,this.baseFogColor));const s=this.rainSplashSystem?.points.material?.uniforms?.uColor;s&&s.value.copy(N.litBySky(gf,this.baseFogColor));const i=this.weather.windDirectionDeg*Mt,n=Math.sin(i)*this.weather.windSpeed,a=-Math.cos(i)*this.weather.windSpeed,o=hr,r=h=>(h%(o*2)+o*3)%(o*2)-o;e.uniforms.uWindOffset.value.set(r(e.uniforms.uWindOffset.value.x+n*t),r(e.uniforms.uWindOffset.value.y+a*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const c=Math.abs(this.rainCameraDirection.y);if(Math.abs(c-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=c;const h=bf+(1-bf)*(1-c),l=Ef+(1-Ef)*(1-c);e.uniforms.uUvSquash.value=l,e.uniforms.uPixelSize.value=wf*h*(.5+.5*l)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:s,life:i,duration:n,lifeAttribute:a}=e,o=a.array;for(let r=0,c=0;r<s.length;r+=3,c++){if(i[c]+=t,i[c]>=n[c]){const h=Math.random()*Math.PI*2,l=Math.sqrt(Math.random())*hr;s[r]=Math.cos(h)*l,s[r+2]=Math.sin(h)*l,n[c]=Sf(mf,pf),i[c]=0}o[c]=i[c]/n[c]}e.points.geometry.attributes.position.needsUpdate=!0,a.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,s=0;if(this.lightningArmed)for(const r of this.lightningFlashes){if(r.t>t)break;const c=De.brightnessAt(r,t);c>s&&(e=r,s=c)}const i=e?Math.min(1,Math.max(.1,($y/e.distanceM)**2)):0,n=s*i*(e?.cloudToGround?1:.6);if(n===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const r=this.scene.fog,c=n*Tl*this.relativeScale/Math.PI;r.color.setRGB(this.airlight[0]+xi.r*c,this.airlight[1]+xi.g*c,this.airlight[2]+xi.b*c)}const a=this.skyMesh?.material?.color;if(a){const r=n*Xy;a.setRGB(1+r*xi.r,1+r*xi.g,1+r*xi.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*Tl*this.relativeScale,e){const{x:r,y:c,z:h}=Vt(25,e.azimuthDeg,de);this.lightningLight.position.set(r,c,h)}this.lightningBolt||(this.lightningBolt=new Hn(de*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,s,o),this.render()}buildCompassLabels(){this.compassSprites=Ty.map(t=>{const e=Da.point(t,this.compassPoints),s=new kc({map:nw(e),depthTest:!1,fog:!1}),i=new to(s),{x:n,y:a,z:o}=Vt(0,t,nf);return i.position.set(n,a,o),i.scale.set(Sc,Sc,1),i.renderOrder=Ry,i.layers.set(dl),i.visible=this.compassForced,this.celestialGroup.add(i),i}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=af*Math.PI/360,s=Sc*Math.tan(t)/Math.tan(e);for(const i of this.compassSprites)i.scale.set(s,s,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const s of Array.isArray(e)?e:[e]){const i=s.map;i&&i.dispose(),s.dispose()}}}const Mt=Math.PI/180;function Oi(u,t,e){return Math.max(t,Math.min(e,u))}function Sf(u,t){return u+Math.random()*(t-u)}function xc(u,t){return(u%(t*2)+t*3)%(t*2)-t}let Tc,Dc;function jy(u){switch(u){case"snow":return Zy();case"hail":return Jy()}}function Zy(){if(Tc)return Tc;const u=64,t=document.createElement("canvas");t.width=u,t.height=u;const e=t.getContext("2d"),s=e.createRadialGradient(u/2,u/2,0,u/2,u/2,u/2);return s.addColorStop(0,"rgba(255,255,255,0.95)"),s.addColorStop(.5,"rgba(255,255,255,0.55)"),s.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=s,e.fillRect(0,0,u,u),Tc=new Qn(t),Tc}function Jy(){if(Dc)return Dc;const u=64,t=document.createElement("canvas");t.width=u,t.height=u;const e=t.getContext("2d"),s=e.createRadialGradient(u/2,u/2,0,u/2,u/2,u/2);return s.addColorStop(0,"rgba(255,255,255,1)"),s.addColorStop(.55,"rgba(255,255,255,0.95)"),s.addColorStop(.8,"rgba(255,255,255,0.4)"),s.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=s,e.fillRect(0,0,u,u),Dc=new Qn(t),Dc}let Ic;function Qy(){if(Ic)return Ic;const u=64,t=document.createElement("canvas");t.width=u,t.height=u;const e=t.getContext("2d"),s=e.createRadialGradient(u/2,u/2,0,u/2,u/2,u/2);return s.addColorStop(0,"rgba(255,255,255,0)"),s.addColorStop(.4,"rgba(255,255,255,0)"),s.addColorStop(.6,"rgba(255,255,255,0.9)"),s.addColorStop(.8,"rgba(255,255,255,0.25)"),s.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=s,e.fillRect(0,0,u,u),Ic=new Qn(t),Ic}const tw=`
|
|
4930
4934
|
uniform float uMaxSize;
|
|
4931
4935
|
uniform float uScale;
|
|
4932
4936
|
attribute float aLife;
|
|
@@ -4992,7 +4996,7 @@ void main() {
|
|
|
4992
4996
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
4993
4997
|
}
|
|
4994
4998
|
`;function xf(u){const e=document.createElement("canvas");e.width=128,e.height=128;const s=e.getContext("2d"),i=128/2-2,n=128/2,a=128/2,o="#010101",r="#f4f1e2";s.fillStyle=o,s.beginPath(),s.arc(n,a,i,0,Math.PI*2),s.fill();const c=Oi(u.illuminatedFraction,0,1),h=u.phaseFraction<.5,l=i*Math.abs(1-2*c),d=c<.5;return s.save(),s.beginPath(),s.arc(n,a,i,0,Math.PI*2),s.clip(),s.fillStyle=r,s.beginPath(),h?(s.arc(n,a,i,-Math.PI/2,Math.PI/2,!1),s.ellipse(n,a,l,i,0,Math.PI/2,-Math.PI/2,d)):(s.arc(n,a,i,Math.PI/2,-Math.PI/2,!1),s.ellipse(n,a,l,i,0,-Math.PI/2,Math.PI/2,d)),s.fill(),s.restore(),new Qn(e)}function nw(u){const t=document.createElement("canvas");t.width=128,t.height=128;const e=t.getContext("2d");return e.fillStyle="rgba(0, 0, 0, 0.55)",e.beginPath(),e.arc(64,64,60,0,Math.PI*2),e.fill(),e.fillStyle="#ffffff",e.font="bold 52px sans-serif",e.textAlign="center",e.textBaseline="middle",e.fillText(u,64,68),new Qn(t)}function Dl(u){let t=u;return function(){t|=0,t=t+1831565813|0;let s=Math.imul(t^t>>>15,1|t);return s=s+Math.imul(s^s>>>7,61|s)^s,((s^s>>>14)>>>0)/4294967296}}class uh{constructor(t,e){this.source=t,this.create=e}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;paint(t,e){this.disposed||(this.wanted={t,canvas:e},this.pumping||this.pump())}recordingChanged(t){this.scene&&(this.scene.sightingData=t)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const t=this.create();return t.setAttribute("max-pixel-ratio","1"),t.setAttribute("always-live",""),Object.assign(t.style,{position:"fixed",left:"-10000px",top:"0",width:`${uh.SCENE_WIDTH_PX}px`,visibility:"hidden",pointerEvents:"none"}),document.body.appendChild(t),t.documentUrl=this.source.documentUrl,t.accountInTheRound=this.source.accountInTheRound,t.sightingData=this.source.sightingData,this.scene=t,t}async pump(){this.pumping=!0;try{for(;this.wanted&&!this.disposed;){const{t,canvas:e}=this.wanted;this.wanted=void 0;const s=this.ensureScene();s.interpretation!==this.source.interpretation&&(s.interpretation=this.source.interpretation),s.compareAccount!==this.source.compareAccount&&(s.compareAccount=this.source.compareAccount),s.showAt(t);for(let i=0;i<uh.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(n=>requestAnimationFrame(()=>n())),!this.wanted);i++)if(s.snapshotTo(e)){e.dataset.ready="true";break}}}finally{this.pumping=!1}}}class $t{static held=new Map;static loaded=new Map;static generation=0;static address(t,e){const s=e??(typeof location>"u"?"http://localhost/":location.href);return new URL(t,s).href}static hold(t,e){$t.held.set(t,e),$t.loaded.delete(t),$t.generation++}static release(){if($t.held.size!==0){for(const t of $t.held.keys())$t.loaded.delete(t);$t.held.clear(),$t.generation++}}static bytes(t,e=fetch.bind(globalThis)){const s=$t.held.get(t);if(s)return Promise.resolve(s);let i=$t.loaded.get(t);return i||(i=e(t).then(async n=>{if(!n.ok)throw new Error(`Frozen data not found (${n.status}): ${t}`);return new Uint8Array(await n.arrayBuffer())}),$t.loaded.set(t,i),i.catch(()=>$t.loaded.delete(t))),i}static async json(t){return JSON.parse(new TextDecoder().decode(await $t.bytes(t)))}static async zip(t){const e=await $t.bytes(t),{unzipSync:s}=await H(async()=>{const{unzipSync:i}=await import("./browser-CltifEM0.js");return{unzipSync:i}},[],import.meta.url);return s(e)}}class ji{static SAME_BOUNDS_DEG=1e-9;loaded=!1;ready;list=[];constructor(t){this.ready=t.then(e=>{this.list=e},()=>{}).finally(()=>{this.loaded=!0})}nearest(t,e){let s,i=1/0;for(const n of this.list){if(n.far)continue;const{x:a,z:o}=ot(n.lat,n.lng,t,e),r=Math.hypot(a,o);r<i&&(i=r,s=n)}return s}farRingOf(t,e){return this.list.find(s=>s.far&&Math.abs(s.lat-t)<=ji.SAME_BOUNDS_DEG&&Math.abs(s.lng-e)<=ji.SAME_BOUNDS_DEG)}static boundsOf(t){return xr(t.lat,t.lng,t.radiusM)}static sameBounds(t,e){const s=(i,n)=>Math.abs(i-n)<=ji.SAME_BOUNDS_DEG;return s(t.north,e.north)&&s(t.south,e.south)&&s(t.east,e.east)&&s(t.west,e.west)}static contains(t,e){return t.north>=e.north&&t.south<=e.south&&t.east>=e.east&&t.west<=e.west}static samePatches(t,e){return t.length===e.length&&t.every((s,i)=>s.lat===e[i].lat&&s.lng===e[i].lng&&s.radiusM===e[i].radiusM&&s.far===e[i].far)}}class dh{static async encode(t){const{zipSync:e,strToU8:s}=await H(async()=>{const{zipSync:a,strToU8:o}=await import("./browser-CltifEM0.js");return{zipSync:a,strToU8:o}},[],import.meta.url),i={},n={version:1,takenOn:t.takenOn,attribution:t.attribution,patches:t.patches.map((a,o)=>{const r=`${o}.f32`;return i[r]=dh.byPlane(a.grid.heights),{lat:a.lat,lng:a.lng,radiusM:a.radiusM,...a.far?{far:a.far}:{},bounds:a.grid.bounds,width:a.grid.width,height:a.grid.height,file:r}})};return i["index.json"]=s(JSON.stringify(n,null,1)),e(i,{level:9})}static decode(t){const e=t["index.json"];if(!e)throw new Error("A relief annex without its index");const s=JSON.parse(new TextDecoder().decode(e));return{takenOn:s.takenOn,attribution:s.attribution,patches:s.patches.flatMap(i=>{const n=t[i.file];if(!n||n.length!==i.width*i.height*4)return[];const a={heights:dh.fromPlanes(n),width:i.width,height:i.height,bounds:i.bounds};return[{lat:i.lat,lng:i.lng,radiusM:i.radiusM,...i.far?{far:i.far}:{},grid:a}]})}}static byPlane(t){const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),s=t.length,i=new Uint8Array(e.length);for(let n=0;n<s;n++)for(let a=0;a<4;a++)i[a*s+n]=e[n*4+a];return i}static fromPlanes(t){const e=t.length/4,s=new Uint8Array(t.length);for(let i=0;i<e;i++)for(let n=0;n<4;n++)s[i*4+n]=t[n*e+i];return new Float32Array(s.buffer)}}class ed{constructor(t){this.annex=t}async getElevationGrid(t,e,s){const{patches:i}=await this.annex,n=i.find(o=>ji.sameBounds(ji.boundsOf(o),t));if(n)return{...n.grid,heights:new Float32Array(n.grid.heights)};const a=i.find(o=>ji.contains(o.grid.bounds,t));if(a)return ed.resample(a.grid,t,e);throw new Error("The snapshots relief does not hold this ground")}static resample(t,e,s){const{width:i,height:n}=s,a=new Float32Array(i*n),o=t.bounds.east-t.bounds.west,r=t.bounds.north-t.bounds.south;for(let c=0;c<n;c++){const h=e.north-(e.north-e.south)*(n>1?c/(n-1):0),l=Math.min(t.height-1,Math.max(0,(t.bounds.north-h)/r*(t.height-1))),d=Math.floor(l),f=Math.min(t.height-1,d+1),m=l-d;for(let p=0;p<i;p++){const g=e.west+(e.east-e.west)*(i>1?p/(i-1):0),M=Math.min(t.width-1,Math.max(0,(g-t.bounds.west)/o*(t.width-1))),v=Math.floor(M),y=Math.min(t.width-1,v+1),w=M-v,b=(S,x)=>t.heights[S*t.width+x],E=b(d,v)*(1-w)+b(d,y)*w,A=b(f,v)*(1-w)+b(f,y)*w;a[c*i+p]=E*(1-m)+A*m}}return{heights:a,width:i,height:n,bounds:e}}}function Sp(u,t){return u.find(e=>e.id===t)??u[0]}class aw{attribution;fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis);const e=t.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${e}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${e})`}async getImageryTexture(t,e){return cm(t,e,s=>this.tileUrlTemplate.replace("{z}",String(s.z)).replace("{y}",String(s.y)).replace("{x}",String(s.x)),this.fetchImpl)}}const Qw=ke.point("elevation").provide(ke.BUILT_IN,[{id:"ign-mnt",name:"IGN LiDAR HD / RGE ALTI",credit:"Relief © IGN, LiDAR HD and RGE ALTI (Licence Ouverte 2.0) in France; © AWS Open Data (SRTM, ETOPO1) elsewhere",creditUrl:"https://geoservices.ign.fr/lidarhd",create:()=>Bm()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new hm}]),xp=ke.point("imagery").provide(ke.BUILT_IN,[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:u=>new Um({fetchImpl:u})},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:u=>new aw({fetchImpl:u})}]);class t5{constructor(t=fetch.bind(globalThis)){this.fetchImpl=t}tiles=new Map;fetch=async(t,e)=>{const s=await this.fetchImpl(t,e);if(s.ok){const i=typeof t=="string"?t:t instanceof URL?t.href:t.url,n=new Uint8Array(await s.clone().arrayBuffer());this.tiles.set(i,{bytes:n,type:s.headers.get("content-type")??"image/jpeg"})}return s}}class Tf{static async encode(t){const{zipSync:e,strToU8:s}=await H(async()=>{const{zipSync:r,strToU8:c}=await import("./browser-CltifEM0.js");return{zipSync:r,strToU8:c}},[],import.meta.url),i={},n={};let a=0;for(const[r,c]of t.tiles){const h=`tiles/${a++}`;i[h]=c.bytes,n[r]={file:h,type:c.type}}const o={version:1,takenOn:t.takenOn,source:t.source,attribution:t.attribution,patches:t.patches,map:t.map,tiles:n};return i["index.json"]=s(JSON.stringify(o,null,1)),e(i,{level:0})}static decode(t){const e=t["index.json"];if(!e)throw new Error("An imagery annex without its index");const s=JSON.parse(new TextDecoder().decode(e)),i=new Map;for(const[n,{file:a,type:o}]of Object.entries(s.tiles)){const r=t[a];r&&i.set(n,{bytes:r,type:o})}return{takenOn:s.takenOn,source:s.source,attribution:s.attribution,patches:s.patches,map:s.map,tiles:i}}}class Ph{constructor(t,e=""){this.annex=t,this.attributionStated=e}provider;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}async getImageryTexture(t,e){return(await(this.provider??=this.annex.then(i=>(this.attributionRead=i.attribution,Sp(xp,i.source).create(Ph.fetchFrom(i.tiles)))))).getImageryTexture(t,e)}static fetchFrom(t){return async e=>{const s=typeof e=="string"?e:e instanceof URL?e.href:e.url,i=t.get(s);return i?new Response(i.bytes,{status:200,headers:{"content-type":i.type}}):new Response(null,{status:404})}}}class ow{constructor(t,e=""){this.annex=t,this.attributionStated=e}picture;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}getImagery(){return this.picture??=this.annex.then(t=>{if(!t.map)throw new Error("An imagery annex that holds no map");return this.attributionRead=t.attribution,Sp(xp,t.source).create(Ph.fetchFrom(t.tiles)).getImageryTexture(t.map.bounds,{width:t.map.pixels,height:t.map.pixels})})}}class sd{constructor(t){this.annex=t}attributionRead;contemporaryRead;async itemsFor(t){const e=await this.annex;return this.attributionRead=e.attribution,this.contemporaryRead=e.contemporary,e.patches.find(s=>ji.sameBounds(ji.boundsOf(s),t))?.items??[]}}class rw{constructor(t,e=""){this.attributionStated=e,this.reader=new sd(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRoads(t){return this.reader.itemsFor(t)}}class cw{constructor(t,e=""){this.attributionStated=e,this.reader=new sd(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(t){return this.reader.itemsFor(t)}}class hw{constructor(t,e=""){this.attributionStated=e,this.reader=new sd(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRailways(t){return this.reader.itemsFor(t)}}class fh{static providers(t,e,s){const i=f=>Oc.held(t,f),n=i("relief"),a=i("imagery"),o=i("roads"),r=i("water"),c=i("railways");if(!n&&!a&&!o&&!r&&!c)return s;const h=f=>$t.address(f.src,e),l=[],d={...s};if(n){const f=$t.zip(h(n)).then(m=>dh.decode(m));d.elevation=new ed(f),l.push(f.then(m=>m.patches))}if(a){const f=$t.zip(h(a)).then(m=>Tf.decode(m));d.imagery=new Ph(f,a.attribution),l.push(f.then(m=>m.patches))}if(o){const f=$t.json(h(o));d.roads=new rw(f,o.attribution),l.push(f.then(m=>m.patches))}if(r){const f=$t.json(h(r));d.water=new cw(f,r.attribution),l.push(f.then(m=>m.patches))}if(c){const f=$t.json(h(c));d.railways=new hw(f,c.attribution),l.push(f.then(m=>m.patches))}return d.patches=new ji(fh.firstRead(l)),d}static map(t,e){const s=$t.zip($t.address(t.src,e)).then(i=>Tf.decode(i));return new ow(s,t.attribution)}static async firstRead(t){for(const e of t)try{const s=await e;if(s.length>0)return s.map(({lat:i,lng:n,radiusM:a,far:o})=>({lat:i,lng:n,radiusM:a,...o?{far:o}:{}}))}catch{}return[]}}const Za="https://en.wikipedia.org/wiki/Kodachrome",ra="https://en.wikipedia.org/wiki/Kodacolor_(still_photography)",lw="https://en.wikipedia.org/wiki/Kodak_Tri-X",Ja="https://en.wikipedia.org/wiki/List_of_discontinued_photographic_films",nn="https://www.kodak.com/en/motion/page/chronology-of-film/",_s=(u,t)=>[{format:"135",from:u,to:t},{format:"120",from:u,to:t}],an=(u,t)=>[{format:"35mm-cine",from:u,to:t}],Df=[{id:"kodacolor",name:"Kodacolor",kind:"negative",iso:32,formats:_s(1942,1963),source:ra},{id:"kodacolor-x",name:"Kodacolor-X",kind:"negative",iso:80,formats:[..._s(1963,1974),{format:"126",from:1963,to:1974}],source:ra},{id:"kodacolor-ii",name:"Kodacolor II",kind:"negative",iso:100,formats:[..._s(1973),{format:"126",from:1973}],source:ra},{id:"kodacolor-400",name:"Kodacolor 400",kind:"negative",iso:400,formats:_s(1977),source:ra},{id:"kodacolor-vr-100",name:"Kodacolor VR 100",kind:"negative",iso:100,formats:_s(1982,1986),source:ra},{id:"kodacolor-vr-200",name:"Kodacolor VR 200",kind:"negative",iso:200,formats:[..._s(1982,1986),{format:"126",from:1982,to:1986}],source:ra},{id:"kodacolor-vr-400",name:"Kodacolor VR 400",kind:"negative",iso:400,formats:_s(1982,1986),source:ra},{id:"agfacolor-cn17",name:"Agfacolor CN17",kind:"negative",iso:40,formats:_s(1956,1971),source:Ja},{id:"agfacolor-cns",name:"Agfacolor CNS",kind:"negative",iso:80,formats:[..._s(1968,1975),{format:"126",from:1968,to:1975}],source:Ja},{id:"agfacolor-cns-2",name:"Agfacolor CNS 2",kind:"negative",iso:80,formats:[..._s(1971,1982),{format:"126",from:1971,to:1982}],source:Ja},{id:"agfacolor-cns-400",name:"Agfacolor CNS 400",kind:"negative",iso:400,formats:_s(1978,1984),source:Ja},{id:"kodachrome",name:"Kodachrome",kind:"slide",iso:10,formats:[{format:"135",from:1936,to:1962}],source:Za},{id:"kodachrome-ii",name:"Kodachrome II",kind:"slide",iso:25,formats:[{format:"135",from:1961,to:1974}],source:Za},{id:"kodachrome-x",name:"Kodachrome-X",kind:"slide",iso:64,formats:[{format:"135",from:1962,to:1974},{format:"126",from:1963,to:1974}],source:Za},{id:"kodachrome-25",name:"Kodachrome 25",kind:"slide",iso:25,formats:[{format:"135",from:1974,to:2001}],source:Za},{id:"kodachrome-64",name:"Kodachrome 64",kind:"slide",iso:64,formats:[{format:"135",from:1974,to:2009},{format:"126",from:1974,to:1993}],source:Za},{id:"kodachrome-200",name:"Kodachrome 200",kind:"slide",iso:200,formats:[{format:"135",from:1988,to:2007}],source:Za},{id:"agfachrome-ct18",name:"Agfachrome CT18",kind:"slide",iso:50,formats:[..._s(1958,1984),{format:"126",from:1958,to:1984}],source:Ja},{id:"agfachrome-ct21",name:"Agfachrome CT21",kind:"slide",iso:100,formats:[{format:"135",from:1974,to:1984}],source:Ja},{id:"tri-x",name:"Kodak Tri-X",kind:"negative",monochrome:!0,iso:400,formats:_s(1954),source:lw},{id:"eastman-5247-1950",name:"Eastman Color Negative 5247 (1950)",kind:"negative",iso:16,formats:an(1950,1952),source:nn},{id:"eastman-5248-1952",name:"Eastman Color Negative 5248 (1952)",kind:"negative",iso:16,formats:an(1952,1959),source:nn},{id:"eastman-5250",name:"Eastman Color Negative 5250",kind:"negative",iso:32,formats:an(1959,1962),source:nn},{id:"eastman-5251",name:"Eastman Color Negative 5251",kind:"negative",iso:50,light:"tungsten",formats:an(1962,1968),source:nn},{id:"eastman-5254",name:"Eastman Color Negative 5254",kind:"negative",iso:100,light:"tungsten",formats:an(1968,1976),source:nn},{id:"eastman-5247-1974",name:"Eastman Color Negative II 5247 (1974)",kind:"negative",iso:64,formats:an(1974,1983),source:nn},{id:"eastman-5294",name:"Eastman High Speed Negative 5294",kind:"negative",iso:400,light:"tungsten",formats:an(1983),source:nn},{id:"eastman-5297",name:"Eastman High Speed Daylight 5297",kind:"negative",iso:250,formats:an(1986,1997),source:nn},{id:"eastman-5245",name:"Eastman EXR 50D 5245",kind:"negative",iso:50,formats:an(1989),source:nn}];class Gr{static byId(t){return Df.find(e=>e.id===t)}static forInstrument(t){return Df.filter(e=>e.formats.some(s=>s.format===t.filmFormat))}static gap(t,e,s){const i=t.formats.find(n=>n.format===e.filmFormat);if(!(!i||s===void 0)){if(s<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&s>i.to)return{kind:"after",to:i.to}}}static possible(t,e){return Gr.forInstrument(t).filter(s=>Gr.gap(s,t,e)===void 0)}static mediumOf(t,e){return!t||!e?t:{...t,kind:e.kind,iso:e.iso,monochrome:e.monochrome}}}class To{constructor(t){this.annex=t}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(t,e,s){let i;try{i=await this.annex}catch{return{status:"failed"}}const n=r=>Math.abs(r.lat-t.lat)<=To.SAME_PLACE_DEG&&Math.abs(r.lng-t.lng)<=To.SAME_PLACE_DEG,o=i.answers.find(r=>n(r)&&Math.abs(r.startMs-e)<=To.SAME_TIME_MS&&Math.abs(r.endMs-s)<=To.SAME_TIME_MS)??i.answers.find(r=>r.startMs<=e&&r.endMs>=s);return o?o.answer:{status:"failed"}}}const Il=7.5,Rl=9;class Pi{static cache=new Map;static load(t){let e=Pi.cache.get(t);return e||(e=fetch(t).then(s=>s.arrayBuffer()).then(s=>Pi.parse(s)),Pi.cache.set(t,e)),e}static upTo(t,e){const s=t.filter((a,o)=>o===0||t[o-1].magnitudeLimit<e);if(s.length<=1)return Pi.load(t[0].url);const i=s.map(a=>a.url).join(`
|
|
4995
|
-
`);let n=Pi.cache.get(i);return n||(n=Promise.all(s.map(a=>Pi.load(a.url))).then(a=>a.reduce((o,r)=>Pi.concat(o,r))),Pi.cache.set(i,n)),n}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),s=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*s,e),dec:new Float32Array(t,1*s,e),mag:new Float32Array(t,2*s,e),ci:new Float32Array(t,3*s,e)}}static concat(t,e){const s=(i,n)=>{const a=new Float32Array(i.length+n.length);return a.set(i,0),a.set(n,i.length),a};return{count:t.count+e.count,ra:s(t.ra,e.ra),dec:s(t.dec,e.dec),mag:s(t.mag,e.mag),ci:s(t.ci,e.ci)}}}class Gt{constructor(t){if(this.heights=t,t.length!==Gt.WIDTH*Gt.HEIGHT)throw new Error(`a lunar relief has ${Gt.WIDTH*Gt.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*Gt.SAMPLES_PER_DEGREE;static HEIGHT=180*Gt.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const s=Gt.SAMPLES_PER_DEGREE,i=(e%360+360)%360*s-.5,n=(90-t)*s-.5,a=Math.floor(i),o=Math.floor(n),r=i-a,c=n-o,h=(f,m)=>{const p=(f%Gt.WIDTH+Gt.WIDTH)%Gt.WIDTH,g=Math.min(Gt.HEIGHT-1,Math.max(0,m));return this.heights[g*Gt.WIDTH+p]},l=h(a,o)*(1-r)+h(a+1,o)*r,d=h(a,o+1)*(1-r)+h(a+1,o+1)*r;return(l*(1-c)+d*c)*Gt.UNIT_KM}static inBand(t,e){const s=Math.PI/180,i=Math.acos(Math.cos(t*s)*Math.cos(e*s))*180/Math.PI;return i>=Gt.BAND_FROM_DEG&&i<=Gt.BAND_TO_DEG}static withBump(t,e,s,i=.4){const n=new Int8Array(Gt.WIDTH*Gt.HEIGHT),a=Gt.SAMPLES_PER_DEGREE,o=Math.ceil(i*a),r=Math.floor(e*a),c=Math.floor((90-t)*a);for(let h=-o;h<=o;h++)for(let l=-o;l<=o;l++)Math.hypot(l,h)<=o&&(n[(c+h)*Gt.WIDTH+(r+l+Gt.WIDTH)%Gt.WIDTH]=Math.round(s/Gt.UNIT_KM));return new Gt(n)}static smooth(){return new Gt(new Int8Array(Gt.WIDTH*Gt.HEIGHT))}}class ii{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,s,i=ii.SAMPLES){const{s:n,u:a,w:o,distanceKm:r}=ii.frame(t,e),c=Math.PI/180,h=new Float32Array(i),l=Gt.REFERENCE_RADIUS_KM;for(let d=0;d<i;d++){const f=d/i*2*Math.PI,m=Math.cos(f),p=Math.sin(f),g=m*a[0]+p*o[0],M=m*a[1]+p*o[1],v=m*a[2]+p*o[2];let y=0;for(let w=ii.SEARCH_FROM_DEG;w<=ii.SEARCH_TO_DEG;w+=ii.SEARCH_STEP_DEG){const b=Math.cos(w*c),E=Math.sin(w*c),A=b*n[0]+E*g,S=b*n[1]+E*M,x=b*n[2]+E*v,T=Math.asin(Math.max(-1,Math.min(1,x)))/c,I=Math.atan2(S,A)/c,R=l+s.heightKm(T,I),O=Math.atan2(R*E,r-R*b);O>y&&(y=O)}h[d]=y/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(l/r)/c}}static frame(t,e){const s=new Zn(e.lat,e.lng,e.elevationM),i=En(t),n=$l(t,s,!1),a=new It(n.x-i.x,n.y-i.y,n.z-i.z,i.t),o=Math.hypot(a.x,a.y,a.z)*ii.AU_KM,r=ii.bodyFixed(t),c=r(a),h=Math.hypot(c[0],c[1],c[2]),l=[c[0]/h,c[1]/h,c[2]/h],d=h1(t,s),f=Gu(d),m=yn(d,new It(-a.x,-a.y,-a.z,i.t)),p=Math.asin(m.z/Math.hypot(m.x,m.y,m.z)),g=Math.atan2(-m.y,m.x),M=new It(-Math.sin(p)*Math.cos(g),Math.sin(p)*Math.sin(g),Math.cos(p),i.t),v=new It(-Math.sin(g),-Math.cos(g),0,i.t);return{s:l,u:r(yn(f,M)),w:r(yn(f,v)),distanceKm:o}}static surfacePoint(t,e,s,i){const{s:n,u:a,w:o}=ii.frame(t,e),r=Math.PI/180,c=[0,1,2].map(l=>Math.cos(s*r)*a[l]+Math.sin(s*r)*o[l]),h=[0,1,2].map(l=>Math.cos(i*r)*n[l]+Math.sin(i*r)*c[l]);return{latDeg:Math.asin(h[2])/r,lonDeg:Math.atan2(h[1],h[0])/r}}static radiusAt(t,e){const s=t.radiusDeg.length,i=(e/360*s%s+s)%s,n=Math.floor(i),a=i-n;return t.radiusDeg[n]*(1-a)+t.radiusDeg[(n+1)%s]*a}static uncoveredFraction(t,e,s){const i=t.radiusDeg.length,n=s.upDeg*s.upDeg+s.rightDeg*s.rightDeg;let a=0;for(let o=0;o<i;o++){const r=o/i*2*Math.PI,c=Math.cos(r),h=Math.sin(r),l=c*s.upDeg+h*s.rightDeg,d=l*l-n+e*e;if(d<=0)continue;const f=Math.sqrt(d),m=l+f;if(m<=0)continue;const p=Math.max(0,l-f),g=Math.max(p,t.radiusDeg[o]);m>g&&(a+=.5*(m*m-g*g))}return Math.min(1,Math.max(0,a*(2*Math.PI/i)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=x1(z.Moon,t),s=Math.PI/180,i=e.ra*15*s,n=e.dec*s,a=e.spin*s,o=(c,[h,l,d])=>[Math.cos(c)*h+Math.sin(c)*l,-Math.sin(c)*h+Math.cos(c)*l,d],r=(c,[h,l,d])=>[h,Math.cos(c)*l+Math.sin(c)*d,-Math.sin(c)*l+Math.cos(c)*d];return c=>o(a,r(Math.PI/2-n,o(Math.PI/2+i,[c.x,c.y,c.z])))}static subObserverPoint(t,e){const s=new Zn(e.lat,e.lng,e.elevationM),i=En(t),n=$l(t,s,!1),a=ii.bodyFixed(t)(new It(n.x-i.x,n.y-i.y,n.z-i.z,i.t)),o=Math.hypot(a[0],a[1],a[2]);return{latDeg:Math.asin(a[2]/o)*180/Math.PI,lonDeg:Math.atan2(a[1],a[0])*180/Math.PI}}}class Pr{static cache=new Map;static load(t){let e=Pr.cache.get(t);return e||(e=Pr.fetchRelief(t).catch(()=>{}),Pr.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let s=new Uint8Array(await e.arrayBuffer());if(s[0]===31&&s[1]===139){if(typeof DecompressionStream>"u")return;const i=new Blob([s]).stream().pipeThrough(new DecompressionStream("gzip"));s=new Uint8Array(await new Response(i).arrayBuffer())}return new Gt(new Int8Array(s.buffer,s.byteOffset,s.length))}}const id=Sn.catalog({en:()=>H(()=>import("./PerceptionMessages_en-B2O6DR64.js"),[],import.meta.url).then(u=>u.perceptionMessages_en),fr:()=>H(()=>import("./PerceptionMessages_fr-B59TnGBC.js"),[],import.meta.url).then(u=>u.perceptionMessages_fr),es:()=>H(()=>import("./PerceptionMessages_es-BmkP6OqD.js"),[],import.meta.url).then(u=>u.perceptionMessages_es),it:()=>H(()=>import("./PerceptionMessages_it-DPlxRmxu.js"),[],import.meta.url).then(u=>u.perceptionMessages_it)});class mh{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=mh.ID;messages=id;sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",kind:"choice",default:"normal",choices:[{id:"normal"},{id:"protan"},{id:"deutan"},{id:"tritan"}]},{id:"severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=mh.MATRICES[String(t.type)];if(!e)return Cs.NONE;const s=Number(t.severity??100),i=Math.max(0,Math.min(100,Number.isFinite(s)?s:100))/100;return{colorMatrix:e.map((a,o)=>Cs.IDENTITY[o]+(a-Cs.IDENTITY[o])*i),contrastGain:1}}}class nd{static ID="fatigue";id=nd.ID;messages=id;sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return Cs.NONE}}class ua{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=ua.ID;messages=id;sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",kind:"number",default:0,min:0,max:ua.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),s=Math.max(0,Math.min(ua.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(s===0)return Cs.NONE;const i=s/ua.MEASURED_LEVEL*ua.MEASURED_LOSS_DB;return{colorMatrix:Cs.IDENTITY,contrastGain:10**(-i/20)}}}const uw=u=>u.sources[0]??u.id,dw=ke.point("perception").provide(ke.BUILT_IN,[new mh,new ua,new nd].map(u=>({id:u.id,name:u.id,credit:uw(u),creditUrl:"https://ufoathome.org/docs/sources/",create:()=>u})));class da{static built=new WeakMap;static get ALL(){return dw.map(t=>{let e=da.built.get(t);return e||(e=t.create(),da.built.set(t,e)),e})}static byId(t){return da.ALL.find(e=>e.id===t)}static perceptionOf(t){return da.ALL.reduce((e,s)=>Cs.combine(e,s.perceive(t?.[s.id]??{})),Cs.NONE)}static compact(t){const e={},s=da.ALL;for(const[i,n]of Object.entries(t))!s.some(a=>a.id===i)&&Object.keys(n??{}).length>0&&(e[i]=n);for(const i of s){const n=t[i.id]??{},a=Object.fromEntries(i.settings.filter(o=>n[o.id]!==void 0&&n[o.id]!==o.default).map(o=>[o.id,n[o.id]]));Object.keys(a).length>0&&(e[i.id]=a)}return Object.keys(e).length>0?e:void 0}}class If{names;constructor(t){this.names=t??Sn.blank(),this.loaded=t!==void 0}loaded;body(t){return this.names.bodies[t]??t}star(t){return this.names.stars[t.name]??t.name}comet(t){return this.names.comets[t.id]??t.name}nova(t){return this.names.novae[t.id]??t.name}satelliteClass(t){return this.names.satelliteClasses[t.id]??t.name}shower(t){return this.names.showers[t.id]??t.name}lightRig(t){return this.names.lightRigs[t.id]??t.name}instrument(t){return this.names.instruments[t.id]??t.name}decorKind(t){return this.names.decorKinds[t]}point(t){return Da.point(t,this.loaded?this.names.compassPoints:void 0)}towards(t){return Da.towards(t,this.loaded?this.names:void 0)}}class Ci{static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const s=t.name??Ci.kind(t,e);return t.services?.length?`${s} — ${t.services.join(", ")}`:s}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,s,i){const{line:n}=t,a=[];n.name&&a.push(Ci.kind(n,e).toLocaleLowerCase(i)),a.push(n.tracks>1?e.tracks.replace("{count}",String(n.tracks)):e.singleTrack);const o=n.voltageV?Ci.voltage(n.voltageV,i):void 0;if(t.contactM!==void 0){const r=t.contactM.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:2});a.push((o?e.overheadVoltage.replace("{voltage}",o):e.overhead).replace("{height}",r))}else n.electrification==="third_rail"?a.push(o?e.thirdRailVoltage.replace("{voltage}",o):e.thirdRail):n.electrification==="none"&&a.push(e.notElectrified);return n.gaugeMm===Ci.METRE_GAUGE_MM?a.push(e.metreGauge):n.gaugeMm!==Ci.STANDARD_GAUGE_MM&&a.push(e.gauge.replace("{mm}",n.gaugeMm.toLocaleString(i))),a.push(e.distance.replace("{distance}",s(t.distanceM))),n.services?.length?`${Ci.name(n,e)}; ${a.join(", ")}`:`${Ci.name(n,e)} — ${a.join(", ")}`}}class kr{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,s=!0){const i=kr.resolve(t,e);if(this.url=i,!i||!s){this.release();return}this.element.src=i,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const s=new URL(t.trim(),e??location.href);return s.protocol!=="https:"&&s.protocol!=="http:"?void 0:s.origin===kr.PUBLISHED_ORIGIN&&kr.isDevelopmentHost(location.hostname)?location.origin+s.pathname:s.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}}class me{static OCTAVES=[63,125,250,500,1e3,2e3,4e3,8e3];static STANDARD={temperatureC:15,relativeHumidity:.7,pressureKPa:101.325};static REFERENCE_PRESSURE_KPA=101.325;static REFERENCE_TEMPERATURE_K=293.15;static TRIPLE_POINT_K=273.16;static speedOfSound(t){return 20.0468*Math.sqrt(t+273.15)}static absorptionDbPerKm(t,e=me.STANDARD){const s=e.temperatureC+273.15,i=me.REFERENCE_TEMPERATURE_K,n=e.pressureKPa/me.REFERENCE_PRESSURE_KPA,a=10**(-6.8346*(me.TRIPLE_POINT_K/s)**1.261+4.6151),o=e.relativeHumidity*100*a/n,r=n*(24+40400*o*(.02+o)/(.391+o)),c=n*(s/i)**-.5*(9+280*o*Math.exp(-4.17*((s/i)**(-1/3)-1))),h=t*t;return 8.686*h*(184e-13*(1/n)*Math.sqrt(s/i)+(s/i)**-2.5*(.01275*Math.exp(-2239.1/s)/(r+h/r)+.1068*Math.exp(-3352/s)/(c+h/c)))*1e3}static aWeightingDb(t){const e=t*t,s=12194**2*e*e/((e+20.6**2)*Math.sqrt((e+107.7**2)*(e+737.9**2))*(e+12194**2));return 20*Math.log10(s)+2}static sumDb(t){return 10*Math.log10(t.reduce((e,s)=>e+10**(s/10),0))}}const fw=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,mw=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Rf=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,pw=20,gw=1,Mw=7,vw=.35,Of=.4,Pf=40,kf=.5,yw=Math.SQRT2;class Aa{context;constructor(t){this.context=t}buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};around;aroundRequested={rms:0,shape:[]};level=1;share=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.gain,this.master.connect(t.destination)),this.master}get gain(){return this.level*this.share}setLevel(t){this.level=t,this.master&&(this.master.gain.value=this.gain)}setOutsideHeard(t){this.share=Math.min(1,Math.max(0,t)),this.master&&(this.master.gain.value=this.gain)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}qs.isLive(this.context)&&qs.unlock(this.context),this.applyAround()}setAround(t,e){const s=this.aroundRequested;s.rms===Math.max(0,t)&&s.shape.length===e.length&&s.shape.every((i,n)=>i===e[n])||(this.aroundRequested={rms:Math.max(0,t),shape:e},this.applyAround())}applyAround(){const t=this.context;if(!t)return;const{rms:e,shape:s}=this.aroundRequested,i=this.paused?0:e;if(i===0&&!this.around)return;const n=this.around??(this.around=this.buildAround(t)),a=t.currentTime;n.gain.gain.setTargetAtTime(i,a,kf),me.OCTAVES.forEach((o,r)=>{const c=Math.sqrt(Math.min(1,1.11*o/(t.sampleRate/2)))/Math.sqrt(3);n.bands[r].gain.setTargetAtTime((s[r]??0)/c,a,kf)})}buildAround(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*Mw),t.sampleRate),s=e.getChannelData(0);for(let p=0;p<s.length;p++)s[p]=Math.random()*2-1;const i=t.createBufferSource();i.buffer=e,i.loop=!0;const n=Math.floor(t.sampleRate*Pf),a=t.createBuffer(1,n,t.sampleRate),o=Array.from({length:Math.round(Pf*Of)},()=>Math.random()*2-1),r=a.getChannelData(0),c=t.sampleRate/Of;for(let p=0;p<n;p++){const g=p/c,M=Math.floor(g),v=g-M,y=v*v*(3-2*v);r[p]=o[M%o.length]*(1-y)+o[(M+1)%o.length]*y}const h=t.createBufferSource();h.buffer=a,h.loop=!0;const l=t.createGain();l.gain.value=vw;const d=t.createGain();d.gain.value=1,h.connect(l).connect(d.gain);const f=t.createGain();f.gain.value=0,d.connect(f).connect(this.output(t));const m=me.OCTAVES.map(p=>{const g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=p,g.Q.value=yw;const M=t.createGain();return M.gain.value=0,i.connect(g).connect(M).connect(d),M});return i.start(),h.start(),{sources:[i,h],nodes:[l,d,f,...m],bands:m,gain:f}}setAmbient(t,e,s){if(this.requested={type:t,intensity:e,windSpeed:s},!this.context)return;this.paused&&(t="none",e=0,s=0);const i=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=i==="hail"?Math.min(1,e*1.3+.2):i==="rain"?e:0,i!==this.ambientKey){this.ambientKey=i;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,i!=="none"&&this.startLoop(fw,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,r=>{this.ambientSource=r?.source,this.ambientGain=r?.gain,r&&(r.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(s/pw,1);const n=s>gw;if(n!==this.windActive){this.windActive=n;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,n&&this.startLoop(mw,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,r=>{this.windSource=r?.source,this.windGain=r?.gain,r&&(r.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:s,windSpeed:i}=this.requested;this.setAmbient(e,s,i),this.applyAround()}playThunder(){!this.context||this.paused||this.playOneShot(Rf,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const s=Math.min(1,Math.max(0,t)),i=e.createBufferSource();i.buffer=this.crackBuffer(e);const n=e.createBiquadFilter();n.type="lowpass",n.frequency.value=Aa.CRACK_CUTOFF_HZ;const a=e.createGain();a.gain.value=s,i.connect(n).connect(a).connect(this.output(e)),i.start(),this.playOneShot(Rf,s,Aa.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(t){if(this.crack?.sampleRate===t.sampleRate)return this.crack;const e=Math.round(t.sampleRate*Aa.CRACK_DECAY_S*6),s=t.createBuffer(1,e,t.sampleRate),i=s.getChannelData(0);for(let n=0;n<e;n++){const a=n/t.sampleRate;i[n]=(Math.random()*2-1)*Math.min(1,a/.005)*Math.exp(-a/Aa.CRACK_DECAY_S)}return this.crack=s,s}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0;for(const t of this.around?.sources??[])try{t.stop()}catch{}for(const t of this.around?.nodes??[])t.disconnect();this.around=void 0,qs.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,s,i){if(e!==s()){t?.source.stop();return}i(t)}async startLoop(t,e){const s=this.context;if(s)try{const i=await this.getBuffer(t),n=s.createBufferSource();n.buffer=i,n.loop=!0;const a=s.createGain();return a.gain.value=e,n.connect(a).connect(this.output(s)),n.start(),{source:n,gain:a}}catch(i){console.warn("Weather ambient sound failed to load, staying silent:",i);return}}async playOneShot(t,e,s=1){const i=this.context;if(i)try{const n=await this.getBuffer(t),a=i.createBufferSource();a.buffer=n,a.playbackRate.value=s;const o=i.createGain();o.gain.value=e,a.connect(o).connect(this.output(i)),a.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let s=this.buffers.get(t);return s||(s=fetch(t).then(i=>{if(!i.ok)throw new Error(`Audio fetch failed (${i.status}): ${t}`);return i.arrayBuffer()}).then(i=>e.decodeAudioData(i)),this.buffers.set(t,s)),s}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}const ww={rollingA:[83.1,89.2,87.7,93.1,100.1,96.7,86.8,76.2],rollingB:[30,41.5,38.9,25.7,32.5,37.2,39,40],propulsionA:[97.9,92.5,90.7,87.2,84.7,88,84.4,77.1],propulsionB:[-1.3,7.2,7.7,8,8,8,8,8]},bw={rollingA:[91.7,96.2,98.2,104.9,105.1,98.5,91.1,85.6],rollingB:[30,33.5,31.3,25.4,31.8,37.1,38.6,40.6],propulsionA:[108.8,104.2,103.5,102.9,102.6,98.5,93.8,87.5],propulsionB:[0,3,4.6,5,5,5,5,5]},Ol=70,Ew=55+10*Math.log10(2*Math.PI),Pl=5,Aw=2;class Ie{static vehiclePowerDbA(t,e){return me.sumDb(Ie.vehiclePowerBands(t,e).map((s,i)=>s+me.aWeightingDb(me.OCTAVES[i])))}static vehiclePowerBands(t,e){const s=t?bw:ww,i=Math.max(e,1);return me.OCTAVES.map((n,a)=>{const o=s.rollingA[a]+s.rollingB[a]*Math.log10(i/Ol),r=s.propulsionA[a]+s.propulsionB[a]*(i-Ol)/Ol;return me.sumDb([o,r])})}static dbA(t,e=!0){if(!Ln.says(t))return-1/0;const s=t.withinM??Ln.DEFAULT_WITHIN_M,i=Ln.DEFAULT_SPEED_KMH,n=[Ie.counted(t.cars,Ie.vehiclePowerDbA(!1,i),s,Pl),Ie.counted(t.trucks,Ie.vehiclePowerDbA(!0,i),s,Pl),e?Ie.counted(t.talking,Ew,s,Aw):-1/0,...(t.roads??[]).map(a=>Ie.road(a.distanceM,a.vehiclesPerMinute,a.trucksPerMinute??0,a.speedKmh??i))].filter(a=>Number.isFinite(a));return n.length>0?me.sumDb(n):-1/0}static vehicleShape(t){if(!Ln.says(t))return;const e=t.withinM??Ln.DEFAULT_WITHIN_M,s=Ln.DEFAULT_SPEED_KMH,i=c=>{const h=Ie.counted(c?t.trucks:t.cars,Ie.vehiclePowerDbA(c,s),e,Pl),l=(t.roads??[]).map(f=>{const m=Math.min(f.trucksPerMinute??0,f.vehiclesPerMinute);return c?Ie.road(f.distanceM,m,m,f.speedKmh??s):Ie.road(f.distanceM,f.vehiclesPerMinute-m,0,f.speedKmh??s)}),d=[h,...l].filter(Number.isFinite);return d.length>0?10**(me.sumDb(d)/10):0},n=i(!1),a=i(!0);if(n+a===0)return;const o=me.OCTAVES.map(()=>0);for(const[c,h]of[[n,!1],[a,!0]]){if(c===0)continue;const l=Ie.vehiclePowerBands(h,s),d=me.sumDb(l.map((f,m)=>f+me.aWeightingDb(me.OCTAVES[m])));l.forEach((f,m)=>o[m]+=c*10**((f-d)/10))}const r=Math.sqrt(o.reduce((c,h)=>c+h,0));return o.map(c=>Math.sqrt(c)/r)}static counted(t,e,s,i){if(!t)return-1/0;const n=Math.min(i,s*.99),a=t*Math.log(s/n)/(Math.PI*(s*s-n*n));return e+10*Math.log10(a)}static road(t,e,s,i){const n=Math.min(s,e),a=(r,c)=>r>0?Ie.vehiclePowerDbA(c,i)+10*Math.log10(r/(1e3*Math.max(i,1))):-1/0,o=me.sumDb([a((e-n)*60,!1),a(n*60,!0)].filter(Number.isFinite));return Number.isFinite(o)?o-10*Math.log10(Math.PI*Math.max(t,1)):-1/0}}class jt{static BASE_DB_A=30;static OUTDOOR_SHAPE_DB=[-12,-7,-5,-5,-7,-11,-17,-25];static HEADROOM_DB=10.5;static AROUND_BED_PLAYED=!1;static WIND_DB_A=[[0,10],[1,28],[2,36],[3,40],[5,46],[8,52],[12,58],[20,66]];static RAIN_DB_A=[[0,0],[.1,42],[.3,50],[.6,58],[1,65]];static BED_RMS=.2;static MINIMUM_REFERENCE=.008;static WIND_BED_MIN_MS=1;static WIND_BED_FULL_MS=20;static dbA(t,e){const s=[jt.BASE_DB_A,jt.along(jt.WIND_DB_A,t.windSpeed),Ie.dbA(e)].filter(Number.isFinite);return(t.precipitationType==="rain"||t.precipitationType==="hail")&&s.push(jt.along(jt.RAIN_DB_A,t.precipitationIntensity)),10*Math.log10(s.filter(i=>i>0).reduce((i,n)=>i+10**(n/10),0))}static bedVolume(t){const e=t.windSpeed>jt.WIND_BED_MIN_MS?Math.min(t.windSpeed/jt.WIND_BED_FULL_MS,1):0,s=t.precipitationType==="hail"?Math.min(1,t.precipitationIntensity*1.3+.2):t.precipitationType==="rain"?t.precipitationIntensity:0;return Math.hypot(e,s)}static referenceAmplitude(t,e){return Math.max(Math.hypot(jt.BED_RMS*jt.bedVolume(t),jt.aroundReference(e)),jt.MINIMUM_REFERENCE)}static aroundReference(t){const e=Ie.dbA(t);return!Number.isFinite(e)||e<=jt.BASE_DB_A?0:jt.MINIMUM_REFERENCE*10**((e-jt.BASE_DB_A)/20)}static aroundBedRms(t){if(!jt.AROUND_BED_PLAYED)return 0;const e=Ie.dbA(t,!1);return!Number.isFinite(e)||e<=jt.BASE_DB_A?0:Math.min(jt.BED_RMS,jt.MINIMUM_REFERENCE*10**((e-jt.BASE_DB_A-jt.HEADROOM_DB)/20))}static bedPlays(t,e){return jt.bedVolume(t)>0||jt.aroundBedRms(e)>0}static shapeDb(t,e){const s=10**(jt.dbA(t,e)/10),i=Ie.dbA(e,!1),n=Number.isFinite(i)?10**(i/10):0,a=Math.max(0,s-n),o=jt.OUTDOOR_SHAPE_DB,r=10**(me.sumDb(o)/10),h=Ie.vehicleShape(e)?.map((m,p)=>m*m*10**(me.aWeightingDb(me.OCTAVES[p])/10)),l=h?.reduce((m,p)=>m+p,0)??1,d=me.OCTAVES.map((m,p)=>a*10**(o[p]/10)/r+(h?n*h[p]/l:0)),f=d.reduce((m,p)=>m+p,0);return d.map(m=>10*Math.log10(m/f))}static aroundBedShape(t){return Ie.vehicleShape(t)}static along(t,e){if(e<=t[0][0])return t[0][1];for(let s=1;s<t.length;s++)if(e<=t[s][0]){const[i,n]=t[s-1],[a,o]=t[s];return n+(o-n)*(e-i)/(a-i)}return t[t.length-1][1]}}class ln{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:s}=t,[i,n]=this.perifocalAxes(),a=Math.sqrt(ln.SUN_GM_AU3_PER_DAY2*(1+e)/s);this.perihelionPosition=this.scale(i,s),this.perihelionVelocity=this.scale(n,a),this.inverseSemiMajorAxis=(1-e)/s}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,s=this.universalAnomaly(e),i=this.inverseSemiMajorAxis*s*s,n=this.elements.perihelionAu,a=1-s*s/n*ln.stumpffC(i),o=e-s*s*s/Math.sqrt(ln.SUN_GM_AU3_PER_DAY2)*ln.stumpffS(i);return{x:a*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:a*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:a*this.perihelionPosition.z+o*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),s=Math.sqrt(ln.SUN_GM_AU3_PER_DAY2)*Math.abs(t),i=o=>{const r=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*ln.stumpffS(r)+c*o};let n=Math.max(1,s/this.elements.perihelionAu);for(;i(n)<s;)n*=2;let a=0;for(let o=0;o<ln.MAX_ITERATIONS&&n-a>1e-13*Math.max(1,n);o++){const r=(a+n)/2;i(r)<s?a=r:n=r}return e*(a+n)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,s=this.elements.inclinationDeg*Math.PI/180,i=Math.cos(t),n=Math.sin(t),a=Math.cos(e),o=Math.sin(e),r=Math.cos(s),c=Math.sin(s);return[{x:i*a-n*o*r,y:n*a+i*o*r,z:o*c},{x:-i*o-n*a*r,y:-n*o+i*a*r,z:a*c}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const s=Math.sqrt(t);return(s-Math.sin(s))/(s*s*s)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const Tp=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class Sw{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return Tp.filter(s=>Math.abs(e-s.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(s=>this.appearanceOf(s,t,e)).sort((s,i)=>s.magnitude-i.magnitude)[0]}static appearanceOf(t,e,s){const i=Kt(e),n=this.earthPositionAt(i),a=this.apparentPositionOf(t,2451545+i.tt,n),o=this.subtract(a,n),r=this.length(a),c=this.length(o),h=this.tailEndAt(t,a,n,r,i,e,s),l=this.horizontalOf(o,i,e,s);return{apparition:t,position:l,...h,heliocentricDistanceAu:r,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},n)),magnitude:this.magnitudeAt(t,r,c)}}static magnitudeAt(t,e,s){const i=t.absoluteMagnitude+5*Math.log10(s)+2.5*t.activityExponent*Math.log10(e);return Math.max(i,t.peakMagnitude)}static tailEndAt(t,e,s,i,n,a,o){if(t.tailLengthAu===void 0)return{};const r=1+t.tailLengthAu/i,c=this.subtract({x:e.x*r,y:e.y*r,z:e.z*r},s),h=this.subtract(e,s);return{tailEnd:this.horizontalOf(c,n,a,o),tailLengthDeg:this.angleBetween(h,c)}}static apparentPositionOf(t,e,s){const i=this.orbitOf(t);let n=i.positionAt(e);for(let a=0;a<2;a++){const o=this.length(this.subtract(n,s))/this.LIGHT_SPEED_AU_PER_DAY;n=i.positionAt(e-o)}return n}static horizontalOf(t,e,s,i){const n=yn(a1(),new It(t.x,t.y,t.z,e)),a=yn(Rm(e),n),o=$l(e,new Zn(i.lat,i.lng,i.elevationM),!0),r=new It(a.x-o.x,a.y-o.y,a.z-o.z,e),c=xh(r);return Wu(c.ra,c.dec,s,i)}static earthPositionAt(t){return yn(n1(),qn(z.Earth,t))}static julianDayOf(t){return 2451545+Kt(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const s=new ln(t.orbit);return this.orbits.set(t.id,s),s}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const s=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,s)))*180/Math.PI}}const kl=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class Lf{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return kl.filter(s=>this.magnitudeAt(s,e)!==void 0)}static appearancesAt(t,e){const s=this.julianDayOf(t),i=[];for(const n of kl){const a=this.magnitudeAt(n,s);a!==void 0&&i.push({outburst:n,position:Mi.ofJ2000(n.raHours,n.decDeg,t,e),magnitude:a})}return i.sort((n,a)=>n.magnitude-a.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return kl.find(e=>e.id===t)}static magnitudeAt(t,e){const s=t.lightCurve,i=e-t.startJd;if(s.length===0||i<s[0][0]||i>s[s.length-1][0])return;let n=1;for(;n<s.length-1&&s[n][0]<i;)n++;const[a,o]=s[n-1]??s[0],[r,c]=s[n]??s[0];if(r===a)return o;const h=Math.min(1,Math.max(0,(i-a)/(r-a)));return o+h*(c-o)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const xw=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],ph=6.5;class Ll{static activeAt(t){return xw.flatMap(e=>{const s=this.nearness(e,t);return s<=0?[]:[{shower:e,zhr:e.peakZhr*s,nearness:s}]})}static nearness(t,e){const s=this.dayOfYear(e),i=this.dayOfYear(this.asDate(t.start)),n=this.dayOfYear(this.asDate(t.peak)),a=this.dayOfYear(this.asDate(t.end)),o=this.wrappedDelta(s,n),r=this.wrappedDelta(n,i),c=this.wrappedDelta(a,n);return o<0?o<-r?0:1+o/r:o>0?o>c?0:1-o/c:1}static observedRatePerHour(t,e,s,i=ph){if(e<=0)return 0;const n=ph-i;return t*Math.sin(e*Math.PI/180)/Math.pow(s,n)}static radiantPosition(t,e,s){return Mi.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,s)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const s=t-e;return s>182?s-365:s<-182?s+365:s}}class Me{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const s=Kt(t),i=new bh(0,_g(t).elon-90,1),n=yn(l1(s),Vu(i,s)),a=xh(n);return Wu(a.ra,a.dec,t,e)}static observedRatePerHour(t,e=ph){const s=Me.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),i=ph-e;return(Me.QUIET_RATE_PER_HOUR+s)/Math.pow(Me.POPULATION_INDEX,i)}static schedule(t){const e=new Ih(t.seed^1542469173);return ni.schedule(t).map(s=>{const i=Me.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),n=s.fromRadiantDeg*Math.PI/180,a=Me.turnAround(i,e.between(0,360)),o={x:i.x*Math.cos(n)+a.x*Math.sin(n),y:i.y*Math.cos(n)+a.y*Math.sin(n),z:i.z*Math.cos(n)+a.z*Math.sin(n)};return{...s,radiant:Me.toHorizontal(o),bearingDeg:Me.bearingFrom(o,i)}})}static turnAround(t,e){const[s,i]=Me.basisAround(t),n=e*Math.PI/180;return{x:s.x*Math.cos(n)+i.x*Math.sin(n),y:s.y*Math.cos(n)+i.y*Math.sin(n),z:s.z*Math.cos(n)+i.z*Math.sin(n)}}static bearingFrom(t,e){const[s,i]=Me.basisAround(t),n=t.x*e.x+t.y*e.y+t.z*e.z,a=Me.normalise({x:e.x-t.x*n,y:e.y-t.y*n,z:e.z-t.z*n});return(Math.atan2(a.x*i.x+a.y*i.y+a.z*i.z,a.x*s.x+a.y*s.y+a.z*s.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},s=Me.normalise(Me.cross(t,e));return[s,Me.normalise(Me.cross(t,s))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=Me.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),s=Me.turnAround(e,t.bearingDeg),i=t.fromRadiantDeg*Math.PI/180;return Me.toHorizontal({x:e.x*Math.cos(i)+s.x*Math.sin(i),y:e.y*Math.cos(i)+s.y*Math.sin(i),z:e.z*Math.cos(i)+s.z*Math.sin(i)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,s=t.azimuthDeg*Math.PI/180,i=Math.cos(e);return{x:i*Math.sin(s),y:Math.sin(e),z:-i*Math.cos(s)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const Pu="https://ufoathome.org/tle/index.json";class es{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??es.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(Pu)||t.push(Pu),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${es.FIRST_SNAPSHOT}T00:00:00Z`)-es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS;if(t.getTime()<e)return!1;const s=await this.loadIndex();return s?Object.values(s.index.kinds).some(i=>t.getTime()>=Date.parse(i.from)-es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS&&t.getTime()<=Date.parse(i.to)+es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:s,base:i}=e,n=[],a=[];for(const o of Object.keys(s.kinds)){const r=await this.kindAt(o,t,s,i);n.push(...r),a.push(this.coverageOf(o,t,s,r.length>0))}return{objects:n,coverage:a,credit:s.credit,creditUrl:s.source}}async kindAt(t,e,s,i){const n=e.getTime(),a=s.binDays*es.DAY_MS,o=Math.floor(n/a),r=n-o*a<a/2?o-1:o+1,c=new Set(s.kinds[t].bins),h=[o,r].map(p=>new Date(p*a).toISOString().slice(0,10)).filter(p=>c.has(p));if(h.length===0)return[];const[l,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,i).href),...h.map(p=>this.binary(new URL(`${t}/${p}.bin`,i).href))]),f=new Map;for(const p of d)for(const g of es.decode(p,s.recordBytes)){const M=f.get(g.norad);(!M||Math.abs(g.epochMs-n)<Math.abs(M.epochMs-n))&&f.set(g.norad,g)}const m=[];for(const p of f.values()){const g=Math.abs(p.epochMs-n)/es.DAY_MS;if(g>es.MAX_ELEMENT_AGE_DAYS)continue;const M=l[p.norad]??{name:String(p.norad)};M.launch&&Date.parse(`${M.launch}T00:00:00Z`)>n||m.push({norad:p.norad,name:M.name,kind:t,launch:M.launch,stdMag:M.stdMag,elements:p,ageDays:g})}return m}coverageOf(t,e,s,i){const{from:n,to:a}=s.kinds[t],o=e.getTime(),r=es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS,c=i?"covered":o<Date.parse(n)-r?"before":o>Date.parse(a)+r?"after":"gap";return{kind:t,status:c,from:n,to:a}}static decode(t,e){const s=new DataView(t),i=[];for(let n=0;n+e<=t.byteLength;n+=e)i.push({norad:s.getUint32(n,!0),epochMs:s.getFloat64(n+4,!0),bstar:s.getFloat32(n+12,!0),inclinationDeg:s.getFloat32(n+16,!0),raanDeg:s.getFloat32(n+20,!0),eccentricity:s.getFloat32(n+24,!0),argOfPerigeeDeg:s.getFloat32(n+28,!0),meanAnomalyDeg:s.getFloat32(n+32,!0),meanMotion:s.getFloat64(n+36,!0)});return i}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let s=this.files.get(t);return s||(s=this.fetchImpl(t).then(i=>{if(!i.ok)throw new Error(`${t}: ${i.status}`);return e(i)}),s.catch(()=>this.files.delete(t)),this.files.set(t,s)),s}}const e5=Object.freeze(Object.defineProperty({__proto__:null,TleArchive:es,UFOATHOME_TLE_INDEX_URL:Pu},Symbol.toStringTag,{value:"Module"}));class Tw{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const s=he.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?s:Math.max(this.lowerM,s)}if(e.inFrontM!==void 0){const s=he.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?s:Math.min(this.upperM,s)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:he.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:he.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Ra{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*Ra.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const s=Ra.degOver(t)/e;return s<1?1:Math.min(Ra.MAX_INSTANTS,Math.max(2,Math.ceil(s)))}static MAX_INSTANTS=64}class ss{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return Ra.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return ss.visualAidGrasp(t,e.focalLengthMm);const s=e.exposureSeconds??t.exposureSeconds,i=e.fNumber??t.fNumber;if(s===void 0||i===void 0||!(s>0)||!(i>0))return ss.EYE;const n=e.focalLengthMm??t.frame?.focalLengthMm??ss.UNKNOWN_CAMERA_FOCAL_MM,a=n/i,o=ss.resolutionArcsec(t,n,a);return{apertureMm:a,exposureSeconds:Math.min(s,ss.trailLimitedSeconds(o)),resolutionArcsec:o}}static visualAidGrasp(t,e){const s=t.visualAid,i=ss.EYE,n=e??t.frame?.focalLengthMm,a=s.magnification??(n!==void 0&&s.eyepieceFocalMm?n/s.eyepieceFocalMm:1),o=Math.min(s.apertureMm,i.apertureMm*a);return{apertureMm:Math.max(o,i.apertureMm),exposureSeconds:i.exposureSeconds,resolutionArcsec:i.resolutionArcsec/Math.max(1,Math.min(a,s.apertureMm/i.apertureMm))}}static resolutionArcsec(t,e,s){const n=(t.detailUm??ss.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*ss.ARCSEC_PER_RADIAN,a=1.22*ss.WAVELENGTH_M/(s/1e3)*ss.ARCSEC_PER_RADIAN;return Math.max(n,a)}static trailLimitedSeconds(t){return t/ss.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const s=ss.graspOf(t,e),i=ss.EYE,n=(s.apertureMm/i.apertureMm)**2,a=s.exposureSeconds/i.exposureSeconds,o=(i.resolutionArcsec/s.resolutionArcsec)**2;return 1.25*Math.log10(n*a*o)}static gainFor(t,e){const s=e.fieldOfViewDeg===void 0?void 0:je.focalLengthMmFor(t,e.fieldOfViewDeg);return ss.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:s,exposureSeconds:e.exposureSeconds})}}const Nf=111320,lr=Math.PI/180,Dw=1.02,Iw=1;class Lr{static of(t,e){const s=Lr.sightings(t,e);if(s.length<2)return;const i=Lr.baseline(s);if(!i)return;const{near:n,far:a,closedM:o}=i,r=Math.tan(a.widthDeg/2*lr)===0?0:Math.tan(n.widthDeg/2*lr)/Math.tan(a.widthDeg/2*lr);if(r<Dw)return;const c=o/(r-1),h=he.sizeMAt(c,n.widthDeg),l=s.map(d=>({t:d.t,m:he.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:l,nearestM:Math.min(...l.map(d=>d.m)),fromT:a.t,toT:n.t,closedM:o}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(s=>{const i=s.shapes.find(o=>o.sourceId===e)?.shape,n=i?.angular?.widthDeg,a=pt(t,s.t);return n===void 0||n<=0||a?.lat===void 0||a.lng===void 0?[]:[{t:s.t,widthDeg:n,lat:a.lat,lng:a.lng,sightAzimuthDeg:i?.aim?.azimuthDeg??a.headingDeg}]}).sort((s,i)=>s.t-i.t)}static baseline(t){let e;for(const s of t)for(const i of t){if(s.t>=i.t)continue;const n=Lr.closedAlongSight(s,i),[a,o,r]=n>=0?[i,s,n]:[s,i,-n];r<Iw||a.widthDeg<=o.widthDeg||(!e||r>e.closedM)&&(e={near:a,far:o,closedM:r})}return e}static closedAlongSight(t,e){const s=(e.lat-t.lat)*Nf,i=(e.lng-t.lng)*Nf*Math.cos(t.lat*lr),n=(t.sightAzimuthDeg??0)*lr;return s*Math.cos(n)+i*Math.sin(n)}}class ws{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:ws.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:ws.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:ws.atLeastNearest(t.derivedM),basis:"derived"};const e=ws.largest(t.range?.minM,t.crossing?.behindM),s=ws.smallest(t.range?.maxM,t.crossing?.inFrontM),i=e===void 0?void 0:e*ws.MARGIN,n=s===void 0?void 0:s/ws.MARGIN;return i!==void 0&&n!==void 0?{distanceM:ws.atLeastNearest(i<=n?Math.sqrt(i*n):i),basis:"bounded"}:i!==void 0?{distanceM:ws.atLeastNearest(i),basis:"bounded"}:n!==void 0&&n<ws.CONVENTIONAL_M?{distanceM:ws.atLeastNearest(n),basis:"bounded"}:{distanceM:ws.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(ws.NEAREST_M,t)}static largest(...t){const e=t.filter(s=>s!==void 0&&s>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(s=>s!==void 0&&s>0);return e.length===0?void 0:Math.min(...e)}}class X{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=4;static DEFAULT_CRUMBLING={perS:1.2,lifeS:4,magnitudeDrop:3,dropBack:.3,spreadKmS:1,sinkKmS:.6,trainS:2.5};static DEFAULT_BURST={perS:12,lifeS:3.5,magnitudeDrop:3.5,dropBack:.5,spreadKmS:1.5,sinkKmS:.9,trainS:2};static FLARE_MAGNITUDES=.5;static shedsOf(t){return t.sheds?t.sheds:[X.DEFAULT_CRUMBLING,...X.flareBursts(t)]}static flareBursts(t){const e=t.lightCurve??[],s=[];for(let i=1;i<e.length-1;i++){const n=e[i];e[i-1].absoluteMagnitude-n.absoluteMagnitude<X.FLARE_MAGNITUDES||e[i+1].absoluteMagnitude-n.absoluteMagnitude<X.FLARE_MAGNITUDES||s.push({...X.DEFAULT_BURST,fromT:n.t-1e3,untilT:n.t+1500})}return s}static FADE_MS=1e3;static FADED_MAGNITUDE=8;static TRAIN_POINTS=8;static leadAt(t,e){const s=t.track;if(s.length<2||e<s[0].t||e>s[s.length-1].t)return;let i=0;for(;i<s.length-2&&s[i+1].t<e;)i++;const n=s[i],a=s[i+1],o=a.t-n.t,r=o>0?(e-n.t)/o:0,[c,h]=X.alongGreatCircle(n,a,r);return{lat:c,lng:h,heightM:(n.altitudeKm+(a.altitudeKm-n.altitudeKm)*r)*1e3}}static mayDazzle(t){const e=Math.max(1,Math.min(...t.track.map(i=>i.altitudeKm))),s=5*Math.log10(e/X.STANDARD_DISTANCE_KM);return t.fragments.some(i=>Math.min(i.absoluteMagnitude,...(i.lightCurve??[]).map(a=>a.absoluteMagnitude))+s<=X.DAZZLING_MAGNITUDE)}static detonationsOf(t,e){const s=[];for(const i of t)i.fragments.forEach((n,a)=>{const o=X.piecesOf(i).find(c=>c.id===(n.id??String(a)));if(!o)return;const r=(n.lightCurve??[]).filter((c,h,l)=>(h===0||l[h-1].absoluteMagnitude>=c.absoluteMagnitude)&&(h===l.length-1||l[h+1].absoluteMagnitude>c.absoluteMagnitude)).map(c=>({t:c.t,magnitude:c.absoluteMagnitude}));r.push({t:o.untilT,magnitude:o.magnitudeAt(o.untilT)});for(const c of r){if(c.magnitude>X.DETONATING_MAGNITUDE||c.t<o.fromT||c.t>o.untilT)continue;const h=X.pieceAt(i,o,c.t);if(!h||h.heightM>X.AUDIBLE_BELOW_KM*1e3||s.some(d=>d.flashT===c.t&&d.reentryId===i.id))continue;const l=X.seenFrom(e,h).distanceKm;s.push({reentryId:i.id,flashT:c.t,t:c.t+l/X.SOUND_KM_S*1e3,distanceKm:l,loudness:Math.min(1,(.3+(X.DETONATING_MAGNITUDE-c.magnitude)/15)*Math.min(1,30/l))})}});return s.sort((i,n)=>i.t-n.t)}static DETONATING_MAGNITUDE=-12;static AUDIBLE_BELOW_KM=50;static SOUND_KM_S=.31;static DAZZLING_MAGNITUDE=-11;static absoluteMagnitudeAt(t,e){const s=t.lightCurve;if(!s||s.length===0)return t.absoluteMagnitude;if(e<=s[0].t)return s[0].absoluteMagnitude;for(let i=1;i<s.length;i++){const n=s[i-1],a=s[i];if(e<=a.t)return n.absoluteMagnitude+(a.absoluteMagnitude-n.absoluteMagnitude)*(e-n.t)/Math.max(a.t-n.t,1)}return s[s.length-1].absoluteMagnitude}static viewsAt(t,e,s){const i=[];for(const n of t)for(const a of X.piecesOf(n)){if(e<a.fromT||e>a.untilT)continue;const o=X.pieceAt(n,a,e);if(!o)continue;const r=X.seenFrom(s,o);if(r.altitudeDeg<0)continue;const c=Math.min(X.FADE_MS,(a.untilT-a.fromT)/4),h=c>0?Math.min(1,(e-a.fromT)/c,(a.untilT-e)/c):1,l=a.magnitudeAt(e)+5*Math.log10(r.distanceKm/X.STANDARD_DISTANCE_KM),d=l+(1-h)*Math.max(0,X.FADED_MAGNITUDE-l),f=[r];for(let m=1;m<=X.TRAIN_POINTS;m++){const p=Math.min(a.trainMs*m/X.TRAIN_POINTS,e-a.fromT),g=X.pieceAt(n,a,e-p);if(!g||(f.push(X.seenFrom(s,g)),p>=e-a.fromT))break}i.push({reentryId:n.id,fragmentId:a.id,head:r,magnitude:d,fade:h,color:a.color,train:f})}return i}static piecesOf(t){const e=X.pieces.get(t);if(e)return e;const s=t.track[0]?.t??0,i=t.track[t.track.length-1]?.t??0,n=[];return t.fragments.forEach((a,o)=>{const r=(a.lagS??0)*1e3,c={id:a.id??String(o),fromT:a.fromT??s,untilT:a.untilT??i,lagMsAt:()=>r,acrossKmAt:()=>0,belowKmAt:()=>0,magnitudeAt:h=>X.absoluteMagnitudeAt(a,h),color:a.color??X.DEFAULT_COLOR,trainMs:(a.trainS??X.DEFAULT_TRAIN_S)*1e3};n.push(c),X.shedsOf(a).forEach((h,l)=>n.push(...X.shedPieces(c,h,l)))}),X.pieces.set(t,n),n}static pieces=new WeakMap;static shedPieces(t,e,s=0){const i=e.fromT??t.fromT,n=Math.min(e.untilT??t.untilT,t.untilT);if(!(e.perS>0)||n<=i)return[];const a=Math.floor((n-i)/1e3*e.perS),o=e.spreadKmS??.3,r=e.sinkKmS??.3,c=e.trainS!==void 0?e.trainS*1e3:t.trainMs*(2/3),h=[];for(let l=0;l<a;l++){const d=A=>X.hash(`${t.id}/${s}/${l}/${A}`),f=i+(l+d(1))/e.perS*1e3,m=e.lifeS*(.4+1.2*d(2))*1e3,p=e.magnitudeDrop*(.5-.5*Math.log(1-.999*d(3))),g=e.dropBack*(.5+d(4)),M=o*(2*d(5)-1),v=r*(.5+d(6)),y=t.lagMsAt(f),w=t.acrossKmAt(f),b=t.belowKmAt(f),E=A=>Math.max(0,A-f)/1e3;h.push({id:`${t.id}.${s}.${l}`,fromT:f,untilT:Math.min(f+m,X.endOf(t)),lagMsAt:A=>y+1e3*X.lagOfBraking(2*g,E(A)),acrossKmAt:A=>w+M*E(A),belowKmAt:A=>b+v*E(A),magnitudeAt:A=>t.magnitudeAt(Math.min(A,t.untilT))+p,color:t.color,trainMs:c})}return h}static lagOfBraking(t,e){return t<=0||e<=0?0:e-(1-Math.exp(-t*e))/t}static endOf(t){return t.untilT}static hash(t){let e=2166136261;for(let s=0;s<t.length;s++)e^=t.charCodeAt(s),e=Math.imul(e,16777619);return(e>>>0)/4294967296}static pieceAt(t,e,s){const i=s-e.lagMsAt(s),n=X.leadAt(t,i);if(!n)return;const a=e.acrossKmAt(s),o=n.heightM-e.belowKmAt(s)*1e3;if(a===0)return{...n,heightM:o};const r=X.leadAt(t,i-1e3)??n;return{...X.across(r,n,a),heightM:o}}static across(t,e,s){const i=X.DEG,n=t.lat*i,a=e.lat*i,o=(e.lng-t.lng)*i,r=Math.atan2(Math.sin(o)*Math.cos(a),Math.cos(n)*Math.sin(a)-Math.sin(n)*Math.cos(a)*Math.cos(o))+Math.PI/2,c=s/6371,h=Math.asin(Math.sin(a)*Math.cos(c)+Math.cos(a)*Math.sin(c)*Math.cos(r)),l=e.lng*i+Math.atan2(Math.sin(r)*Math.sin(c)*Math.cos(a),Math.cos(c)-Math.sin(a)*Math.sin(h));return{lat:h/i,lng:l/i}}static seenFrom(t,e){const s=X.ecef(t),i=X.ecef(e),n=i[0]-s[0],a=i[1]-s[1],o=i[2]-s[2],r=t.lat*X.DEG,c=t.lng*X.DEG,h=-Math.sin(c)*n+Math.cos(c)*a,l=-Math.sin(r)*Math.cos(c)*n-Math.sin(r)*Math.sin(c)*a+Math.cos(r)*o,d=Math.cos(r)*Math.cos(c)*n+Math.cos(r)*Math.sin(c)*a+Math.sin(r)*o,f=Math.hypot(h,l,d);return{altitudeDeg:Math.asin(d/f)/X.DEG,azimuthDeg:(Math.atan2(h,l)/X.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*X.DEG,s=t.lng*X.DEG,i=Math.sin(e),n=X.A/Math.sqrt(1-X.E2*i*i);return[(n+t.heightM)*Math.cos(e)*Math.cos(s),(n+t.heightM)*Math.cos(e)*Math.sin(s),(n*(1-X.E2)+t.heightM)*i]}static alongGreatCircle(t,e,s){const i=h=>{const l=h.lat*X.DEG,d=h.lng*X.DEG;return[Math.cos(l)*Math.cos(d),Math.cos(l)*Math.sin(d),Math.sin(l)]},n=i(t),a=i(e),o=Math.max(-1,Math.min(1,n[0]*a[0]+n[1]*a[1]+n[2]*a[2])),r=Math.acos(o);let c;if(r<1e-12)c=n;else{const h=Math.sin((1-s)*r)/Math.sin(r),l=Math.sin(s*r)/Math.sin(r);c=[n[0]*h+a[0]*l,n[1]*h+a[1]*l,n[2]*h+a[2]*l]}return[Math.atan2(c[2],Math.hypot(c[0],c[1]))/X.DEG,Math.atan2(c[1],c[0])/X.DEG]}}class Do{static typed=new Map;static of(t){return Do.typed.get(t)}static set(t,e){const s=e.trim();s===""?Do.typed.delete(t):Do.typed.set(t,s)}static forget(){Do.typed.clear()}}class ad{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=ad.FIRST_DAY}}class Cf{constructor(t,e,s){this.citation=t,this.covers=e,this.load=s}loading;mayCover(t){return this.covers(t)}async between(t,e,s,i){try{return await(await this.provider()).between(t,e,s,i)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const Rw="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",Ow="Aircraft positions: Flightradar24 API (https://fr24api.flightradar24.com/)",_f="flightradar24",Pw=ke.point("aircraft").provide(ke.BUILT_IN,[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new Cf(Rw,u=>ad.mayCover(u),async()=>new(await H(async()=>{const{AdsbLolArchiveProvider:u}=await import("./AdsbLolArchiveProvider-Ck345V92.js");return{AdsbLolArchiveProvider:u}},__vite__mapDeps([48,1,2,3,4,5,6,7,8,9,10]),import.meta.url)).AdsbLolArchiveProvider)},{id:_f,name:"Flightradar24",credit:"Flightradar24, on your own subscription",creditUrl:"https://fr24api.flightradar24.com/",keyUrl:"https://fr24api.flightradar24.com/key-management",create:()=>new Cf(Ow,u=>u>=Date.UTC(2016,4,11)&&u<=Date.now(),async()=>new(await H(async()=>{const{Flightradar24Provider:u}=await import("./Flightradar24Provider-MzQcuUHn.js");return{Flightradar24Provider:u}},__vite__mapDeps([49,1,2,3,4,5,6,7,8,9,10]),import.meta.url)).Flightradar24Provider({token:()=>Do.of(_f)}))}]);class $e{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,s){const i=$e.positionAt(t,s);if(!i)return;const n=X.seenFrom(e,i.geo);if(!(n.altitudeDeg<0))return{track:t,sky:n,altitudeFt:i.altitudeFt,groundSpeedKt:i.groundSpeedKt,trackDeg:i.trackDeg,angularRateDegPerS:$e.angularRate(t,e,s)}}static viewsAt(t,e,s){return t.flatMap(i=>$e.seenFrom(i,e,s)??[])}static groundDistanceKm(t,e){const s=Math.PI/180,i=Math.sin((e.lat-t.lat)*s/2)**2+Math.cos(t.lat*s)*Math.cos(e.lat*s)*Math.sin((e.lng-t.lng)*s/2)**2;return 2*$e.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(i)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const s=t.points;if(s.length===0||e<s[0].t||e>s[s.length-1].t)return;let i=0;for(;i<s.length-1&&s[i+1].t<=e;)i++;const n=s[i],a=s[i+1]??n,o=a.t-n.t;if(o>$e.MAX_GAP_S*1e3)return;const r=o>0?(e-n.t)/o:0,c=n.altitudeFt+(a.altitudeFt-n.altitudeFt)*r,h=(a.lng-n.lng+540)%360-180;return{geo:{lat:n.lat+(a.lat-n.lat)*r,lng:$e.wrapLongitude(n.lng+h*r),heightM:c*$e.FT_TO_M},altitudeFt:c,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg}}static angularRate(t,e,s){const i=$e.positionAt(t,s-500),n=$e.positionAt(t,s+500);if(!i||!n)return;const a=$e.unit(X.seenFrom(e,i.geo)),o=$e.unit(X.seenFrom(e,n.geo)),r=Math.min(1,Math.max(-1,a[0]*o[0]+a[1]*o[1]+a[2]*o[2]));return Math.acos(r)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,s=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(s),Math.cos(e)*Math.cos(s),Math.sin(e)]}}const zf="https://ufoathome.org/fireballs/index.json";class Vi{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Vi.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(zf)||t.push(zf),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Vi.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Vi.mayCover(e))return;const s=await this.loadIndex();if(!s)return;const i=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...i].some(a=>a>=s.index.from&&a<=s.index.to)?(await Promise.all([...i].filter(a=>s.index.months.includes(a)).map(a=>this.monthOf(a,s.base)))).flat().filter(a=>a.t>=t&&a.t<=e):void 0}static seenFrom(t,e){const s=Vi.peakFraction(t),i={lat:t.from[0]+(t.to[0]-t.from[0])*s,lng:t.from[1]+(t.to[1]-t.from[1])*s,heightM:t.peakHeightKm*1e3},n=X.seenFrom(e,i);if(!(n.altitudeDeg<0))return{record:t,peak:n,magnitude:t.peakMagnitude+5*Math.log10(n.distanceKm/X.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const s=t.t-e,i=s+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:s,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:i,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Vi.COLOR,trainS:Vi.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let s=this.months.get(t);return s||(s=this.fetchImpl(new URL(`${t}.json`,e).href).then(i=>i.ok?i.json():[]).catch(()=>[]),this.months.set(t,s)),s}}class Mn{static FIRST_YEAR=1932;static AURORA_ID="gfz-kp";fetchImpl;baseUrls;years=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.baseUrls=t.baseUrls??Mn.defaultBaseUrls()}static defaultBaseUrls(){const t=[];typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/kp/",location.href).href);const e="https://ufoathome.org/kp/";return t.includes(e)||t.push(e),t}static mayCover(t){return new Date(t).getUTCFullYear()>=Mn.FIRST_YEAR}async between(t,e){if(!Mn.mayCover(e))return;const s=[],i=new Date(t).getUTCFullYear(),n=new Date(e).getUTCFullYear();for(let a=i;a<=n;a++){const o=await this.yearOf(a);if(!o)continue;const{stepMs:r,values:c}=o,h=Date.UTC(a,0,1),l=Math.max(0,Math.floor((t-h)/r)-1),d=Math.min(c.length-1,Math.ceil((e-h)/r));for(let f=l;f<=d;f++)c[f]>=0&&s.push({t:h+f*r+r/2,kp:c[f]/3})}return s.length>0?s:void 0}static asAurora(t,e){return{id:Mn.AURORA_ID,activity:t.map(s=>({t:s.t-e,kp:s.kp}))}}yearOf(t){let e=this.years.get(t);return e||(e=(async()=>{if(!(t<Mn.FIRST_YEAR))for(const s of this.baseUrls)try{const i=await this.fetchImpl(new URL(`${t}.json`,s).href);if(!i.ok)continue;const n=await i.json();return{stepMs:n.stepHours*36e5,values:n.values}}catch{}})(),this.years.set(t,e)),e}}class Gn{static POLES=[{year:1900,lat:78.7,lng:-68.8},{year:1925,lat:78.6,lng:-68.6},{year:1950,lat:78.5,lng:-68.8},{year:1975,lat:78.8,lng:-70},{year:1990,lat:79.2,lng:-71.1},{year:2e3,lat:79.6,lng:-71.6},{year:2010,lat:80.1,lng:-72.2},{year:2015,lat:80.4,lng:-72.6},{year:2020,lat:80.7,lng:-72.7},{year:2025,lat:80.8,lng:-72.7}];static poleAt(t){const e=t.getUTCFullYear()+t.getUTCMonth()/12,s=Gn.POLES;if(e<=s[0].year)return{lat:s[0].lat,lng:s[0].lng};for(let n=1;n<s.length;n++){if(e>s[n].year)continue;const a=s[n-1],o=s[n],r=(e-a.year)/(o.year-a.year);return{lat:a.lat+(o.lat-a.lat)*r,lng:a.lng+(o.lng-a.lng)*r}}const i=s[s.length-1];return{lat:i.lat,lng:i.lng}}static earthVector(t,e){const s=t*Math.PI/180,i=e*Math.PI/180;return[Math.cos(s)*Math.cos(i),Math.cos(s)*Math.sin(i),Math.sin(s)]}static latitudeOf(t,e,s){const i=Gn.poleAt(s),[n,a,o]=Gn.earthVector(i.lat,i.lng),[r,c,h]=Gn.earthVector(t,e);return Math.asin(Math.max(-1,Math.min(1,n*r+a*c+o*h)))*180/Math.PI}static axisAt(t,e,s){const i=Gn.poleAt(s),n=Gn.earthVector(i.lat,i.lng),a=t*Math.PI/180,o=e*Math.PI/180,r=[-Math.sin(o),Math.cos(o),0],c=[-Math.sin(a)*Math.cos(o),-Math.sin(a)*Math.sin(o),Math.cos(a)],h=[Math.cos(a)*Math.cos(o),Math.cos(a)*Math.sin(o),Math.sin(a)],l=(d,f)=>d[0]*f[0]+d[1]*f[1]+d[2]*f[2];return[l(n,r),l(n,h),-l(n,c)]}static localTime(t,e,s){const i=(h,l)=>h[0]*l[0]+h[1]*l[1]+h[2]*l[2],n=h=>{const l=i(h,e);return[h[0]-l*e[0],h[1]-l*e[1],h[2]-l*e[2]]},a=n(t),o=n(s),r=[e[1]*o[2]-e[2]*o[1],e[2]*o[0]-e[0]*o[2],e[0]*o[1]-e[1]*o[0]];return((12+Math.atan2(i(r,a),i(o,a))*12/Math.PI)%24+24)%24}static footLatitude(t,e,s=100,i=6371){const n=Math.cos(t*Math.PI/180),a=Math.sqrt(Math.min(1,n*n*(i+s)/(i+e)));return Math.sign(t)*(Math.acos(a)*180)/Math.PI}}Wm();const Dp="satellites-change",Ip="fireballs-change",Rp="references-change",Op="aircraft-change",Pp="rr0-confrontation",Ff="comet:",Hf="nova:",kw=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,Lw=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,Nw=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,Cw=-18,_w={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Rc={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class nt extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Lo,No,ma]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;flightMark;markedFlight;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;approaches={key:"",of:new Map};distanceHypotheses=new Map;depths=new Map;directionScratch=new D;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new es;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Vi;fireballs;static geomagneticArchive=new Mn;archivedAurora;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=Pw[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return nt.trafficRuntimeLoading??=H(()=>import("./trafficRuntime-BMTtwn7o.js"),__vite__mapDeps([50,42,51,1,7,6,2,3,4,5,8,9,10]),import.meta.url).then(t=>nt.trafficRuntime=t),nt.trafficRuntimeLoading.catch(()=>{nt.trafficRuntimeLoading=void 0}),nt.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new Aa;vehicleAudio=new Zd;aircraftAudio;vehicleHearing=new Zc;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;decorModelsAsked=new Set;thunderTimeoutId;handleFullscreenChange=()=>{this.resizeToStage(),this.hoverTooltip.hidden=!0;for(const t of[this.hoverTooltip,this.shadow.getElementById("credits-panel")])t&&typeof t.hidePopover=="function"&&t.matches(":popover-open")&&t.hidePopover();this.tooltipOver=document.fullscreenElement};handlePointerMove=t=>{if(this.lastHover={clientX:t.clientX,clientY:t.clientY,altKey:t.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&t.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=t.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(t,e){const s=this.ufoElement.canvasElement.getBoundingClientRect();if(s.width===0||s.height===0)return!0;const i=(t.clientX-s.left)/s.width*2-1,n=1-(t.clientY-s.top)/s.height*2;return this.sceneRenderer.ghostsReadableAt(i,n)?this.sceneRenderer.pickGhostAt(i,n)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>nt.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;tooltipOver=null;hoverAt(t){if(this.showCompassFor({hovered:!0}),this.holding||this.poster.up){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,s=e.getBoundingClientRect();if(s.width===0||s.height===0)return;const i=(t.clientX-s.left)/s.width*e.width,n=(t.clientY-s.top)/s.height*e.height;if(this.ufoElement.hasVisibleShapeAt(i,n)){this.hoverTooltip.hidden=!0;return}const a=(t.clientX-s.left)/s.width*2-1,o=-((t.clientY-s.top)/s.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(a,o))return;const r=this.pickAt(a,o,!0,t.altKey);r?this.showHoverTooltip(t,t.altKey&&r.detail?r.detail():r.name):this.hoverTooltip.hidden=!0,this.showGhostPath(r?.path,s)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const s=this.stageElement.getBoundingClientRect(),i=d=>({x:e.left-s.left+(d.x+1)/2*e.width,y:e.top-s.top+(1-d.y)/2*e.height}),n=i(t.from),a=i(t.to),o=i({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${s.width} ${s.height}`);const[r,c,h,l]=Array.from(this.ghostPath.children);for(const d of[r,c])d.setAttribute("x1",String(n.x)),d.setAttribute("y1",String(n.y)),d.setAttribute("x2",String(a.x)),d.setAttribute("y2",String(a.y));h.setAttribute("cx",String(o.x)),h.setAttribute("cy",String(o.y)),l.setAttribute("cx",String(a.x)),l.setAttribute("cy",String(a.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,s=!0,i=!1){const n=this.naming,a=n.names;if(i&&this.sceneRenderer.pickDropAt(t,e)){const E=a.ghostTooltip,A=E.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:A,detail:()=>E.dropDetail.replace("{name}",A)}}const o=this.sceneRenderer.pickBodyAt(t,e);if(o)return{kind:"sky",id:o,name:this.bodyName(o)};const r=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,c=r?this.interpretationShown?.bodies.find(E=>E.id===r):void 0,h=c?this.said.read(c.title)||this.explainedName(c.explains)||this.kindName(c):void 0;if(r!==void 0&&h)return{kind:"body",id:r,name:h};const l=this.skyEventPickAt(t,e,(E,A)=>!A.inSky);if(l)return l;const d=s?this.ghostPick(t,e):void 0;if(d)return d;if(this.sceneRenderer.pickAfterimageAt(t,e)){const E=this.naming.names.afterimageTooltip;return{kind:"afterimage",name:E.name,detail:()=>E.detail.replace("{name}",E.name)}}const f=this.pickDecorAt(t,e)??this.sceneRenderer.pickPeakAt(t,e),m=f?this.ufoElement.sighting.decor.find(E=>E.id===f):void 0;if(m){const E=this.said.read(m.title)||n.decorKind(m.kind);return{kind:"decor",id:m.id,name:E,detail:()=>this.decorTooltip(m,E)}}const p=this.sceneRenderer.pickRailwayAt(t,e);if(p){const E=a.railwayTooltip;return{kind:"railway",id:p.line.id,name:Ci.name(p.line,E),detail:()=>Ci.detail(p,E,A=>this.distanceText(A))}}const g=this.trafficTooltipAt(t,e);if(g)return{kind:"traffic",name:g};const M=this.skyEventPickAt(t,e,(E,A)=>A.inSky===!0&&!E.pickedAfterSatellites);if(M)return M;const v=this.sceneRenderer.pickSatelliteAt(t,e);if(v)return{kind:"satellite",name:a.satelliteTooltip.replace("{name}",v.name).replace("{mag}",v.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(v.heightKm).toLocaleString())};const y=this.skyEventPickAt(t,e,(E,A)=>A.inSky===!0&&E.pickedAfterSatellites===!0);if(y)return y;const w=this.sceneRenderer.pickOpticsAt(t,e);if(w){const E=a.opticsTooltips[w.id].replace("{angle}",String(Math.round(w.angleDeg??0)));return{kind:"optics",id:w.id,name:E.split(" — ")[0],detail:()=>E}}const b=this.sceneRenderer.pickStarAt(t,e);if(b){const E=b.star.mag,A=b.altitudeDeg,S=A<0?a.starTooltipBelow:a.starTooltip,x=n.star(b.star);return{kind:"star",name:x,detail:()=>S.replace("{name}",x).replace("{mag}",E.toLocaleString(void 0,{maximumFractionDigits:Math.abs(E)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(A))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const s=this.ufoElement.canvasElement,i={x:8/Math.max(1,s.clientWidth),y:8/Math.max(1,s.clientHeight)},n=`${Math.round(t/i.x)}:${Math.round(e/i.y)}`,a=performance.now(),o=this.ghostLights.get(n);if(o&&a-o.atMs<nt.GHOST_LIGHT_KEPT_MS)return o.light;let r=this.shiningDecorNear(t,e,2*Math.max(i.x,i.y)),c;if(!r)for(const[h,l]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+h*i.x,e+l*i.y,!1);if(d?.kind==="star")c??=d;else if(d){r=d;break}}return r??=this.shiningDecorNear(t,e,6*Math.max(i.x,i.y)),r??=c,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(n,{light:r??null,atMs:a}),r??null}ghostPick(t,e){const s=this.sceneRenderer.pickGhostAt(t,e);if(!s)return;const i=this.naming.names.ghostTooltip,n=s.beyond?{kind:"sky",id:"sun",name:this.bodyName("sun")}:this.lightOfGhost(s.source.x,s.source.y)??void 0,a=(n?.kind==="star"?n.name.split(" — ")[0]:n?.name)??i.unnamed,o=s.ghost,c=(wt.scatters(o)?i.halo:o.cause==="glass"?i.double:i.ghost).replace("{name}",a),h=o.scale<0?i.opposite:o.scale===1?i.around:i.sameSide;return{kind:"ghost",id:n?.id,name:c,detail:()=>i.detail.replace("{name}",c).replace("{cause}",i.causes[o.cause??"lens"]).replace("{where}",h),path:{from:{x:2*(o.offset?.[0]??0)+o.scale*s.source.x,y:2*(o.offset?.[1]??0)+o.scale*s.source.y},to:s.source}}}shiningDecorNear(t,e,s){let i;for(const n of this.ufoElement.sighting.decor){if(!(n.kind==="streetlight"||n.kind==="trafficlight"||(n.lights?.length??0)>0||n.kind==="vehicle"&&n.lit))continue;const o=this.sceneRenderer.decorScreenBox(n.id);if(!o)continue;const r=Math.hypot(Math.max(o.minX-t,0,t-o.maxX),Math.max(o.minY-e,0,e-o.maxY));if(r>s||i&&r>=i.distance)continue;const c=this.said.read(n.title)||this.naming.decorKind(n.kind);i={distance:r,pick:{kind:"decor",id:n.id,name:c}}}return i?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(s=>[s.t,s.weather.precipitationType,s.weather.precipitationIntensity,s.weather.windDirectionDeg,s.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const s=new pa(i=>{if(!wt.records(t.instrumentAt(i*1e3))||!wt.falling(t.lensAt(i*1e3)))return 0;const n=Ko(t,i*1e3),a=pt(t,i*1e3);return(n.precipitationAmount??1)*wt.impactRate(n,t.lens?.glass,a&&{headingDeg:a.headingDeg??0,pitchDeg:a.pitchDeg,windFromDeg:n.windDirectionDeg,windSpeedMS:n.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:s}}return this.glassWetting.wetting}glassWetting;get skyEventsShown(){return this.skyEventsOf(this.ufoElement.sighting)}skyEventsStartDate;skyEventsMerged;skyEventsOf(t){const e=t.skyEvents,s=this.fireballs?.reentries,i=e?.auroras?.length?void 0:this.archivedAurora?.aurora,n=this.skyEventsMerged;if(n&&n.stated===e&&n.fireballs===s&&n.aurora===i)return n.shown;let a=s?.length?{...e,reentries:[...e?.reentries??[],...s]}:e;return i&&(a={...a,auroras:[i]}),this.skyEventsMerged={stated:e,fireballs:s,aurora:i,shown:a},a}skyEventTexts=new Map;skyEventTextsLanguage;loadSkyEventTexts(t){const e=pr(pn.preferencesFor(this),gr);e!==this.skyEventTextsLanguage&&(this.skyEventTexts.clear(),this.skyEventTextsLanguage=e);for(const s of t)this.skyEventTexts.has(s)||s.messages.load(e).then(i=>{this.skyEventTextsLanguage===e&&this.skyEventTexts.set(s,i)},()=>{})}skyEventPickAt(t,e,s){const i=this.skyEventsShown;if(!i)return;const n=this.sceneRenderer.pickSkyEventAt(t,e,s),a=n?fu.map(d=>vn.of(d)).find(d=>d.key===n.kind):void 0,o=n&&a?vn.eventsOf(i,a).find(d=>d.id===n.id):void 0;if(!n||!a||!o)return;const r=this.skyEventTexts.get(a);if(!r){this.loadSkyEventTexts([a]);return}const c=this.said.read(o.title)||r.name,h=a.describe?.(o,n,{said:this.said,texts:r,name:c,distance:d=>this.distanceText(d)}),l=h?.detail??(n.distanceM!==void 0?`${c}, ${this.distanceText(n.distanceM)}`:void 0);return{kind:a.pickKind??"skyEvent",id:o.id,name:h?.name??c,...l!==void 0?{detail:()=>l}:{}}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const s=h=>h.toLocaleString(void 0,{maximumFractionDigits:h<10?1:0}),i=C.sizeOf(t),n=this.sceneRenderer.decorDistanceM(t.id),a=n===void 0?"":this.distanceText(n),r=this.naming.names.decorTooltip.replace("{name}",e).replace("{size}",`${s(i.widthM)} × ${s(i.lengthM)} × ${s(i.heightM)} m`),c=this.said.read(t.note);return c?`${r.replace("{distance}",a)}. ${c}`:r.replace("{distance}",a)}computedKinds=new Map;computedKindTexts=new Map;bodyModelKinds=new Map;showInterpretation(t){const e=Lh.kinds(),s=this.obstaclesOf(this.ufoElement.sighting.decor);this.interpretationObstacles=s;const{interpretation:i,kindOf:n}=Tn.expandWithKinds(t,e,{obstacles:s});if(this.interpretationAsked=t,this.interpretationShown=i,this.computedKinds=n,this.loadComputedKindTexts(),Tn.loaded(t,e))return;const a=Tn.load(t,e);this.sceneRenderer.holdUntil(a),a.then(()=>{this.interpretationAsked!==t||!Tn.loaded(t,e)||(this.showInterpretation(t),this.ufoElement.refreshSoundControls(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())})}interpretationAsked;interpretationObstacles=yd.NONE;obstaclesMadeOf;obstaclesOf(t){return this.obstaclesMadeOf?.decor!==t&&(this.obstaclesMadeOf={decor:t,obstacles:yd.of(t,e=>C.sizeOf(e))}),this.obstaclesMadeOf.obstacles}recomputeAmongNewDecor(){const t=this.interpretationAsked;!t||!Tn.computes(t,Lh.kinds())||this.obstaclesOf(this.ufoElement.sighting.decor).signature!==this.interpretationObstacles.signature&&(this.showInterpretation(t),this.ufoElement.refreshSoundControls())}computedInterpretation(t){const e=Lh.kinds(),s=Tn.loaded(t,e)?Promise.resolve():Tn.load(t,e),{interpretation:i,phenomenonOf:n}=Tn.expandWithKinds(t,e,{obstacles:this.obstaclesOf(this.ufoElement.sighting.decor)});return{interpretation:i??t,phenomenonOf:n,loaded:s}}loadComputedKindTexts(){const t=this.namesLanguage;if(t)for(const e of new Set(this.computedKinds.values()))this.computedKindTexts.has(e)||e.messages.load(t).then(s=>{t===this.namesLanguage&&this.computedKindTexts.set(e,s)}).catch(()=>{})}kindName(t){const e=this.computedKinds.get(t.id),s=e?this.computedKindTexts.get(e):void 0;if(s?.name)return s.name;const i=t.model.id;if(i==="figure")return this.naming.decorKind("entity");if(!i||t.model.url!==void 0)return;if(!this.bodyModelKinds.has(i)){this.bodyModelKinds.set(i,void 0),this.sceneRenderer.entryOfDecorModel(i).then(a=>this.bodyModelKinds.set(i,[a?.kind].flat()[0])).catch(()=>{});return}const n=this.bodyModelKinds.get(i);return n&&this.naming.decorKind(n)||void 0}explainedName(t){if(!t?.length)return;const e=this.ufoElement.sighting.timeline.allKeyframes,s=t.map(i=>{for(const n of e){const a=this.said.read(n.shapes.find(o=>o.sourceId===i)?.shape.title);if(a)return a}}).filter(i=>!!i);return s.length?s.join(", "):void 0}bodyName(t){const e=t.startsWith(Ff)?t.slice(Ff.length):void 0,s=e?Tp.find(n=>n.id===e):void 0;if(s)return this.naming.comet(s);const i=t.startsWith(Hf)?Lf.byId(t.slice(Hf.length)):void 0;return i?this.naming.nova(i):this.naming.body(t)}get naming(){return this.sceneNaming}sceneNaming=new If;namesLanguage;ready=Promise.resolve();async loadSceneNames(){const t=pr(pn.preferencesFor(this),gr);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await Np(t);t===this.namesLanguage&&(this.applySceneNaming(new If(e)),this.computedKindTexts.clear(),this.loadComputedKindTexts())}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let s=0;const i=(n,a)=>{n.setAttribute("aria-label",a),n.replaceChildren(),a.split(" ").forEach((o,r)=>{r>0&&n.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of o){const l=document.createElement("span");l.className="scene-loader-letter",l.style.setProperty("--i",String(s++)),l.textContent=h,c.append(l)}n.append(c),s++})};i(this.loaderNotVideo,t),s+=6,i(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t,t.loaded&&(this.creditsButton.title=t.names.credits,this.creditsButton.setAttribute("aria-label",t.names.credits),this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names.compassPoints))}showHoverTooltip(t,e){const s=this.hoverTooltip;if(s.textContent=e,s.hidden=!1,typeof s.showPopover=="function"){const l=document.fullscreenElement;s.matches(":popover-open")&&l!==this.tooltipOver&&s.hidePopover(),s.matches(":popover-open")||s.showPopover(),this.tooltipOver=l}const{innerWidth:i,innerHeight:n}=window,a=12,o=4,r=Math.min(t.clientX+a,i-s.offsetWidth-o),c=t.clientY+a,h=c+s.offsetHeight+o>n?t.clientY-a-s.offsetHeight:c;s.style.left=`${Math.max(o,r)}px`,s.style.top=`${Math.max(o,h)}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.showCompassFor({hovered:!1})};hearDetonations(t,e,s,i){const n=`${s.lat.toFixed(4)},${s.lng.toFixed(4)}`,a=this.detonationsFor;(!a||n!==a.key||t.length!==a.reentries.length||t.some((c,h)=>c!==a.reentries[h]))&&(this.detonationsFor={reentries:[...t],key:n,detonations:t.length?X.detonationsOf(t,s):[]});const o=this.detonationsFor.detonations;if(i)return;const r=this.lastDetonationT;if(this.lastDetonationT=e,!(r===void 0||e<r||e-r>nt.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const c of o)c.t>r&&c.t<=e&&this.weatherAudio.playDetonation(c.loudness)}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],s=pt(t,0),i=t.event.place?.[0],n=s?.lat??i?.lat,a=s?.lng??i?.lng;return e.length>0&&n!==void 0&&a!==void 0&&X.detonationsOf(e,{lat:n,lng:a,heightM:this.altitudeOf(s)}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){if(clearTimeout(this.thunderTimeoutId),this.filmSound){this.filmThunderAtMs=this.lastTimeMs+De.thunderDelayMs(t)*this.ufoElement.playbackRate;return}this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),De.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(Ko(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){if(this.filmSound)return;const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{if(this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const e=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&e-this.lastPlayingHoverMs>=nt.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.placeFlightMark(),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing",e=t||this.filming;this.sceneRenderer.setAnimationsRunning(e,e);const s=t||this.filmSound!==void 0;this.weatherAudio.setPaused(!s),this.vehicleAudio.setPaused(!s),this.aircraftAudio?.setPaused(!s),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${v2}</style>${M2}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new N(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(Rp));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new kr(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=n=>{this.holding=n,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.flightMark=this.shadow.getElementById("flight-mark"),this.ufoElement=document.createElement(au),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapSnapshotSource=n=>this.snapshotMapOf(n),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",n=>this.lookToward(n.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const s=this.shadow.getElementById("credits-panel"),i=this.shadow.getElementById("credits-list");s.addEventListener("beforetoggle",n=>{n.newState==="open"&&Qe.fill(i,this)}),this.sceneRenderer.onMapSubjectBounds=n=>this.ufoElement.setMapSubjectBounds(n),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(Km,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(n,a)=>this.seekPreviewOf(a).paint(n,a),typeof VideoEncoder<"u"&&typeof OffscreenCanvas<"u"&&(this.ufoElement.filmer={film:(n,a,o)=>this.film(n,a,o),generativeKit:(n,a,o)=>this.generativeKit(n,a,o),fileName:()=>this.filmFileName(),kitFileName:()=>this.filmFileName().replace(/\.mp4$/," - kit.zip"),pictureSize:()=>this.filmPictureSize(),hasMap:()=>this.ufoElement.hasObserverMap,durationS:()=>this.ufoElement.seekableDuration/this.filmRate()/1e3,positionS:()=>this.ufoElement.currentTime/this.filmRate()/1e3}),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=n=>n.vehicle!==void 0||n.decor.some(a=>a.engine!==void 0)||n.decor.some(a=>gd.kindOf(a,this.decorModelSounds.get(a.model?.id??""))!==void 0)||this.interpretationShown?.bodies.some(a=>a.sound)===!0||n.weatherTrack.allKeyframes.some(a=>a.weather.precipitationType!=="none"||a.weather.windSpeed>1)||this.detonates(n)||(this.traffic?.audible?.size??0)>0,this.ufoElement.addEventListener("referenceview",n=>this.applyReferenceView(n.detail)),this.ufoElement.addEventListener("traceview",n=>this.sceneRenderer.setTracesShown(n.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const n of nt.GESTURES)this.addEventListener(n,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Nr(pn.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const s=t.vehicle;return!s||!ns.isRoad(s.kind)?void 0:{setting:Hl.at(s.headlights??"auto",s.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}}travelHeadingAt(t,e){const s=pt(t,e);if(!s)return 0;for(const i of[400,-400]){const n=pt(t,e+i);if(!n||s.lat===void 0||s.lng===void 0||n.lat===void 0||n.lng===void 0)break;const a=ot(n.lat,n.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)<.8)continue;return(Math.atan2(a.x,-a.z)*180/Math.PI+(i<0?180:0)+360)%360}return s.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const s=e.flatMap(n=>n.pose.lat!==void 0&&n.pose.lng!==void 0?[{lat:n.pose.lat,lng:n.pose.lng}]:[]),i=s.length>=2?s:void 0;return this.routeCache={track:t,count:e.length,route:i},i}traceLabels(t){const e=pn.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const s=new Map;for(const i of t){const n=this.said.read(i.title);n&&s.set(i.id,n)}this.traceLabelsFor={traces:t,language:e,labels:s}}return this.traceLabelsFor.labels}connectedCallback(){ke.changes.addEventListener("change",this.onModulesChanged),this.saidTexts=void 0,this.ready=this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of nt.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){ke.changes.removeEventListener("change",this.onModulesChanged),this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of nt.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,s){if(t==="src"&&s&&s!==e&&this.isConnected&&this.loadFromSrc(s),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&s!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&s!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&s!==e){const i=Number(s);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(i)&&i>0?i:Math.min(window.devicePixelRatio||1,2))}(t===Lo||t===No||t===ma)&&s!==e&&this.forwardPlayerAttributes(),t===ma&&this.stageElement.classList.toggle("minified",s!==null)}forwardPlayerAttributes(){for(const t of[Lo,No,ma]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.showCompassFor({forced:t})}compassHovered=!1;compassForced=!1;showCompassFor(t){this.compassHovered=t.hovered??this.compassHovered,this.compassForced=t.forced??this.compassForced,this.sceneRenderer.setCompassForced(this.compassForced||this.compassHovered)}lookToward(t){const e=pt(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:s,z:i}=ot(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(s,i)<1)return this.setLookOffset(0,0);const n=(Math.atan2(s,-i)*180/Math.PI+360)%360;this.setLookOffset(((n-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setOutsideHeard(ns.transmission(this.ufoElement.sighting.vehicle)),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed);const e=this.ufoElement.sighting.around;this.weatherAudio.setAround(jt.aroundBedRms(e),jt.aroundBedShape(e)??[])}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,s,i=0){return this.sceneRenderer.decorGroundPointAt(t,e,s,i)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,s){return this.sceneRenderer.decorGrabHeightAt(t,e,s)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=Uf.recording(t);this.holdForNewScene(e);const s=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(s.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=s}loader;poster;showPoster(t,e,s=!0){this.poster.show(t,e,s)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,(t||e)&&(this.hoverTooltip.hidden=!0),this.ufoElement.namesHeld=t||e,this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){const e=ku.recording(t);this.ufoElement.playerTitle=void 0,this.ufoElement.sightingData=e,this.requireModules(e.modules),this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.showInterpretation(this.inTheRound?this.ufoElement.sighting.interpretation:void 0),this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}onModulesChanged=t=>{t.detail==="skyEvents"&&this.sceneRenderer.setSkyEvents(this.skyEventsShown,!0,this.skyEventsStartDate)};requireModules(t){if(!t?.length)return;const e=this.documentUrl,s=H(async()=>{const{ModuleSession:i}=await import("./ModuleSession-Dac4fD0X.js");return{ModuleSession:i}},__vite__mapDeps([52,1,9,6]),import.meta.url).then(({ModuleSession:i})=>i.shared.require(t,e)).then(()=>this.sceneRenderer.setDecorModelProvider(new gp));this.sceneRenderer.holdUntil(s)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,s=Math.round(t.width/e);return t.height!==s&&(t.height=s),this.seekPreview??=new uh(this,()=>document.createElement(gh))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}filmName;filmFileName(){return`${(this.filmName??"").replace(/[\\/:*?"<>|\u0000-\u001f]+/g," ").replace(/\s+/g," ").trim()||"observation"}.mp4`}filming=!1;async film(t,e,s){const[{VideoExport:i},{FilmChrome:n}]=await Promise.all([H(()=>import("./VideoExport-B8ZhHNnd.js").then(o=>o.a),[],import.meta.url),H(()=>import("./FilmChrome-DYiyzoB_.js"),[],import.meta.url)]),a=await n.loadLogo();return this.filmScene(t,o=>i.film({...o,frameAt:(r,c,h)=>o.frameAt(r,c,h)?(n.paint(h,this.ufoElement.filmChrome(t),a),!0):!1},e,s))}async generativeKit(t,e,s){const[{GenerativeKit:i},{generativeKitMessages:n},{toSightingJson:a}]=await Promise.all([H(()=>import("./GenerativeKit-BmhvjjzB.js"),__vite__mapDeps([53,54,55]),import.meta.url),H(()=>import("./GenerativeKitMessages-BwG7cWZX.js"),__vite__mapDeps([56,1]),import.meta.url),H(()=>Promise.resolve().then(()=>L1),void 0,import.meta.url)]),o=pr(pn.preferencesFor(this),gr),[r]=await Promise.all([n.load(o),this.sceneRenderer.loadControlPasses()]),c=this.sceneRenderer.areReferencesShown;this.sceneRenderer.setReferencesShown(!1);try{return await this.filmScene({...t,caption:!1,time:!1,map:!1},h=>i.make({film:h,drawControlPasses:()=>this.sceneRenderer.drawControlPasses(),recording:a(this.ufoElement.sighting),title:this.filmName??"",source:h.about?.source,language:o},r,e,s))}finally{this.sceneRenderer.setReferencesShown(c)}}async filmScene(t,e){if(this.filming)throw new Error("Already filming");const s=this.ufoElement,i=s.currentTime;s.pause();const n={width:this.sceneCanvas.clientWidth,height:this.sceneCanvas.clientHeight},a=t.height&&n.height>0?t.height/n.height:this.sceneRenderer.maxPixelRatio;this.filming=!0,this.sceneRenderer.holdPixelRatio(a),s.filmMap(t.map),this.syncAnimationsToPlayback();try{const o=t.height??this.sceneCanvas.height,r=t.height&&n.height>0?Math.round(t.height*n.width/n.height):this.sceneCanvas.width,c=this.filmRate(),h=Math.min(s.seekableDuration,t.toS!==void 0?t.toS*1e3*c:s.seekableDuration),l=Math.min(h,Math.max(0,(t.fromS??0)*1e3*c));return await e({fromMs:l,toMs:h,rate:c,width:r,height:o,frameAt:(d,f,m)=>this.filmFrameAt(d,f,m),hearInto:d=>this.hearInto(d),about:{title:this.filmName,description:s.filmDescription,source:this.documentUrl?new URL(this.documentUrl,location.href).href:void 0}})}finally{this.filming=!1,this.sceneRenderer.holdPixelRatio(void 0),s.filmMap(void 0),s.currentTime=i,this.syncAnimationsToPlayback()}}filmRate(){const t=this.ufoElement.playbackRate;return t>0?t:1}filmPictureSize(){const t=this.sceneRenderer.maxPixelRatio;return{width:Math.round(this.sceneCanvas.clientWidth*t),height:Math.round(this.sceneCanvas.clientHeight*t)}}filmSound;liveSound;filmThunderAtMs;hearInto(t){if(t){this.liveSound??={weather:this.weatherAudio,vehicle:this.vehicleAudio,aircraft:this.aircraftAudio},this.filmSound=t,this.weatherAudio=new Aa(t),this.vehicleAudio=new Zd(t);const e=nt.trafficRuntime;this.aircraftAudio=this.liveSound.aircraft&&e?this.newAircraftAudio(e):void 0}else this.liveSound&&(this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.weatherAudio=this.liveSound.weather,this.vehicleAudio=this.liveSound.vehicle,this.aircraftAudio=this.liveSound.aircraft,this.liveSound=void 0,this.filmSound=void 0,this.filmThunderAtMs=void 0);this.ufoElement.hearInto(t),this.syncAnimationsToPlayback()}filmFrameAt(t,e,s){this.ufoElement.currentTime!==t&&(this.ufoElement.currentTime=t),this.filmThunderAtMs!==void 0&&t>=this.filmThunderAtMs&&(this.filmThunderAtMs=void 0,this.weatherAudio.playThunder()),this.sceneRenderer.render();const i=this.sceneRenderer.framesDrawn;return this.sceneRenderer.frame(e),this.sceneRenderer.framesDrawn===i?!1:(s.drawImage(this.sceneCanvas,0,0,s.canvas.width,s.canvas.height),!0)}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}horizonPointAt(t){const e=t*Math.PI/180,s=this.sceneRenderer.screenPointOf(new D(Math.sin(e),0,-Math.cos(e)));return s&&{x:(s.ndcX+1)/2,y:(1-s.ndcY)/2}}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const s=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:s?s.shown?s.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.snapshotKey=void 0,this.applySnapshots(this.ufoElement.sighting.snapshots)}liveTerrainProviders;snapshotKey="none";applySnapshots(t){const e=Oc.isEmpty(t)?"none":`${JSON.stringify(t)}
|
|
4999
|
+
`);let n=Pi.cache.get(i);return n||(n=Promise.all(s.map(a=>Pi.load(a.url))).then(a=>a.reduce((o,r)=>Pi.concat(o,r))),Pi.cache.set(i,n)),n}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),s=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*s,e),dec:new Float32Array(t,1*s,e),mag:new Float32Array(t,2*s,e),ci:new Float32Array(t,3*s,e)}}static concat(t,e){const s=(i,n)=>{const a=new Float32Array(i.length+n.length);return a.set(i,0),a.set(n,i.length),a};return{count:t.count+e.count,ra:s(t.ra,e.ra),dec:s(t.dec,e.dec),mag:s(t.mag,e.mag),ci:s(t.ci,e.ci)}}}class Gt{constructor(t){if(this.heights=t,t.length!==Gt.WIDTH*Gt.HEIGHT)throw new Error(`a lunar relief has ${Gt.WIDTH*Gt.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*Gt.SAMPLES_PER_DEGREE;static HEIGHT=180*Gt.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const s=Gt.SAMPLES_PER_DEGREE,i=(e%360+360)%360*s-.5,n=(90-t)*s-.5,a=Math.floor(i),o=Math.floor(n),r=i-a,c=n-o,h=(f,m)=>{const p=(f%Gt.WIDTH+Gt.WIDTH)%Gt.WIDTH,g=Math.min(Gt.HEIGHT-1,Math.max(0,m));return this.heights[g*Gt.WIDTH+p]},l=h(a,o)*(1-r)+h(a+1,o)*r,d=h(a,o+1)*(1-r)+h(a+1,o+1)*r;return(l*(1-c)+d*c)*Gt.UNIT_KM}static inBand(t,e){const s=Math.PI/180,i=Math.acos(Math.cos(t*s)*Math.cos(e*s))*180/Math.PI;return i>=Gt.BAND_FROM_DEG&&i<=Gt.BAND_TO_DEG}static withBump(t,e,s,i=.4){const n=new Int8Array(Gt.WIDTH*Gt.HEIGHT),a=Gt.SAMPLES_PER_DEGREE,o=Math.ceil(i*a),r=Math.floor(e*a),c=Math.floor((90-t)*a);for(let h=-o;h<=o;h++)for(let l=-o;l<=o;l++)Math.hypot(l,h)<=o&&(n[(c+h)*Gt.WIDTH+(r+l+Gt.WIDTH)%Gt.WIDTH]=Math.round(s/Gt.UNIT_KM));return new Gt(n)}static smooth(){return new Gt(new Int8Array(Gt.WIDTH*Gt.HEIGHT))}}class ii{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,s,i=ii.SAMPLES){const{s:n,u:a,w:o,distanceKm:r}=ii.frame(t,e),c=Math.PI/180,h=new Float32Array(i),l=Gt.REFERENCE_RADIUS_KM;for(let d=0;d<i;d++){const f=d/i*2*Math.PI,m=Math.cos(f),p=Math.sin(f),g=m*a[0]+p*o[0],M=m*a[1]+p*o[1],v=m*a[2]+p*o[2];let y=0;for(let w=ii.SEARCH_FROM_DEG;w<=ii.SEARCH_TO_DEG;w+=ii.SEARCH_STEP_DEG){const b=Math.cos(w*c),E=Math.sin(w*c),A=b*n[0]+E*g,S=b*n[1]+E*M,x=b*n[2]+E*v,T=Math.asin(Math.max(-1,Math.min(1,x)))/c,I=Math.atan2(S,A)/c,R=l+s.heightKm(T,I),O=Math.atan2(R*E,r-R*b);O>y&&(y=O)}h[d]=y/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(l/r)/c}}static frame(t,e){const s=new Zn(e.lat,e.lng,e.elevationM),i=En(t),n=$l(t,s,!1),a=new It(n.x-i.x,n.y-i.y,n.z-i.z,i.t),o=Math.hypot(a.x,a.y,a.z)*ii.AU_KM,r=ii.bodyFixed(t),c=r(a),h=Math.hypot(c[0],c[1],c[2]),l=[c[0]/h,c[1]/h,c[2]/h],d=h1(t,s),f=Gu(d),m=yn(d,new It(-a.x,-a.y,-a.z,i.t)),p=Math.asin(m.z/Math.hypot(m.x,m.y,m.z)),g=Math.atan2(-m.y,m.x),M=new It(-Math.sin(p)*Math.cos(g),Math.sin(p)*Math.sin(g),Math.cos(p),i.t),v=new It(-Math.sin(g),-Math.cos(g),0,i.t);return{s:l,u:r(yn(f,M)),w:r(yn(f,v)),distanceKm:o}}static surfacePoint(t,e,s,i){const{s:n,u:a,w:o}=ii.frame(t,e),r=Math.PI/180,c=[0,1,2].map(l=>Math.cos(s*r)*a[l]+Math.sin(s*r)*o[l]),h=[0,1,2].map(l=>Math.cos(i*r)*n[l]+Math.sin(i*r)*c[l]);return{latDeg:Math.asin(h[2])/r,lonDeg:Math.atan2(h[1],h[0])/r}}static radiusAt(t,e){const s=t.radiusDeg.length,i=(e/360*s%s+s)%s,n=Math.floor(i),a=i-n;return t.radiusDeg[n]*(1-a)+t.radiusDeg[(n+1)%s]*a}static uncoveredFraction(t,e,s){const i=t.radiusDeg.length,n=s.upDeg*s.upDeg+s.rightDeg*s.rightDeg;let a=0;for(let o=0;o<i;o++){const r=o/i*2*Math.PI,c=Math.cos(r),h=Math.sin(r),l=c*s.upDeg+h*s.rightDeg,d=l*l-n+e*e;if(d<=0)continue;const f=Math.sqrt(d),m=l+f;if(m<=0)continue;const p=Math.max(0,l-f),g=Math.max(p,t.radiusDeg[o]);m>g&&(a+=.5*(m*m-g*g))}return Math.min(1,Math.max(0,a*(2*Math.PI/i)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=x1(z.Moon,t),s=Math.PI/180,i=e.ra*15*s,n=e.dec*s,a=e.spin*s,o=(c,[h,l,d])=>[Math.cos(c)*h+Math.sin(c)*l,-Math.sin(c)*h+Math.cos(c)*l,d],r=(c,[h,l,d])=>[h,Math.cos(c)*l+Math.sin(c)*d,-Math.sin(c)*l+Math.cos(c)*d];return c=>o(a,r(Math.PI/2-n,o(Math.PI/2+i,[c.x,c.y,c.z])))}static subObserverPoint(t,e){const s=new Zn(e.lat,e.lng,e.elevationM),i=En(t),n=$l(t,s,!1),a=ii.bodyFixed(t)(new It(n.x-i.x,n.y-i.y,n.z-i.z,i.t)),o=Math.hypot(a[0],a[1],a[2]);return{latDeg:Math.asin(a[2]/o)*180/Math.PI,lonDeg:Math.atan2(a[1],a[0])*180/Math.PI}}}class Pr{static cache=new Map;static load(t){let e=Pr.cache.get(t);return e||(e=Pr.fetchRelief(t).catch(()=>{}),Pr.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let s=new Uint8Array(await e.arrayBuffer());if(s[0]===31&&s[1]===139){if(typeof DecompressionStream>"u")return;const i=new Blob([s]).stream().pipeThrough(new DecompressionStream("gzip"));s=new Uint8Array(await new Response(i).arrayBuffer())}return new Gt(new Int8Array(s.buffer,s.byteOffset,s.length))}}const id=Sn.catalog({en:()=>H(()=>import("./PerceptionMessages_en-B2O6DR64.js"),[],import.meta.url).then(u=>u.perceptionMessages_en),fr:()=>H(()=>import("./PerceptionMessages_fr-B59TnGBC.js"),[],import.meta.url).then(u=>u.perceptionMessages_fr),es:()=>H(()=>import("./PerceptionMessages_es-BmkP6OqD.js"),[],import.meta.url).then(u=>u.perceptionMessages_es),it:()=>H(()=>import("./PerceptionMessages_it-DPlxRmxu.js"),[],import.meta.url).then(u=>u.perceptionMessages_it)});class mh{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=mh.ID;messages=id;sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",kind:"choice",default:"normal",choices:[{id:"normal"},{id:"protan"},{id:"deutan"},{id:"tritan"}]},{id:"severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=mh.MATRICES[String(t.type)];if(!e)return Cs.NONE;const s=Number(t.severity??100),i=Math.max(0,Math.min(100,Number.isFinite(s)?s:100))/100;return{colorMatrix:e.map((a,o)=>Cs.IDENTITY[o]+(a-Cs.IDENTITY[o])*i),contrastGain:1}}}class nd{static ID="fatigue";id=nd.ID;messages=id;sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return Cs.NONE}}class ua{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=ua.ID;messages=id;sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",kind:"number",default:0,min:0,max:ua.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),s=Math.max(0,Math.min(ua.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(s===0)return Cs.NONE;const i=s/ua.MEASURED_LEVEL*ua.MEASURED_LOSS_DB;return{colorMatrix:Cs.IDENTITY,contrastGain:10**(-i/20)}}}const uw=u=>u.sources[0]??u.id,dw=ke.point("perception").provide(ke.BUILT_IN,[new mh,new ua,new nd].map(u=>({id:u.id,name:u.id,credit:uw(u),creditUrl:"https://ufoathome.org/docs/sources/",create:()=>u})));class da{static built=new WeakMap;static get ALL(){return dw.map(t=>{let e=da.built.get(t);return e||(e=t.create(),da.built.set(t,e)),e})}static byId(t){return da.ALL.find(e=>e.id===t)}static perceptionOf(t){return da.ALL.reduce((e,s)=>Cs.combine(e,s.perceive(t?.[s.id]??{})),Cs.NONE)}static compact(t){const e={},s=da.ALL;for(const[i,n]of Object.entries(t))!s.some(a=>a.id===i)&&Object.keys(n??{}).length>0&&(e[i]=n);for(const i of s){const n=t[i.id]??{},a=Object.fromEntries(i.settings.filter(o=>n[o.id]!==void 0&&n[o.id]!==o.default).map(o=>[o.id,n[o.id]]));Object.keys(a).length>0&&(e[i.id]=a)}return Object.keys(e).length>0?e:void 0}}class If{names;constructor(t){this.names=t??Sn.blank(),this.loaded=t!==void 0}loaded;body(t){return this.names.bodies[t]??t}star(t){return this.names.stars[t.name]??t.name}comet(t){return this.names.comets[t.id]??t.name}nova(t){return this.names.novae[t.id]??t.name}satelliteClass(t){return this.names.satelliteClasses[t.id]??t.name}shower(t){return this.names.showers[t.id]??t.name}lightRig(t){return this.names.lightRigs[t.id]??t.name}instrument(t){return this.names.instruments[t.id]??t.name}decorKind(t){return this.names.decorKinds[t]}point(t){return Da.point(t,this.loaded?this.names.compassPoints:void 0)}towards(t){return Da.towards(t,this.loaded?this.names:void 0)}}class Ci{static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const s=t.name??Ci.kind(t,e);return t.services?.length?`${s} — ${t.services.join(", ")}`:s}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,s,i){const{line:n}=t,a=[];n.name&&a.push(Ci.kind(n,e).toLocaleLowerCase(i)),a.push(n.tracks>1?e.tracks.replace("{count}",String(n.tracks)):e.singleTrack);const o=n.voltageV?Ci.voltage(n.voltageV,i):void 0;if(t.contactM!==void 0){const r=t.contactM.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:2});a.push((o?e.overheadVoltage.replace("{voltage}",o):e.overhead).replace("{height}",r))}else n.electrification==="third_rail"?a.push(o?e.thirdRailVoltage.replace("{voltage}",o):e.thirdRail):n.electrification==="none"&&a.push(e.notElectrified);return n.gaugeMm===Ci.METRE_GAUGE_MM?a.push(e.metreGauge):n.gaugeMm!==Ci.STANDARD_GAUGE_MM&&a.push(e.gauge.replace("{mm}",n.gaugeMm.toLocaleString(i))),a.push(e.distance.replace("{distance}",s(t.distanceM))),n.services?.length?`${Ci.name(n,e)}; ${a.join(", ")}`:`${Ci.name(n,e)} — ${a.join(", ")}`}}class kr{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,s=!0){const i=kr.resolve(t,e);if(this.url=i,!i||!s){this.release();return}this.element.src=i,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const s=new URL(t.trim(),e??location.href);return s.protocol!=="https:"&&s.protocol!=="http:"?void 0:s.origin===kr.PUBLISHED_ORIGIN&&kr.isDevelopmentHost(location.hostname)?location.origin+s.pathname:s.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}}class me{static OCTAVES=[63,125,250,500,1e3,2e3,4e3,8e3];static STANDARD={temperatureC:15,relativeHumidity:.7,pressureKPa:101.325};static REFERENCE_PRESSURE_KPA=101.325;static REFERENCE_TEMPERATURE_K=293.15;static TRIPLE_POINT_K=273.16;static speedOfSound(t){return 20.0468*Math.sqrt(t+273.15)}static absorptionDbPerKm(t,e=me.STANDARD){const s=e.temperatureC+273.15,i=me.REFERENCE_TEMPERATURE_K,n=e.pressureKPa/me.REFERENCE_PRESSURE_KPA,a=10**(-6.8346*(me.TRIPLE_POINT_K/s)**1.261+4.6151),o=e.relativeHumidity*100*a/n,r=n*(24+40400*o*(.02+o)/(.391+o)),c=n*(s/i)**-.5*(9+280*o*Math.exp(-4.17*((s/i)**(-1/3)-1))),h=t*t;return 8.686*h*(184e-13*(1/n)*Math.sqrt(s/i)+(s/i)**-2.5*(.01275*Math.exp(-2239.1/s)/(r+h/r)+.1068*Math.exp(-3352/s)/(c+h/c)))*1e3}static aWeightingDb(t){const e=t*t,s=12194**2*e*e/((e+20.6**2)*Math.sqrt((e+107.7**2)*(e+737.9**2))*(e+12194**2));return 20*Math.log10(s)+2}static sumDb(t){return 10*Math.log10(t.reduce((e,s)=>e+10**(s/10),0))}}const fw=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,mw=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Rf=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,pw=20,gw=1,Mw=7,vw=.35,Of=.4,Pf=40,kf=.5,yw=Math.SQRT2;class Aa{context;constructor(t){this.context=t}buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};around;aroundRequested={rms:0,shape:[]};level=1;share=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.gain,this.master.connect(t.destination)),this.master}get gain(){return this.level*this.share}setLevel(t){this.level=t,this.master&&(this.master.gain.value=this.gain)}setOutsideHeard(t){this.share=Math.min(1,Math.max(0,t)),this.master&&(this.master.gain.value=this.gain)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}qs.isLive(this.context)&&qs.unlock(this.context),this.applyAround()}setAround(t,e){const s=this.aroundRequested;s.rms===Math.max(0,t)&&s.shape.length===e.length&&s.shape.every((i,n)=>i===e[n])||(this.aroundRequested={rms:Math.max(0,t),shape:e},this.applyAround())}applyAround(){const t=this.context;if(!t)return;const{rms:e,shape:s}=this.aroundRequested,i=this.paused?0:e;if(i===0&&!this.around)return;const n=this.around??(this.around=this.buildAround(t)),a=t.currentTime;n.gain.gain.setTargetAtTime(i,a,kf),me.OCTAVES.forEach((o,r)=>{const c=Math.sqrt(Math.min(1,1.11*o/(t.sampleRate/2)))/Math.sqrt(3);n.bands[r].gain.setTargetAtTime((s[r]??0)/c,a,kf)})}buildAround(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*Mw),t.sampleRate),s=e.getChannelData(0);for(let p=0;p<s.length;p++)s[p]=Math.random()*2-1;const i=t.createBufferSource();i.buffer=e,i.loop=!0;const n=Math.floor(t.sampleRate*Pf),a=t.createBuffer(1,n,t.sampleRate),o=Array.from({length:Math.round(Pf*Of)},()=>Math.random()*2-1),r=a.getChannelData(0),c=t.sampleRate/Of;for(let p=0;p<n;p++){const g=p/c,M=Math.floor(g),v=g-M,y=v*v*(3-2*v);r[p]=o[M%o.length]*(1-y)+o[(M+1)%o.length]*y}const h=t.createBufferSource();h.buffer=a,h.loop=!0;const l=t.createGain();l.gain.value=vw;const d=t.createGain();d.gain.value=1,h.connect(l).connect(d.gain);const f=t.createGain();f.gain.value=0,d.connect(f).connect(this.output(t));const m=me.OCTAVES.map(p=>{const g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=p,g.Q.value=yw;const M=t.createGain();return M.gain.value=0,i.connect(g).connect(M).connect(d),M});return i.start(),h.start(),{sources:[i,h],nodes:[l,d,f,...m],bands:m,gain:f}}setAmbient(t,e,s){if(this.requested={type:t,intensity:e,windSpeed:s},!this.context)return;this.paused&&(t="none",e=0,s=0);const i=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=i==="hail"?Math.min(1,e*1.3+.2):i==="rain"?e:0,i!==this.ambientKey){this.ambientKey=i;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,i!=="none"&&this.startLoop(fw,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,r=>{this.ambientSource=r?.source,this.ambientGain=r?.gain,r&&(r.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(s/pw,1);const n=s>gw;if(n!==this.windActive){this.windActive=n;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,n&&this.startLoop(mw,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,r=>{this.windSource=r?.source,this.windGain=r?.gain,r&&(r.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:s,windSpeed:i}=this.requested;this.setAmbient(e,s,i),this.applyAround()}playThunder(){!this.context||this.paused||this.playOneShot(Rf,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const s=Math.min(1,Math.max(0,t)),i=e.createBufferSource();i.buffer=this.crackBuffer(e);const n=e.createBiquadFilter();n.type="lowpass",n.frequency.value=Aa.CRACK_CUTOFF_HZ;const a=e.createGain();a.gain.value=s,i.connect(n).connect(a).connect(this.output(e)),i.start(),this.playOneShot(Rf,s,Aa.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(t){if(this.crack?.sampleRate===t.sampleRate)return this.crack;const e=Math.round(t.sampleRate*Aa.CRACK_DECAY_S*6),s=t.createBuffer(1,e,t.sampleRate),i=s.getChannelData(0);for(let n=0;n<e;n++){const a=n/t.sampleRate;i[n]=(Math.random()*2-1)*Math.min(1,a/.005)*Math.exp(-a/Aa.CRACK_DECAY_S)}return this.crack=s,s}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0;for(const t of this.around?.sources??[])try{t.stop()}catch{}for(const t of this.around?.nodes??[])t.disconnect();this.around=void 0,qs.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,s,i){if(e!==s()){t?.source.stop();return}i(t)}async startLoop(t,e){const s=this.context;if(s)try{const i=await this.getBuffer(t),n=s.createBufferSource();n.buffer=i,n.loop=!0;const a=s.createGain();return a.gain.value=e,n.connect(a).connect(this.output(s)),n.start(),{source:n,gain:a}}catch(i){console.warn("Weather ambient sound failed to load, staying silent:",i);return}}async playOneShot(t,e,s=1){const i=this.context;if(i)try{const n=await this.getBuffer(t),a=i.createBufferSource();a.buffer=n,a.playbackRate.value=s;const o=i.createGain();o.gain.value=e,a.connect(o).connect(this.output(i)),a.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let s=this.buffers.get(t);return s||(s=fetch(t).then(i=>{if(!i.ok)throw new Error(`Audio fetch failed (${i.status}): ${t}`);return i.arrayBuffer()}).then(i=>e.decodeAudioData(i)),this.buffers.set(t,s)),s}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}const ww={rollingA:[83.1,89.2,87.7,93.1,100.1,96.7,86.8,76.2],rollingB:[30,41.5,38.9,25.7,32.5,37.2,39,40],propulsionA:[97.9,92.5,90.7,87.2,84.7,88,84.4,77.1],propulsionB:[-1.3,7.2,7.7,8,8,8,8,8]},bw={rollingA:[91.7,96.2,98.2,104.9,105.1,98.5,91.1,85.6],rollingB:[30,33.5,31.3,25.4,31.8,37.1,38.6,40.6],propulsionA:[108.8,104.2,103.5,102.9,102.6,98.5,93.8,87.5],propulsionB:[0,3,4.6,5,5,5,5,5]},Ol=70,Ew=55+10*Math.log10(2*Math.PI),Pl=5,Aw=2;class Ie{static vehiclePowerDbA(t,e){return me.sumDb(Ie.vehiclePowerBands(t,e).map((s,i)=>s+me.aWeightingDb(me.OCTAVES[i])))}static vehiclePowerBands(t,e){const s=t?bw:ww,i=Math.max(e,1);return me.OCTAVES.map((n,a)=>{const o=s.rollingA[a]+s.rollingB[a]*Math.log10(i/Ol),r=s.propulsionA[a]+s.propulsionB[a]*(i-Ol)/Ol;return me.sumDb([o,r])})}static dbA(t,e=!0){if(!Ln.says(t))return-1/0;const s=t.withinM??Ln.DEFAULT_WITHIN_M,i=Ln.DEFAULT_SPEED_KMH,n=[Ie.counted(t.cars,Ie.vehiclePowerDbA(!1,i),s,Pl),Ie.counted(t.trucks,Ie.vehiclePowerDbA(!0,i),s,Pl),e?Ie.counted(t.talking,Ew,s,Aw):-1/0,...(t.roads??[]).map(a=>Ie.road(a.distanceM,a.vehiclesPerMinute,a.trucksPerMinute??0,a.speedKmh??i))].filter(a=>Number.isFinite(a));return n.length>0?me.sumDb(n):-1/0}static vehicleShape(t){if(!Ln.says(t))return;const e=t.withinM??Ln.DEFAULT_WITHIN_M,s=Ln.DEFAULT_SPEED_KMH,i=c=>{const h=Ie.counted(c?t.trucks:t.cars,Ie.vehiclePowerDbA(c,s),e,Pl),l=(t.roads??[]).map(f=>{const m=Math.min(f.trucksPerMinute??0,f.vehiclesPerMinute);return c?Ie.road(f.distanceM,m,m,f.speedKmh??s):Ie.road(f.distanceM,f.vehiclesPerMinute-m,0,f.speedKmh??s)}),d=[h,...l].filter(Number.isFinite);return d.length>0?10**(me.sumDb(d)/10):0},n=i(!1),a=i(!0);if(n+a===0)return;const o=me.OCTAVES.map(()=>0);for(const[c,h]of[[n,!1],[a,!0]]){if(c===0)continue;const l=Ie.vehiclePowerBands(h,s),d=me.sumDb(l.map((f,m)=>f+me.aWeightingDb(me.OCTAVES[m])));l.forEach((f,m)=>o[m]+=c*10**((f-d)/10))}const r=Math.sqrt(o.reduce((c,h)=>c+h,0));return o.map(c=>Math.sqrt(c)/r)}static counted(t,e,s,i){if(!t)return-1/0;const n=Math.min(i,s*.99),a=t*Math.log(s/n)/(Math.PI*(s*s-n*n));return e+10*Math.log10(a)}static road(t,e,s,i){const n=Math.min(s,e),a=(r,c)=>r>0?Ie.vehiclePowerDbA(c,i)+10*Math.log10(r/(1e3*Math.max(i,1))):-1/0,o=me.sumDb([a((e-n)*60,!1),a(n*60,!0)].filter(Number.isFinite));return Number.isFinite(o)?o-10*Math.log10(Math.PI*Math.max(t,1)):-1/0}}class jt{static BASE_DB_A=30;static OUTDOOR_SHAPE_DB=[-12,-7,-5,-5,-7,-11,-17,-25];static HEADROOM_DB=10.5;static AROUND_BED_PLAYED=!1;static WIND_DB_A=[[0,10],[1,28],[2,36],[3,40],[5,46],[8,52],[12,58],[20,66]];static RAIN_DB_A=[[0,0],[.1,42],[.3,50],[.6,58],[1,65]];static BED_RMS=.2;static MINIMUM_REFERENCE=.008;static WIND_BED_MIN_MS=1;static WIND_BED_FULL_MS=20;static dbA(t,e){const s=[jt.BASE_DB_A,jt.along(jt.WIND_DB_A,t.windSpeed),Ie.dbA(e)].filter(Number.isFinite);return(t.precipitationType==="rain"||t.precipitationType==="hail")&&s.push(jt.along(jt.RAIN_DB_A,t.precipitationIntensity)),10*Math.log10(s.filter(i=>i>0).reduce((i,n)=>i+10**(n/10),0))}static bedVolume(t){const e=t.windSpeed>jt.WIND_BED_MIN_MS?Math.min(t.windSpeed/jt.WIND_BED_FULL_MS,1):0,s=t.precipitationType==="hail"?Math.min(1,t.precipitationIntensity*1.3+.2):t.precipitationType==="rain"?t.precipitationIntensity:0;return Math.hypot(e,s)}static referenceAmplitude(t,e){return Math.max(Math.hypot(jt.BED_RMS*jt.bedVolume(t),jt.aroundReference(e)),jt.MINIMUM_REFERENCE)}static aroundReference(t){const e=Ie.dbA(t);return!Number.isFinite(e)||e<=jt.BASE_DB_A?0:jt.MINIMUM_REFERENCE*10**((e-jt.BASE_DB_A)/20)}static aroundBedRms(t){if(!jt.AROUND_BED_PLAYED)return 0;const e=Ie.dbA(t,!1);return!Number.isFinite(e)||e<=jt.BASE_DB_A?0:Math.min(jt.BED_RMS,jt.MINIMUM_REFERENCE*10**((e-jt.BASE_DB_A-jt.HEADROOM_DB)/20))}static bedPlays(t,e){return jt.bedVolume(t)>0||jt.aroundBedRms(e)>0}static shapeDb(t,e){const s=10**(jt.dbA(t,e)/10),i=Ie.dbA(e,!1),n=Number.isFinite(i)?10**(i/10):0,a=Math.max(0,s-n),o=jt.OUTDOOR_SHAPE_DB,r=10**(me.sumDb(o)/10),h=Ie.vehicleShape(e)?.map((m,p)=>m*m*10**(me.aWeightingDb(me.OCTAVES[p])/10)),l=h?.reduce((m,p)=>m+p,0)??1,d=me.OCTAVES.map((m,p)=>a*10**(o[p]/10)/r+(h?n*h[p]/l:0)),f=d.reduce((m,p)=>m+p,0);return d.map(m=>10*Math.log10(m/f))}static aroundBedShape(t){return Ie.vehicleShape(t)}static along(t,e){if(e<=t[0][0])return t[0][1];for(let s=1;s<t.length;s++)if(e<=t[s][0]){const[i,n]=t[s-1],[a,o]=t[s];return n+(o-n)*(e-i)/(a-i)}return t[t.length-1][1]}}class ln{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:s}=t,[i,n]=this.perifocalAxes(),a=Math.sqrt(ln.SUN_GM_AU3_PER_DAY2*(1+e)/s);this.perihelionPosition=this.scale(i,s),this.perihelionVelocity=this.scale(n,a),this.inverseSemiMajorAxis=(1-e)/s}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,s=this.universalAnomaly(e),i=this.inverseSemiMajorAxis*s*s,n=this.elements.perihelionAu,a=1-s*s/n*ln.stumpffC(i),o=e-s*s*s/Math.sqrt(ln.SUN_GM_AU3_PER_DAY2)*ln.stumpffS(i);return{x:a*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:a*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:a*this.perihelionPosition.z+o*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),s=Math.sqrt(ln.SUN_GM_AU3_PER_DAY2)*Math.abs(t),i=o=>{const r=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*ln.stumpffS(r)+c*o};let n=Math.max(1,s/this.elements.perihelionAu);for(;i(n)<s;)n*=2;let a=0;for(let o=0;o<ln.MAX_ITERATIONS&&n-a>1e-13*Math.max(1,n);o++){const r=(a+n)/2;i(r)<s?a=r:n=r}return e*(a+n)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,s=this.elements.inclinationDeg*Math.PI/180,i=Math.cos(t),n=Math.sin(t),a=Math.cos(e),o=Math.sin(e),r=Math.cos(s),c=Math.sin(s);return[{x:i*a-n*o*r,y:n*a+i*o*r,z:o*c},{x:-i*o-n*a*r,y:-n*o+i*a*r,z:a*c}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const s=Math.sqrt(t);return(s-Math.sin(s))/(s*s*s)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const Tp=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class Sw{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return Tp.filter(s=>Math.abs(e-s.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(s=>this.appearanceOf(s,t,e)).sort((s,i)=>s.magnitude-i.magnitude)[0]}static appearanceOf(t,e,s){const i=Kt(e),n=this.earthPositionAt(i),a=this.apparentPositionOf(t,2451545+i.tt,n),o=this.subtract(a,n),r=this.length(a),c=this.length(o),h=this.tailEndAt(t,a,n,r,i,e,s),l=this.horizontalOf(o,i,e,s);return{apparition:t,position:l,...h,heliocentricDistanceAu:r,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},n)),magnitude:this.magnitudeAt(t,r,c)}}static magnitudeAt(t,e,s){const i=t.absoluteMagnitude+5*Math.log10(s)+2.5*t.activityExponent*Math.log10(e);return Math.max(i,t.peakMagnitude)}static tailEndAt(t,e,s,i,n,a,o){if(t.tailLengthAu===void 0)return{};const r=1+t.tailLengthAu/i,c=this.subtract({x:e.x*r,y:e.y*r,z:e.z*r},s),h=this.subtract(e,s);return{tailEnd:this.horizontalOf(c,n,a,o),tailLengthDeg:this.angleBetween(h,c)}}static apparentPositionOf(t,e,s){const i=this.orbitOf(t);let n=i.positionAt(e);for(let a=0;a<2;a++){const o=this.length(this.subtract(n,s))/this.LIGHT_SPEED_AU_PER_DAY;n=i.positionAt(e-o)}return n}static horizontalOf(t,e,s,i){const n=yn(a1(),new It(t.x,t.y,t.z,e)),a=yn(Rm(e),n),o=$l(e,new Zn(i.lat,i.lng,i.elevationM),!0),r=new It(a.x-o.x,a.y-o.y,a.z-o.z,e),c=xh(r);return Wu(c.ra,c.dec,s,i)}static earthPositionAt(t){return yn(n1(),qn(z.Earth,t))}static julianDayOf(t){return 2451545+Kt(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const s=new ln(t.orbit);return this.orbits.set(t.id,s),s}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const s=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,s)))*180/Math.PI}}const kl=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class Lf{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return kl.filter(s=>this.magnitudeAt(s,e)!==void 0)}static appearancesAt(t,e){const s=this.julianDayOf(t),i=[];for(const n of kl){const a=this.magnitudeAt(n,s);a!==void 0&&i.push({outburst:n,position:Mi.ofJ2000(n.raHours,n.decDeg,t,e),magnitude:a})}return i.sort((n,a)=>n.magnitude-a.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return kl.find(e=>e.id===t)}static magnitudeAt(t,e){const s=t.lightCurve,i=e-t.startJd;if(s.length===0||i<s[0][0]||i>s[s.length-1][0])return;let n=1;for(;n<s.length-1&&s[n][0]<i;)n++;const[a,o]=s[n-1]??s[0],[r,c]=s[n]??s[0];if(r===a)return o;const h=Math.min(1,Math.max(0,(i-a)/(r-a)));return o+h*(c-o)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const xw=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],ph=6.5;class Ll{static activeAt(t){return xw.flatMap(e=>{const s=this.nearness(e,t);return s<=0?[]:[{shower:e,zhr:e.peakZhr*s,nearness:s}]})}static nearness(t,e){const s=this.dayOfYear(e),i=this.dayOfYear(this.asDate(t.start)),n=this.dayOfYear(this.asDate(t.peak)),a=this.dayOfYear(this.asDate(t.end)),o=this.wrappedDelta(s,n),r=this.wrappedDelta(n,i),c=this.wrappedDelta(a,n);return o<0?o<-r?0:1+o/r:o>0?o>c?0:1-o/c:1}static observedRatePerHour(t,e,s,i=ph){if(e<=0)return 0;const n=ph-i;return t*Math.sin(e*Math.PI/180)/Math.pow(s,n)}static radiantPosition(t,e,s){return Mi.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,s)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const s=t-e;return s>182?s-365:s<-182?s+365:s}}class Me{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const s=Kt(t),i=new bh(0,_g(t).elon-90,1),n=yn(l1(s),Vu(i,s)),a=xh(n);return Wu(a.ra,a.dec,t,e)}static observedRatePerHour(t,e=ph){const s=Me.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),i=ph-e;return(Me.QUIET_RATE_PER_HOUR+s)/Math.pow(Me.POPULATION_INDEX,i)}static schedule(t){const e=new Ih(t.seed^1542469173);return ni.schedule(t).map(s=>{const i=Me.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),n=s.fromRadiantDeg*Math.PI/180,a=Me.turnAround(i,e.between(0,360)),o={x:i.x*Math.cos(n)+a.x*Math.sin(n),y:i.y*Math.cos(n)+a.y*Math.sin(n),z:i.z*Math.cos(n)+a.z*Math.sin(n)};return{...s,radiant:Me.toHorizontal(o),bearingDeg:Me.bearingFrom(o,i)}})}static turnAround(t,e){const[s,i]=Me.basisAround(t),n=e*Math.PI/180;return{x:s.x*Math.cos(n)+i.x*Math.sin(n),y:s.y*Math.cos(n)+i.y*Math.sin(n),z:s.z*Math.cos(n)+i.z*Math.sin(n)}}static bearingFrom(t,e){const[s,i]=Me.basisAround(t),n=t.x*e.x+t.y*e.y+t.z*e.z,a=Me.normalise({x:e.x-t.x*n,y:e.y-t.y*n,z:e.z-t.z*n});return(Math.atan2(a.x*i.x+a.y*i.y+a.z*i.z,a.x*s.x+a.y*s.y+a.z*s.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},s=Me.normalise(Me.cross(t,e));return[s,Me.normalise(Me.cross(t,s))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=Me.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),s=Me.turnAround(e,t.bearingDeg),i=t.fromRadiantDeg*Math.PI/180;return Me.toHorizontal({x:e.x*Math.cos(i)+s.x*Math.sin(i),y:e.y*Math.cos(i)+s.y*Math.sin(i),z:e.z*Math.cos(i)+s.z*Math.sin(i)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,s=t.azimuthDeg*Math.PI/180,i=Math.cos(e);return{x:i*Math.sin(s),y:Math.sin(e),z:-i*Math.cos(s)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const Pu="https://ufoathome.org/tle/index.json";class es{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??es.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(Pu)||t.push(Pu),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${es.FIRST_SNAPSHOT}T00:00:00Z`)-es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS;if(t.getTime()<e)return!1;const s=await this.loadIndex();return s?Object.values(s.index.kinds).some(i=>t.getTime()>=Date.parse(i.from)-es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS&&t.getTime()<=Date.parse(i.to)+es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:s,base:i}=e,n=[],a=[];for(const o of Object.keys(s.kinds)){const r=await this.kindAt(o,t,s,i);n.push(...r),a.push(this.coverageOf(o,t,s,r.length>0))}return{objects:n,coverage:a,credit:s.credit,creditUrl:s.source}}async kindAt(t,e,s,i){const n=e.getTime(),a=s.binDays*es.DAY_MS,o=Math.floor(n/a),r=n-o*a<a/2?o-1:o+1,c=new Set(s.kinds[t].bins),h=[o,r].map(p=>new Date(p*a).toISOString().slice(0,10)).filter(p=>c.has(p));if(h.length===0)return[];const[l,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,i).href),...h.map(p=>this.binary(new URL(`${t}/${p}.bin`,i).href))]),f=new Map;for(const p of d)for(const g of es.decode(p,s.recordBytes)){const M=f.get(g.norad);(!M||Math.abs(g.epochMs-n)<Math.abs(M.epochMs-n))&&f.set(g.norad,g)}const m=[];for(const p of f.values()){const g=Math.abs(p.epochMs-n)/es.DAY_MS;if(g>es.MAX_ELEMENT_AGE_DAYS)continue;const M=l[p.norad]??{name:String(p.norad)};M.launch&&Date.parse(`${M.launch}T00:00:00Z`)>n||m.push({norad:p.norad,name:M.name,kind:t,launch:M.launch,stdMag:M.stdMag,elements:p,ageDays:g})}return m}coverageOf(t,e,s,i){const{from:n,to:a}=s.kinds[t],o=e.getTime(),r=es.MAX_ELEMENT_AGE_DAYS*es.DAY_MS,c=i?"covered":o<Date.parse(n)-r?"before":o>Date.parse(a)+r?"after":"gap";return{kind:t,status:c,from:n,to:a}}static decode(t,e){const s=new DataView(t),i=[];for(let n=0;n+e<=t.byteLength;n+=e)i.push({norad:s.getUint32(n,!0),epochMs:s.getFloat64(n+4,!0),bstar:s.getFloat32(n+12,!0),inclinationDeg:s.getFloat32(n+16,!0),raanDeg:s.getFloat32(n+20,!0),eccentricity:s.getFloat32(n+24,!0),argOfPerigeeDeg:s.getFloat32(n+28,!0),meanAnomalyDeg:s.getFloat32(n+32,!0),meanMotion:s.getFloat64(n+36,!0)});return i}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let s=this.files.get(t);return s||(s=this.fetchImpl(t).then(i=>{if(!i.ok)throw new Error(`${t}: ${i.status}`);return e(i)}),s.catch(()=>this.files.delete(t)),this.files.set(t,s)),s}}const e5=Object.freeze(Object.defineProperty({__proto__:null,TleArchive:es,UFOATHOME_TLE_INDEX_URL:Pu},Symbol.toStringTag,{value:"Module"}));class Tw{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const s=he.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?s:Math.max(this.lowerM,s)}if(e.inFrontM!==void 0){const s=he.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?s:Math.min(this.upperM,s)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:he.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:he.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Ra{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*Ra.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const s=Ra.degOver(t)/e;return s<1?1:Math.min(Ra.MAX_INSTANTS,Math.max(2,Math.ceil(s)))}static MAX_INSTANTS=64}class ss{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return Ra.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return ss.visualAidGrasp(t,e.focalLengthMm);const s=e.exposureSeconds??t.exposureSeconds,i=e.fNumber??t.fNumber;if(s===void 0||i===void 0||!(s>0)||!(i>0))return ss.EYE;const n=e.focalLengthMm??t.frame?.focalLengthMm??ss.UNKNOWN_CAMERA_FOCAL_MM,a=n/i,o=ss.resolutionArcsec(t,n,a);return{apertureMm:a,exposureSeconds:Math.min(s,ss.trailLimitedSeconds(o)),resolutionArcsec:o}}static visualAidGrasp(t,e){const s=t.visualAid,i=ss.EYE,n=e??t.frame?.focalLengthMm,a=s.magnification??(n!==void 0&&s.eyepieceFocalMm?n/s.eyepieceFocalMm:1),o=Math.min(s.apertureMm,i.apertureMm*a);return{apertureMm:Math.max(o,i.apertureMm),exposureSeconds:i.exposureSeconds,resolutionArcsec:i.resolutionArcsec/Math.max(1,Math.min(a,s.apertureMm/i.apertureMm))}}static resolutionArcsec(t,e,s){const n=(t.detailUm??ss.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*ss.ARCSEC_PER_RADIAN,a=1.22*ss.WAVELENGTH_M/(s/1e3)*ss.ARCSEC_PER_RADIAN;return Math.max(n,a)}static trailLimitedSeconds(t){return t/ss.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const s=ss.graspOf(t,e),i=ss.EYE,n=(s.apertureMm/i.apertureMm)**2,a=s.exposureSeconds/i.exposureSeconds,o=(i.resolutionArcsec/s.resolutionArcsec)**2;return 1.25*Math.log10(n*a*o)}static gainFor(t,e){const s=e.fieldOfViewDeg===void 0?void 0:je.focalLengthMmFor(t,e.fieldOfViewDeg);return ss.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:s,exposureSeconds:e.exposureSeconds})}}const Nf=111320,lr=Math.PI/180,Dw=1.02,Iw=1;class Lr{static of(t,e){const s=Lr.sightings(t,e);if(s.length<2)return;const i=Lr.baseline(s);if(!i)return;const{near:n,far:a,closedM:o}=i,r=Math.tan(a.widthDeg/2*lr)===0?0:Math.tan(n.widthDeg/2*lr)/Math.tan(a.widthDeg/2*lr);if(r<Dw)return;const c=o/(r-1),h=he.sizeMAt(c,n.widthDeg),l=s.map(d=>({t:d.t,m:he.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:l,nearestM:Math.min(...l.map(d=>d.m)),fromT:a.t,toT:n.t,closedM:o}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(s=>{const i=s.shapes.find(o=>o.sourceId===e)?.shape,n=i?.angular?.widthDeg,a=pt(t,s.t);return n===void 0||n<=0||a?.lat===void 0||a.lng===void 0?[]:[{t:s.t,widthDeg:n,lat:a.lat,lng:a.lng,sightAzimuthDeg:i?.aim?.azimuthDeg??a.headingDeg}]}).sort((s,i)=>s.t-i.t)}static baseline(t){let e;for(const s of t)for(const i of t){if(s.t>=i.t)continue;const n=Lr.closedAlongSight(s,i),[a,o,r]=n>=0?[i,s,n]:[s,i,-n];r<Iw||a.widthDeg<=o.widthDeg||(!e||r>e.closedM)&&(e={near:a,far:o,closedM:r})}return e}static closedAlongSight(t,e){const s=(e.lat-t.lat)*Nf,i=(e.lng-t.lng)*Nf*Math.cos(t.lat*lr),n=(t.sightAzimuthDeg??0)*lr;return s*Math.cos(n)+i*Math.sin(n)}}class ws{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:ws.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:ws.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:ws.atLeastNearest(t.derivedM),basis:"derived"};const e=ws.largest(t.range?.minM,t.crossing?.behindM),s=ws.smallest(t.range?.maxM,t.crossing?.inFrontM),i=e===void 0?void 0:e*ws.MARGIN,n=s===void 0?void 0:s/ws.MARGIN;return i!==void 0&&n!==void 0?{distanceM:ws.atLeastNearest(i<=n?Math.sqrt(i*n):i),basis:"bounded"}:i!==void 0?{distanceM:ws.atLeastNearest(i),basis:"bounded"}:n!==void 0&&n<ws.CONVENTIONAL_M?{distanceM:ws.atLeastNearest(n),basis:"bounded"}:{distanceM:ws.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(ws.NEAREST_M,t)}static largest(...t){const e=t.filter(s=>s!==void 0&&s>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(s=>s!==void 0&&s>0);return e.length===0?void 0:Math.min(...e)}}class X{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=4;static DEFAULT_CRUMBLING={perS:1.2,lifeS:4,magnitudeDrop:3,dropBack:.3,spreadKmS:1,sinkKmS:.6,trainS:2.5};static DEFAULT_BURST={perS:12,lifeS:3.5,magnitudeDrop:3.5,dropBack:.5,spreadKmS:1.5,sinkKmS:.9,trainS:2};static FLARE_MAGNITUDES=.5;static shedsOf(t){return t.sheds?t.sheds:[X.DEFAULT_CRUMBLING,...X.flareBursts(t)]}static flareBursts(t){const e=t.lightCurve??[],s=[];for(let i=1;i<e.length-1;i++){const n=e[i];e[i-1].absoluteMagnitude-n.absoluteMagnitude<X.FLARE_MAGNITUDES||e[i+1].absoluteMagnitude-n.absoluteMagnitude<X.FLARE_MAGNITUDES||s.push({...X.DEFAULT_BURST,fromT:n.t-1e3,untilT:n.t+1500})}return s}static FADE_MS=1e3;static FADED_MAGNITUDE=8;static TRAIN_POINTS=8;static leadAt(t,e){const s=t.track;if(s.length<2||e<s[0].t||e>s[s.length-1].t)return;let i=0;for(;i<s.length-2&&s[i+1].t<e;)i++;const n=s[i],a=s[i+1],o=a.t-n.t,r=o>0?(e-n.t)/o:0,[c,h]=X.alongGreatCircle(n,a,r);return{lat:c,lng:h,heightM:(n.altitudeKm+(a.altitudeKm-n.altitudeKm)*r)*1e3}}static mayDazzle(t){const e=Math.max(1,Math.min(...t.track.map(i=>i.altitudeKm))),s=5*Math.log10(e/X.STANDARD_DISTANCE_KM);return t.fragments.some(i=>Math.min(i.absoluteMagnitude,...(i.lightCurve??[]).map(a=>a.absoluteMagnitude))+s<=X.DAZZLING_MAGNITUDE)}static detonationsOf(t,e){const s=[];for(const i of t)i.fragments.forEach((n,a)=>{const o=X.piecesOf(i).find(c=>c.id===(n.id??String(a)));if(!o)return;const r=(n.lightCurve??[]).filter((c,h,l)=>(h===0||l[h-1].absoluteMagnitude>=c.absoluteMagnitude)&&(h===l.length-1||l[h+1].absoluteMagnitude>c.absoluteMagnitude)).map(c=>({t:c.t,magnitude:c.absoluteMagnitude}));r.push({t:o.untilT,magnitude:o.magnitudeAt(o.untilT)});for(const c of r){if(c.magnitude>X.DETONATING_MAGNITUDE||c.t<o.fromT||c.t>o.untilT)continue;const h=X.pieceAt(i,o,c.t);if(!h||h.heightM>X.AUDIBLE_BELOW_KM*1e3||s.some(d=>d.flashT===c.t&&d.reentryId===i.id))continue;const l=X.seenFrom(e,h).distanceKm;s.push({reentryId:i.id,flashT:c.t,t:c.t+l/X.SOUND_KM_S*1e3,distanceKm:l,loudness:Math.min(1,(.3+(X.DETONATING_MAGNITUDE-c.magnitude)/15)*Math.min(1,30/l))})}});return s.sort((i,n)=>i.t-n.t)}static DETONATING_MAGNITUDE=-12;static AUDIBLE_BELOW_KM=50;static SOUND_KM_S=.31;static DAZZLING_MAGNITUDE=-11;static absoluteMagnitudeAt(t,e){const s=t.lightCurve;if(!s||s.length===0)return t.absoluteMagnitude;if(e<=s[0].t)return s[0].absoluteMagnitude;for(let i=1;i<s.length;i++){const n=s[i-1],a=s[i];if(e<=a.t)return n.absoluteMagnitude+(a.absoluteMagnitude-n.absoluteMagnitude)*(e-n.t)/Math.max(a.t-n.t,1)}return s[s.length-1].absoluteMagnitude}static viewsAt(t,e,s){const i=[];for(const n of t)for(const a of X.piecesOf(n)){if(e<a.fromT||e>a.untilT)continue;const o=X.pieceAt(n,a,e);if(!o)continue;const r=X.seenFrom(s,o);if(r.altitudeDeg<0)continue;const c=Math.min(X.FADE_MS,(a.untilT-a.fromT)/4),h=c>0?Math.min(1,(e-a.fromT)/c,(a.untilT-e)/c):1,l=a.magnitudeAt(e)+5*Math.log10(r.distanceKm/X.STANDARD_DISTANCE_KM),d=l+(1-h)*Math.max(0,X.FADED_MAGNITUDE-l),f=[r];for(let m=1;m<=X.TRAIN_POINTS;m++){const p=Math.min(a.trainMs*m/X.TRAIN_POINTS,e-a.fromT),g=X.pieceAt(n,a,e-p);if(!g||(f.push(X.seenFrom(s,g)),p>=e-a.fromT))break}i.push({reentryId:n.id,fragmentId:a.id,head:r,magnitude:d,fade:h,color:a.color,train:f})}return i}static piecesOf(t){const e=X.pieces.get(t);if(e)return e;const s=t.track[0]?.t??0,i=t.track[t.track.length-1]?.t??0,n=[];return t.fragments.forEach((a,o)=>{const r=(a.lagS??0)*1e3,c={id:a.id??String(o),fromT:a.fromT??s,untilT:a.untilT??i,lagMsAt:()=>r,acrossKmAt:()=>0,belowKmAt:()=>0,magnitudeAt:h=>X.absoluteMagnitudeAt(a,h),color:a.color??X.DEFAULT_COLOR,trainMs:(a.trainS??X.DEFAULT_TRAIN_S)*1e3};n.push(c),X.shedsOf(a).forEach((h,l)=>n.push(...X.shedPieces(c,h,l)))}),X.pieces.set(t,n),n}static pieces=new WeakMap;static shedPieces(t,e,s=0){const i=e.fromT??t.fromT,n=Math.min(e.untilT??t.untilT,t.untilT);if(!(e.perS>0)||n<=i)return[];const a=Math.floor((n-i)/1e3*e.perS),o=e.spreadKmS??.3,r=e.sinkKmS??.3,c=e.trainS!==void 0?e.trainS*1e3:t.trainMs*(2/3),h=[];for(let l=0;l<a;l++){const d=A=>X.hash(`${t.id}/${s}/${l}/${A}`),f=i+(l+d(1))/e.perS*1e3,m=e.lifeS*(.4+1.2*d(2))*1e3,p=e.magnitudeDrop*(.5-.5*Math.log(1-.999*d(3))),g=e.dropBack*(.5+d(4)),M=o*(2*d(5)-1),v=r*(.5+d(6)),y=t.lagMsAt(f),w=t.acrossKmAt(f),b=t.belowKmAt(f),E=A=>Math.max(0,A-f)/1e3;h.push({id:`${t.id}.${s}.${l}`,fromT:f,untilT:Math.min(f+m,X.endOf(t)),lagMsAt:A=>y+1e3*X.lagOfBraking(2*g,E(A)),acrossKmAt:A=>w+M*E(A),belowKmAt:A=>b+v*E(A),magnitudeAt:A=>t.magnitudeAt(Math.min(A,t.untilT))+p,color:t.color,trainMs:c})}return h}static lagOfBraking(t,e){return t<=0||e<=0?0:e-(1-Math.exp(-t*e))/t}static endOf(t){return t.untilT}static hash(t){let e=2166136261;for(let s=0;s<t.length;s++)e^=t.charCodeAt(s),e=Math.imul(e,16777619);return(e>>>0)/4294967296}static pieceAt(t,e,s){const i=s-e.lagMsAt(s),n=X.leadAt(t,i);if(!n)return;const a=e.acrossKmAt(s),o=n.heightM-e.belowKmAt(s)*1e3;if(a===0)return{...n,heightM:o};const r=X.leadAt(t,i-1e3)??n;return{...X.across(r,n,a),heightM:o}}static across(t,e,s){const i=X.DEG,n=t.lat*i,a=e.lat*i,o=(e.lng-t.lng)*i,r=Math.atan2(Math.sin(o)*Math.cos(a),Math.cos(n)*Math.sin(a)-Math.sin(n)*Math.cos(a)*Math.cos(o))+Math.PI/2,c=s/6371,h=Math.asin(Math.sin(a)*Math.cos(c)+Math.cos(a)*Math.sin(c)*Math.cos(r)),l=e.lng*i+Math.atan2(Math.sin(r)*Math.sin(c)*Math.cos(a),Math.cos(c)-Math.sin(a)*Math.sin(h));return{lat:h/i,lng:l/i}}static seenFrom(t,e){const s=X.ecef(t),i=X.ecef(e),n=i[0]-s[0],a=i[1]-s[1],o=i[2]-s[2],r=t.lat*X.DEG,c=t.lng*X.DEG,h=-Math.sin(c)*n+Math.cos(c)*a,l=-Math.sin(r)*Math.cos(c)*n-Math.sin(r)*Math.sin(c)*a+Math.cos(r)*o,d=Math.cos(r)*Math.cos(c)*n+Math.cos(r)*Math.sin(c)*a+Math.sin(r)*o,f=Math.hypot(h,l,d);return{altitudeDeg:Math.asin(d/f)/X.DEG,azimuthDeg:(Math.atan2(h,l)/X.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*X.DEG,s=t.lng*X.DEG,i=Math.sin(e),n=X.A/Math.sqrt(1-X.E2*i*i);return[(n+t.heightM)*Math.cos(e)*Math.cos(s),(n+t.heightM)*Math.cos(e)*Math.sin(s),(n*(1-X.E2)+t.heightM)*i]}static alongGreatCircle(t,e,s){const i=h=>{const l=h.lat*X.DEG,d=h.lng*X.DEG;return[Math.cos(l)*Math.cos(d),Math.cos(l)*Math.sin(d),Math.sin(l)]},n=i(t),a=i(e),o=Math.max(-1,Math.min(1,n[0]*a[0]+n[1]*a[1]+n[2]*a[2])),r=Math.acos(o);let c;if(r<1e-12)c=n;else{const h=Math.sin((1-s)*r)/Math.sin(r),l=Math.sin(s*r)/Math.sin(r);c=[n[0]*h+a[0]*l,n[1]*h+a[1]*l,n[2]*h+a[2]*l]}return[Math.atan2(c[2],Math.hypot(c[0],c[1]))/X.DEG,Math.atan2(c[1],c[0])/X.DEG]}}class Do{static typed=new Map;static of(t){return Do.typed.get(t)}static set(t,e){const s=e.trim();s===""?Do.typed.delete(t):Do.typed.set(t,s)}static forget(){Do.typed.clear()}}class ad{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=ad.FIRST_DAY}}class Cf{constructor(t,e,s){this.citation=t,this.covers=e,this.load=s}loading;mayCover(t){return this.covers(t)}async between(t,e,s,i){try{return await(await this.provider()).between(t,e,s,i)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const Rw="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",Ow="Aircraft positions: Flightradar24 API (https://fr24api.flightradar24.com/)",_f="flightradar24",Pw=ke.point("aircraft").provide(ke.BUILT_IN,[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new Cf(Rw,u=>ad.mayCover(u),async()=>new(await H(async()=>{const{AdsbLolArchiveProvider:u}=await import("./AdsbLolArchiveProvider-JK7ddZzC.js");return{AdsbLolArchiveProvider:u}},__vite__mapDeps([48,1,2,3,4,5,6,7,8,9,10]),import.meta.url)).AdsbLolArchiveProvider)},{id:_f,name:"Flightradar24",credit:"Flightradar24, on your own subscription",creditUrl:"https://fr24api.flightradar24.com/",keyUrl:"https://fr24api.flightradar24.com/key-management",create:()=>new Cf(Ow,u=>u>=Date.UTC(2016,4,11)&&u<=Date.now(),async()=>new(await H(async()=>{const{Flightradar24Provider:u}=await import("./Flightradar24Provider-XASYwL-N.js");return{Flightradar24Provider:u}},__vite__mapDeps([49,1,2,3,4,5,6,7,8,9,10]),import.meta.url)).Flightradar24Provider({token:()=>Do.of(_f)}))}]);class $e{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,s){const i=$e.positionAt(t,s);if(!i)return;const n=X.seenFrom(e,i.geo);if(!(n.altitudeDeg<0))return{track:t,sky:n,altitudeFt:i.altitudeFt,groundSpeedKt:i.groundSpeedKt,trackDeg:i.trackDeg,angularRateDegPerS:$e.angularRate(t,e,s)}}static viewsAt(t,e,s){return t.flatMap(i=>$e.seenFrom(i,e,s)??[])}static groundDistanceKm(t,e){const s=Math.PI/180,i=Math.sin((e.lat-t.lat)*s/2)**2+Math.cos(t.lat*s)*Math.cos(e.lat*s)*Math.sin((e.lng-t.lng)*s/2)**2;return 2*$e.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(i)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const s=t.points;if(s.length===0||e<s[0].t||e>s[s.length-1].t)return;let i=0;for(;i<s.length-1&&s[i+1].t<=e;)i++;const n=s[i],a=s[i+1]??n,o=a.t-n.t;if(o>$e.MAX_GAP_S*1e3)return;const r=o>0?(e-n.t)/o:0,c=n.altitudeFt+(a.altitudeFt-n.altitudeFt)*r,h=(a.lng-n.lng+540)%360-180;return{geo:{lat:n.lat+(a.lat-n.lat)*r,lng:$e.wrapLongitude(n.lng+h*r),heightM:c*$e.FT_TO_M},altitudeFt:c,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg}}static angularRate(t,e,s){const i=$e.positionAt(t,s-500),n=$e.positionAt(t,s+500);if(!i||!n)return;const a=$e.unit(X.seenFrom(e,i.geo)),o=$e.unit(X.seenFrom(e,n.geo)),r=Math.min(1,Math.max(-1,a[0]*o[0]+a[1]*o[1]+a[2]*o[2]));return Math.acos(r)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,s=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(s),Math.cos(e)*Math.cos(s),Math.sin(e)]}}const zf="https://ufoathome.org/fireballs/index.json";class Vi{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Vi.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(zf)||t.push(zf),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Vi.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Vi.mayCover(e))return;const s=await this.loadIndex();if(!s)return;const i=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...i].some(a=>a>=s.index.from&&a<=s.index.to)?(await Promise.all([...i].filter(a=>s.index.months.includes(a)).map(a=>this.monthOf(a,s.base)))).flat().filter(a=>a.t>=t&&a.t<=e):void 0}static seenFrom(t,e){const s=Vi.peakFraction(t),i={lat:t.from[0]+(t.to[0]-t.from[0])*s,lng:t.from[1]+(t.to[1]-t.from[1])*s,heightM:t.peakHeightKm*1e3},n=X.seenFrom(e,i);if(!(n.altitudeDeg<0))return{record:t,peak:n,magnitude:t.peakMagnitude+5*Math.log10(n.distanceKm/X.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const s=t.t-e,i=s+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:s,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:i,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Vi.COLOR,trainS:Vi.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let s=this.months.get(t);return s||(s=this.fetchImpl(new URL(`${t}.json`,e).href).then(i=>i.ok?i.json():[]).catch(()=>[]),this.months.set(t,s)),s}}class Mn{static FIRST_YEAR=1932;static AURORA_ID="gfz-kp";fetchImpl;baseUrls;years=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.baseUrls=t.baseUrls??Mn.defaultBaseUrls()}static defaultBaseUrls(){const t=[];typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/kp/",location.href).href);const e="https://ufoathome.org/kp/";return t.includes(e)||t.push(e),t}static mayCover(t){return new Date(t).getUTCFullYear()>=Mn.FIRST_YEAR}async between(t,e){if(!Mn.mayCover(e))return;const s=[],i=new Date(t).getUTCFullYear(),n=new Date(e).getUTCFullYear();for(let a=i;a<=n;a++){const o=await this.yearOf(a);if(!o)continue;const{stepMs:r,values:c}=o,h=Date.UTC(a,0,1),l=Math.max(0,Math.floor((t-h)/r)-1),d=Math.min(c.length-1,Math.ceil((e-h)/r));for(let f=l;f<=d;f++)c[f]>=0&&s.push({t:h+f*r+r/2,kp:c[f]/3})}return s.length>0?s:void 0}static asAurora(t,e){return{id:Mn.AURORA_ID,activity:t.map(s=>({t:s.t-e,kp:s.kp}))}}yearOf(t){let e=this.years.get(t);return e||(e=(async()=>{if(!(t<Mn.FIRST_YEAR))for(const s of this.baseUrls)try{const i=await this.fetchImpl(new URL(`${t}.json`,s).href);if(!i.ok)continue;const n=await i.json();return{stepMs:n.stepHours*36e5,values:n.values}}catch{}})(),this.years.set(t,e)),e}}class Gn{static POLES=[{year:1900,lat:78.7,lng:-68.8},{year:1925,lat:78.6,lng:-68.6},{year:1950,lat:78.5,lng:-68.8},{year:1975,lat:78.8,lng:-70},{year:1990,lat:79.2,lng:-71.1},{year:2e3,lat:79.6,lng:-71.6},{year:2010,lat:80.1,lng:-72.2},{year:2015,lat:80.4,lng:-72.6},{year:2020,lat:80.7,lng:-72.7},{year:2025,lat:80.8,lng:-72.7}];static poleAt(t){const e=t.getUTCFullYear()+t.getUTCMonth()/12,s=Gn.POLES;if(e<=s[0].year)return{lat:s[0].lat,lng:s[0].lng};for(let n=1;n<s.length;n++){if(e>s[n].year)continue;const a=s[n-1],o=s[n],r=(e-a.year)/(o.year-a.year);return{lat:a.lat+(o.lat-a.lat)*r,lng:a.lng+(o.lng-a.lng)*r}}const i=s[s.length-1];return{lat:i.lat,lng:i.lng}}static earthVector(t,e){const s=t*Math.PI/180,i=e*Math.PI/180;return[Math.cos(s)*Math.cos(i),Math.cos(s)*Math.sin(i),Math.sin(s)]}static latitudeOf(t,e,s){const i=Gn.poleAt(s),[n,a,o]=Gn.earthVector(i.lat,i.lng),[r,c,h]=Gn.earthVector(t,e);return Math.asin(Math.max(-1,Math.min(1,n*r+a*c+o*h)))*180/Math.PI}static axisAt(t,e,s){const i=Gn.poleAt(s),n=Gn.earthVector(i.lat,i.lng),a=t*Math.PI/180,o=e*Math.PI/180,r=[-Math.sin(o),Math.cos(o),0],c=[-Math.sin(a)*Math.cos(o),-Math.sin(a)*Math.sin(o),Math.cos(a)],h=[Math.cos(a)*Math.cos(o),Math.cos(a)*Math.sin(o),Math.sin(a)],l=(d,f)=>d[0]*f[0]+d[1]*f[1]+d[2]*f[2];return[l(n,r),l(n,h),-l(n,c)]}static localTime(t,e,s){const i=(h,l)=>h[0]*l[0]+h[1]*l[1]+h[2]*l[2],n=h=>{const l=i(h,e);return[h[0]-l*e[0],h[1]-l*e[1],h[2]-l*e[2]]},a=n(t),o=n(s),r=[e[1]*o[2]-e[2]*o[1],e[2]*o[0]-e[0]*o[2],e[0]*o[1]-e[1]*o[0]];return((12+Math.atan2(i(r,a),i(o,a))*12/Math.PI)%24+24)%24}static footLatitude(t,e,s=100,i=6371){const n=Math.cos(t*Math.PI/180),a=Math.sqrt(Math.min(1,n*n*(i+s)/(i+e)));return Math.sign(t)*(Math.acos(a)*180)/Math.PI}}Wm();const Dp="satellites-change",Ip="fireballs-change",Rp="references-change",Op="aircraft-change",Pp="rr0-confrontation",Ff="comet:",Hf="nova:",kw=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,Lw=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,Nw=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,Cw=-18,_w={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Rc={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class nt extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Lo,No,ma]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;flightMark;markedFlight;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;approaches={key:"",of:new Map};distanceHypotheses=new Map;depths=new Map;directionScratch=new D;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new es;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Vi;fireballs;static geomagneticArchive=new Mn;archivedAurora;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=Pw[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return nt.trafficRuntimeLoading??=H(()=>import("./trafficRuntime-CyYep5Cc.js"),__vite__mapDeps([50,42,51,1,7,6,2,3,4,5,8,9,10]),import.meta.url).then(t=>nt.trafficRuntime=t),nt.trafficRuntimeLoading.catch(()=>{nt.trafficRuntimeLoading=void 0}),nt.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new Aa;vehicleAudio=new Zd;aircraftAudio;vehicleHearing=new Zc;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;decorModelsAsked=new Set;thunderTimeoutId;handleFullscreenChange=()=>{this.resizeToStage(),this.hoverTooltip.hidden=!0;for(const t of[this.hoverTooltip,this.shadow.getElementById("credits-panel")])t&&typeof t.hidePopover=="function"&&t.matches(":popover-open")&&t.hidePopover();this.tooltipOver=document.fullscreenElement};handlePointerMove=t=>{if(this.lastHover={clientX:t.clientX,clientY:t.clientY,altKey:t.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&t.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=t.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(t,e){const s=this.ufoElement.canvasElement.getBoundingClientRect();if(s.width===0||s.height===0)return!0;const i=(t.clientX-s.left)/s.width*2-1,n=1-(t.clientY-s.top)/s.height*2;return this.sceneRenderer.ghostsReadableAt(i,n)?this.sceneRenderer.pickGhostAt(i,n)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>nt.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;tooltipOver=null;hoverAt(t){if(this.showCompassFor({hovered:!0}),this.holding||this.poster.up){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,s=e.getBoundingClientRect();if(s.width===0||s.height===0)return;const i=(t.clientX-s.left)/s.width*e.width,n=(t.clientY-s.top)/s.height*e.height;if(this.ufoElement.hasVisibleShapeAt(i,n)){this.hoverTooltip.hidden=!0;return}const a=(t.clientX-s.left)/s.width*2-1,o=-((t.clientY-s.top)/s.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(a,o))return;const r=this.pickAt(a,o,!0,t.altKey);r?this.showHoverTooltip(t,t.altKey&&r.detail?r.detail():r.name):this.hoverTooltip.hidden=!0,this.showGhostPath(r?.path,s)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const s=this.stageElement.getBoundingClientRect(),i=d=>({x:e.left-s.left+(d.x+1)/2*e.width,y:e.top-s.top+(1-d.y)/2*e.height}),n=i(t.from),a=i(t.to),o=i({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${s.width} ${s.height}`);const[r,c,h,l]=Array.from(this.ghostPath.children);for(const d of[r,c])d.setAttribute("x1",String(n.x)),d.setAttribute("y1",String(n.y)),d.setAttribute("x2",String(a.x)),d.setAttribute("y2",String(a.y));h.setAttribute("cx",String(o.x)),h.setAttribute("cy",String(o.y)),l.setAttribute("cx",String(a.x)),l.setAttribute("cy",String(a.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,s=!0,i=!1){const n=this.naming,a=n.names;if(i&&this.sceneRenderer.pickDropAt(t,e)){const E=a.ghostTooltip,A=E.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:A,detail:()=>E.dropDetail.replace("{name}",A)}}const o=this.sceneRenderer.pickBodyAt(t,e);if(o)return{kind:"sky",id:o,name:this.bodyName(o)};const r=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,c=r?this.interpretationShown?.bodies.find(E=>E.id===r):void 0,h=c?this.said.read(c.title)||this.explainedName(c.explains)||this.kindName(c):void 0;if(r!==void 0&&h)return{kind:"body",id:r,name:h};const l=this.skyEventPickAt(t,e,(E,A)=>!A.inSky);if(l)return l;const d=s?this.ghostPick(t,e):void 0;if(d)return d;if(this.sceneRenderer.pickAfterimageAt(t,e)){const E=this.naming.names.afterimageTooltip;return{kind:"afterimage",name:E.name,detail:()=>E.detail.replace("{name}",E.name)}}const f=this.pickDecorAt(t,e)??this.sceneRenderer.pickPeakAt(t,e),m=f?this.ufoElement.sighting.decor.find(E=>E.id===f):void 0;if(m){const E=this.said.read(m.title)||n.decorKind(m.kind);return{kind:"decor",id:m.id,name:E,detail:()=>this.decorTooltip(m,E)}}const p=this.sceneRenderer.pickRailwayAt(t,e);if(p){const E=a.railwayTooltip;return{kind:"railway",id:p.line.id,name:Ci.name(p.line,E),detail:()=>Ci.detail(p,E,A=>this.distanceText(A))}}const g=this.trafficTooltipAt(t,e);if(g)return{kind:"traffic",name:g};const M=this.skyEventPickAt(t,e,(E,A)=>A.inSky===!0&&!E.pickedAfterSatellites);if(M)return M;const v=this.sceneRenderer.pickSatelliteAt(t,e);if(v)return{kind:"satellite",name:a.satelliteTooltip.replace("{name}",v.name).replace("{mag}",v.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(v.heightKm).toLocaleString())};const y=this.skyEventPickAt(t,e,(E,A)=>A.inSky===!0&&E.pickedAfterSatellites===!0);if(y)return y;const w=this.sceneRenderer.pickOpticsAt(t,e);if(w){const E=a.opticsTooltips[w.id].replace("{angle}",String(Math.round(w.angleDeg??0)));return{kind:"optics",id:w.id,name:E.split(" — ")[0],detail:()=>E}}const b=this.sceneRenderer.pickStarAt(t,e);if(b){const E=b.star.mag,A=b.altitudeDeg,S=A<0?a.starTooltipBelow:a.starTooltip,x=n.star(b.star);return{kind:"star",name:x,detail:()=>S.replace("{name}",x).replace("{mag}",E.toLocaleString(void 0,{maximumFractionDigits:Math.abs(E)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(A))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const s=this.ufoElement.canvasElement,i={x:8/Math.max(1,s.clientWidth),y:8/Math.max(1,s.clientHeight)},n=`${Math.round(t/i.x)}:${Math.round(e/i.y)}`,a=performance.now(),o=this.ghostLights.get(n);if(o&&a-o.atMs<nt.GHOST_LIGHT_KEPT_MS)return o.light;let r=this.shiningDecorNear(t,e,2*Math.max(i.x,i.y)),c;if(!r)for(const[h,l]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+h*i.x,e+l*i.y,!1);if(d?.kind==="star")c??=d;else if(d){r=d;break}}return r??=this.shiningDecorNear(t,e,6*Math.max(i.x,i.y)),r??=c,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(n,{light:r??null,atMs:a}),r??null}ghostPick(t,e){const s=this.sceneRenderer.pickGhostAt(t,e);if(!s)return;const i=this.naming.names.ghostTooltip,n=s.beyond?{kind:"sky",id:"sun",name:this.bodyName("sun")}:this.lightOfGhost(s.source.x,s.source.y)??void 0,a=(n?.kind==="star"?n.name.split(" — ")[0]:n?.name)??i.unnamed,o=s.ghost,c=(wt.scatters(o)?i.halo:o.cause==="glass"?i.double:i.ghost).replace("{name}",a),h=o.scale<0?i.opposite:o.scale===1?i.around:i.sameSide;return{kind:"ghost",id:n?.id,name:c,detail:()=>i.detail.replace("{name}",c).replace("{cause}",i.causes[o.cause??"lens"]).replace("{where}",h),path:{from:{x:2*(o.offset?.[0]??0)+o.scale*s.source.x,y:2*(o.offset?.[1]??0)+o.scale*s.source.y},to:s.source}}}shiningDecorNear(t,e,s){let i;for(const n of this.ufoElement.sighting.decor){if(!(n.kind==="streetlight"||n.kind==="trafficlight"||(n.lights?.length??0)>0||n.kind==="vehicle"&&n.lit))continue;const o=this.sceneRenderer.decorScreenBox(n.id);if(!o)continue;const r=Math.hypot(Math.max(o.minX-t,0,t-o.maxX),Math.max(o.minY-e,0,e-o.maxY));if(r>s||i&&r>=i.distance)continue;const c=this.said.read(n.title)||this.naming.decorKind(n.kind);i={distance:r,pick:{kind:"decor",id:n.id,name:c}}}return i?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(s=>[s.t,s.weather.precipitationType,s.weather.precipitationIntensity,s.weather.windDirectionDeg,s.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const s=new pa(i=>{if(!wt.records(t.instrumentAt(i*1e3))||!wt.falling(t.lensAt(i*1e3)))return 0;const n=Ko(t,i*1e3),a=pt(t,i*1e3);return(n.precipitationAmount??1)*wt.impactRate(n,t.lens?.glass,a&&{headingDeg:a.headingDeg??0,pitchDeg:a.pitchDeg,windFromDeg:n.windDirectionDeg,windSpeedMS:n.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:s}}return this.glassWetting.wetting}glassWetting;get skyEventsShown(){return this.skyEventsOf(this.ufoElement.sighting)}skyEventsStartDate;skyEventsMerged;skyEventsOf(t){const e=t.skyEvents,s=this.fireballs?.reentries,i=e?.auroras?.length?void 0:this.archivedAurora?.aurora,n=this.skyEventsMerged;if(n&&n.stated===e&&n.fireballs===s&&n.aurora===i)return n.shown;let a=s?.length?{...e,reentries:[...e?.reentries??[],...s]}:e;return i&&(a={...a,auroras:[i]}),this.skyEventsMerged={stated:e,fireballs:s,aurora:i,shown:a},a}skyEventTexts=new Map;skyEventTextsLanguage;loadSkyEventTexts(t){const e=pr(pn.preferencesFor(this),gr);e!==this.skyEventTextsLanguage&&(this.skyEventTexts.clear(),this.skyEventTextsLanguage=e);for(const s of t)this.skyEventTexts.has(s)||s.messages.load(e).then(i=>{this.skyEventTextsLanguage===e&&this.skyEventTexts.set(s,i)},()=>{})}skyEventPickAt(t,e,s){const i=this.skyEventsShown;if(!i)return;const n=this.sceneRenderer.pickSkyEventAt(t,e,s),a=n?fu.map(d=>vn.of(d)).find(d=>d.key===n.kind):void 0,o=n&&a?vn.eventsOf(i,a).find(d=>d.id===n.id):void 0;if(!n||!a||!o)return;const r=this.skyEventTexts.get(a);if(!r){this.loadSkyEventTexts([a]);return}const c=this.said.read(o.title)||r.name,h=a.describe?.(o,n,{said:this.said,texts:r,name:c,distance:d=>this.distanceText(d)}),l=h?.detail??(n.distanceM!==void 0?`${c}, ${this.distanceText(n.distanceM)}`:void 0);return{kind:a.pickKind??"skyEvent",id:o.id,name:h?.name??c,...l!==void 0?{detail:()=>l}:{}}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const s=h=>h.toLocaleString(void 0,{maximumFractionDigits:h<10?1:0}),i=C.sizeOf(t),n=this.sceneRenderer.decorDistanceM(t.id),a=n===void 0?"":this.distanceText(n),r=this.naming.names.decorTooltip.replace("{name}",e).replace("{size}",`${s(i.widthM)} × ${s(i.lengthM)} × ${s(i.heightM)} m`),c=this.said.read(t.note);return c?`${r.replace("{distance}",a)}. ${c}`:r.replace("{distance}",a)}computedKinds=new Map;computedKindTexts=new Map;bodyModelKinds=new Map;showInterpretation(t){const e=Lh.kinds(),s=this.obstaclesOf(this.ufoElement.sighting.decor);this.interpretationObstacles=s;const{interpretation:i,kindOf:n}=Tn.expandWithKinds(t,e,{obstacles:s});if(this.interpretationAsked=t,this.interpretationShown=i,this.computedKinds=n,this.loadComputedKindTexts(),Tn.loaded(t,e))return;const a=Tn.load(t,e);this.sceneRenderer.holdUntil(a),a.then(()=>{this.interpretationAsked!==t||!Tn.loaded(t,e)||(this.showInterpretation(t),this.ufoElement.refreshSoundControls(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())})}interpretationAsked;interpretationObstacles=yd.NONE;obstaclesMadeOf;obstaclesOf(t){return this.obstaclesMadeOf?.decor!==t&&(this.obstaclesMadeOf={decor:t,obstacles:yd.of(t,e=>C.sizeOf(e))}),this.obstaclesMadeOf.obstacles}recomputeAmongNewDecor(){const t=this.interpretationAsked;!t||!Tn.computes(t,Lh.kinds())||this.obstaclesOf(this.ufoElement.sighting.decor).signature!==this.interpretationObstacles.signature&&(this.showInterpretation(t),this.ufoElement.refreshSoundControls())}computedInterpretation(t){const e=Lh.kinds(),s=Tn.loaded(t,e)?Promise.resolve():Tn.load(t,e),{interpretation:i,phenomenonOf:n}=Tn.expandWithKinds(t,e,{obstacles:this.obstaclesOf(this.ufoElement.sighting.decor)});return{interpretation:i??t,phenomenonOf:n,loaded:s}}loadComputedKindTexts(){const t=this.namesLanguage;if(t)for(const e of new Set(this.computedKinds.values()))this.computedKindTexts.has(e)||e.messages.load(t).then(s=>{t===this.namesLanguage&&this.computedKindTexts.set(e,s)}).catch(()=>{})}kindName(t){const e=this.computedKinds.get(t.id),s=e?this.computedKindTexts.get(e):void 0;if(s?.name)return s.name;const i=t.model.id;if(i==="figure")return this.naming.decorKind("entity");if(!i||t.model.url!==void 0)return;if(!this.bodyModelKinds.has(i)){this.bodyModelKinds.set(i,void 0),this.sceneRenderer.entryOfDecorModel(i).then(a=>this.bodyModelKinds.set(i,[a?.kind].flat()[0])).catch(()=>{});return}const n=this.bodyModelKinds.get(i);return n&&this.naming.decorKind(n)||void 0}explainedName(t){if(!t?.length)return;const e=this.ufoElement.sighting.timeline.allKeyframes,s=t.map(i=>{for(const n of e){const a=this.said.read(n.shapes.find(o=>o.sourceId===i)?.shape.title);if(a)return a}}).filter(i=>!!i);return s.length?s.join(", "):void 0}bodyName(t){const e=t.startsWith(Ff)?t.slice(Ff.length):void 0,s=e?Tp.find(n=>n.id===e):void 0;if(s)return this.naming.comet(s);const i=t.startsWith(Hf)?Lf.byId(t.slice(Hf.length)):void 0;return i?this.naming.nova(i):this.naming.body(t)}get naming(){return this.sceneNaming}sceneNaming=new If;namesLanguage;ready=Promise.resolve();async loadSceneNames(){const t=pr(pn.preferencesFor(this),gr);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await Np(t);t===this.namesLanguage&&(this.applySceneNaming(new If(e)),this.computedKindTexts.clear(),this.loadComputedKindTexts())}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let s=0;const i=(n,a)=>{n.setAttribute("aria-label",a),n.replaceChildren(),a.split(" ").forEach((o,r)=>{r>0&&n.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of o){const l=document.createElement("span");l.className="scene-loader-letter",l.style.setProperty("--i",String(s++)),l.textContent=h,c.append(l)}n.append(c),s++})};i(this.loaderNotVideo,t),s+=6,i(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t,t.loaded&&(this.creditsButton.title=t.names.credits,this.creditsButton.setAttribute("aria-label",t.names.credits),this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names.compassPoints))}showHoverTooltip(t,e){const s=this.hoverTooltip;if(s.textContent=e,s.hidden=!1,typeof s.showPopover=="function"){const l=document.fullscreenElement;s.matches(":popover-open")&&l!==this.tooltipOver&&s.hidePopover(),s.matches(":popover-open")||s.showPopover(),this.tooltipOver=l}const{innerWidth:i,innerHeight:n}=window,a=12,o=4,r=Math.min(t.clientX+a,i-s.offsetWidth-o),c=t.clientY+a,h=c+s.offsetHeight+o>n?t.clientY-a-s.offsetHeight:c;s.style.left=`${Math.max(o,r)}px`,s.style.top=`${Math.max(o,h)}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.showCompassFor({hovered:!1})};hearDetonations(t,e,s,i){const n=`${s.lat.toFixed(4)},${s.lng.toFixed(4)}`,a=this.detonationsFor;(!a||n!==a.key||t.length!==a.reentries.length||t.some((c,h)=>c!==a.reentries[h]))&&(this.detonationsFor={reentries:[...t],key:n,detonations:t.length?X.detonationsOf(t,s):[]});const o=this.detonationsFor.detonations;if(i)return;const r=this.lastDetonationT;if(this.lastDetonationT=e,!(r===void 0||e<r||e-r>nt.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const c of o)c.t>r&&c.t<=e&&this.weatherAudio.playDetonation(c.loudness)}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],s=pt(t,0),i=t.event.place?.[0],n=s?.lat??i?.lat,a=s?.lng??i?.lng;return e.length>0&&n!==void 0&&a!==void 0&&X.detonationsOf(e,{lat:n,lng:a,heightM:this.altitudeOf(s)}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){if(clearTimeout(this.thunderTimeoutId),this.filmSound){this.filmThunderAtMs=this.lastTimeMs+De.thunderDelayMs(t)*this.ufoElement.playbackRate;return}this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),De.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(Ko(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){if(this.filmSound)return;const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{if(this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const e=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&e-this.lastPlayingHoverMs>=nt.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.placeFlightMark(),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing",e=t||this.filming;this.sceneRenderer.setAnimationsRunning(e,e);const s=t||this.filmSound!==void 0;this.weatherAudio.setPaused(!s),this.vehicleAudio.setPaused(!s),this.aircraftAudio?.setPaused(!s),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${v2}</style>${M2}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new N(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(Rp));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new kr(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=n=>{this.holding=n,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.flightMark=this.shadow.getElementById("flight-mark"),this.ufoElement=document.createElement(au),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapSnapshotSource=n=>this.snapshotMapOf(n),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",n=>this.lookToward(n.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const s=this.shadow.getElementById("credits-panel"),i=this.shadow.getElementById("credits-list");s.addEventListener("beforetoggle",n=>{n.newState==="open"&&Qe.fill(i,this)}),this.sceneRenderer.onMapSubjectBounds=n=>this.ufoElement.setMapSubjectBounds(n),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(Km,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(n,a)=>this.seekPreviewOf(a).paint(n,a),typeof VideoEncoder<"u"&&typeof OffscreenCanvas<"u"&&(this.ufoElement.filmer={film:(n,a,o)=>this.film(n,a,o),generativeKit:(n,a,o)=>this.generativeKit(n,a,o),fileName:()=>this.filmFileName(),kitFileName:()=>this.filmFileName().replace(/\.mp4$/," - kit.zip"),pictureSize:()=>this.filmPictureSize(),hasMap:()=>this.ufoElement.hasObserverMap,durationS:()=>this.ufoElement.seekableDuration/this.filmRate()/1e3,positionS:()=>this.ufoElement.currentTime/this.filmRate()/1e3}),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=n=>n.vehicle!==void 0||n.decor.some(a=>a.engine!==void 0)||n.decor.some(a=>gd.kindOf(a,this.decorModelSounds.get(a.model?.id??""))!==void 0)||this.interpretationShown?.bodies.some(a=>a.sound)===!0||n.weatherTrack.allKeyframes.some(a=>a.weather.precipitationType!=="none"||a.weather.windSpeed>1)||this.detonates(n)||(this.traffic?.audible?.size??0)>0,this.ufoElement.addEventListener("referenceview",n=>this.applyReferenceView(n.detail)),this.ufoElement.addEventListener("traceview",n=>this.sceneRenderer.setTracesShown(n.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const n of nt.GESTURES)this.addEventListener(n,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Nr(pn.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const s=t.vehicle;return!s||!ns.isRoad(s.kind)?void 0:{setting:Hl.at(s.headlights??"auto",s.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}}travelHeadingAt(t,e){const s=pt(t,e);if(!s)return 0;for(const i of[400,-400]){const n=pt(t,e+i);if(!n||s.lat===void 0||s.lng===void 0||n.lat===void 0||n.lng===void 0)break;const a=ot(n.lat,n.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)<.8)continue;return(Math.atan2(a.x,-a.z)*180/Math.PI+(i<0?180:0)+360)%360}return s.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const s=e.flatMap(n=>n.pose.lat!==void 0&&n.pose.lng!==void 0?[{lat:n.pose.lat,lng:n.pose.lng}]:[]),i=s.length>=2?s:void 0;return this.routeCache={track:t,count:e.length,route:i},i}traceLabels(t){const e=pn.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const s=new Map;for(const i of t){const n=this.said.read(i.title);n&&s.set(i.id,n)}this.traceLabelsFor={traces:t,language:e,labels:s}}return this.traceLabelsFor.labels}connectedCallback(){ke.changes.addEventListener("change",this.onModulesChanged),this.saidTexts=void 0,this.ready=this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of nt.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){ke.changes.removeEventListener("change",this.onModulesChanged),this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of nt.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,s){if(t==="src"&&s&&s!==e&&this.isConnected&&this.loadFromSrc(s),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&s!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&s!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&s!==e){const i=Number(s);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(i)&&i>0?i:Math.min(window.devicePixelRatio||1,2))}(t===Lo||t===No||t===ma)&&s!==e&&this.forwardPlayerAttributes(),t===ma&&this.stageElement.classList.toggle("minified",s!==null)}forwardPlayerAttributes(){for(const t of[Lo,No,ma]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.showCompassFor({forced:t})}compassHovered=!1;compassForced=!1;showCompassFor(t){this.compassHovered=t.hovered??this.compassHovered,this.compassForced=t.forced??this.compassForced,this.sceneRenderer.setCompassForced(this.compassForced||this.compassHovered)}lookToward(t){const e=pt(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:s,z:i}=ot(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(s,i)<1)return this.setLookOffset(0,0);const n=(Math.atan2(s,-i)*180/Math.PI+360)%360;this.setLookOffset(((n-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setOutsideHeard(ns.transmission(this.ufoElement.sighting.vehicle)),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed);const e=this.ufoElement.sighting.around;this.weatherAudio.setAround(jt.aroundBedRms(e),jt.aroundBedShape(e)??[])}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,s,i=0){return this.sceneRenderer.decorGroundPointAt(t,e,s,i)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,s){return this.sceneRenderer.decorGrabHeightAt(t,e,s)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=Uf.recording(t);this.holdForNewScene(e);const s=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(s.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=s}loader;poster;showPoster(t,e,s=!0){this.poster.show(t,e,s)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,(t||e)&&(this.hoverTooltip.hidden=!0),this.ufoElement.namesHeld=t||e,this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){const e=ku.recording(t);this.ufoElement.playerTitle=void 0,this.ufoElement.sightingData=e,this.requireModules(e.modules),this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.showInterpretation(this.inTheRound?this.ufoElement.sighting.interpretation:void 0),this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}onModulesChanged=t=>{t.detail==="skyEvents"&&this.sceneRenderer.setSkyEvents(this.skyEventsShown,!0,this.skyEventsStartDate)};requireModules(t){if(!t?.length)return;const e=this.documentUrl,s=H(async()=>{const{ModuleSession:i}=await import("./ModuleSession-Dac4fD0X.js");return{ModuleSession:i}},__vite__mapDeps([52,1,9,6]),import.meta.url).then(({ModuleSession:i})=>i.shared.require(t,e)).then(()=>this.sceneRenderer.setDecorModelProvider(new gp));this.sceneRenderer.holdUntil(s)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,s=Math.round(t.width/e);return t.height!==s&&(t.height=s),this.seekPreview??=new uh(this,()=>document.createElement(gh))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}filmName;filmFileName(){return`${(this.filmName??"").replace(/[\\/:*?"<>|\u0000-\u001f]+/g," ").replace(/\s+/g," ").trim()||"observation"}.mp4`}filming=!1;async film(t,e,s){const[{VideoExport:i},{FilmChrome:n}]=await Promise.all([H(()=>import("./VideoExport-B8ZhHNnd.js").then(o=>o.a),[],import.meta.url),H(()=>import("./FilmChrome-DYiyzoB_.js"),[],import.meta.url)]),a=await n.loadLogo();return this.filmScene(t,o=>i.film({...o,frameAt:(r,c,h)=>o.frameAt(r,c,h)?(n.paint(h,this.ufoElement.filmChrome(t),a),!0):!1},e,s))}async generativeKit(t,e,s){const[{GenerativeKit:i},{generativeKitMessages:n},{toSightingJson:a}]=await Promise.all([H(()=>import("./GenerativeKit-BmhvjjzB.js"),__vite__mapDeps([53,54,55]),import.meta.url),H(()=>import("./GenerativeKitMessages-BwG7cWZX.js"),__vite__mapDeps([56,1]),import.meta.url),H(()=>Promise.resolve().then(()=>L1),void 0,import.meta.url)]),o=pr(pn.preferencesFor(this),gr),[r]=await Promise.all([n.load(o),this.sceneRenderer.loadControlPasses()]),c=this.sceneRenderer.areReferencesShown;this.sceneRenderer.setReferencesShown(!1);try{return await this.filmScene({...t,caption:!1,time:!1,map:!1},h=>i.make({film:h,drawControlPasses:()=>this.sceneRenderer.drawControlPasses(),recording:a(this.ufoElement.sighting),title:this.filmName??"",source:h.about?.source,language:o},r,e,s))}finally{this.sceneRenderer.setReferencesShown(c)}}async filmScene(t,e){if(this.filming)throw new Error("Already filming");const s=this.ufoElement,i=s.currentTime;s.pause();const n={width:this.sceneCanvas.clientWidth,height:this.sceneCanvas.clientHeight},a=t.height&&n.height>0?t.height/n.height:this.sceneRenderer.maxPixelRatio;this.filming=!0,this.sceneRenderer.holdPixelRatio(a),s.filmMap(t.map),this.syncAnimationsToPlayback();try{const o=t.height??this.sceneCanvas.height,r=t.height&&n.height>0?Math.round(t.height*n.width/n.height):this.sceneCanvas.width,c=this.filmRate(),h=Math.min(s.seekableDuration,t.toS!==void 0?t.toS*1e3*c:s.seekableDuration),l=Math.min(h,Math.max(0,(t.fromS??0)*1e3*c));return await e({fromMs:l,toMs:h,rate:c,width:r,height:o,frameAt:(d,f,m)=>this.filmFrameAt(d,f,m),hearInto:d=>this.hearInto(d),about:{title:this.filmName,description:s.filmDescription,source:this.documentUrl?new URL(this.documentUrl,location.href).href:void 0}})}finally{this.filming=!1,this.sceneRenderer.holdPixelRatio(void 0),s.filmMap(void 0),s.currentTime=i,this.syncAnimationsToPlayback()}}filmRate(){const t=this.ufoElement.playbackRate;return t>0?t:1}filmPictureSize(){const t=this.sceneRenderer.maxPixelRatio;return{width:Math.round(this.sceneCanvas.clientWidth*t),height:Math.round(this.sceneCanvas.clientHeight*t)}}filmSound;liveSound;filmThunderAtMs;hearInto(t){if(t){this.liveSound??={weather:this.weatherAudio,vehicle:this.vehicleAudio,aircraft:this.aircraftAudio},this.filmSound=t,this.weatherAudio=new Aa(t),this.vehicleAudio=new Zd(t);const e=nt.trafficRuntime;this.aircraftAudio=this.liveSound.aircraft&&e?this.newAircraftAudio(e):void 0}else this.liveSound&&(this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.weatherAudio=this.liveSound.weather,this.vehicleAudio=this.liveSound.vehicle,this.aircraftAudio=this.liveSound.aircraft,this.liveSound=void 0,this.filmSound=void 0,this.filmThunderAtMs=void 0);this.ufoElement.hearInto(t),this.syncAnimationsToPlayback()}filmFrameAt(t,e,s){this.ufoElement.currentTime!==t&&(this.ufoElement.currentTime=t),this.filmThunderAtMs!==void 0&&t>=this.filmThunderAtMs&&(this.filmThunderAtMs=void 0,this.weatherAudio.playThunder()),this.sceneRenderer.render();const i=this.sceneRenderer.framesDrawn;return this.sceneRenderer.frame(e),this.sceneRenderer.framesDrawn===i?!1:(s.drawImage(this.sceneCanvas,0,0,s.canvas.width,s.canvas.height),!0)}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}horizonPointAt(t){const e=t*Math.PI/180,s=this.sceneRenderer.screenPointOf(new D(Math.sin(e),0,-Math.cos(e)));return s&&{x:(s.ndcX+1)/2,y:(1-s.ndcY)/2}}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const s=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:s?s.shown?s.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.snapshotKey=void 0,this.applySnapshots(this.ufoElement.sighting.snapshots)}liveTerrainProviders;snapshotKey="none";applySnapshots(t){const e=Oc.isEmpty(t)?"none":`${JSON.stringify(t)}
|
|
4996
5000
|
${this.documentUrl??""}
|
|
4997
5001
|
${$t.generation}`;if(e===this.snapshotKey)return;const s=this.snapshotKey!==void 0&&this.traffic?.set!==void 0;this.snapshotKey=e,this.sceneRenderer.setTerrainProviders(fh.providers(t,this.documentUrl,this.liveTerrainProviders??Gm())),this.ufoElement.observerMapSnapshot=this.snapshotMapOf(t),s&&(this.traffic=void 0,this.decorMemo=void 0)}snapshotMapOf(t){const e=Oc.held(t,"map");if(!e)return;const s=`${$t.address(e.src,this.documentUrl)}
|
|
4998
5002
|
${$t.generation}`;return this.snapshotMap?.key!==s&&(this.snapshotMap={key:s,imagery:fh.map(e,this.documentUrl)}),this.snapshotMap.imagery}snapshotMap;setDecorModelProvider(t){this.sceneRenderer.setDecorModelProvider(t)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(e=>[`${e.title}|${e.author??""}|${e.license}|${e.sourceUrl??""}`,e])).values()]}framedInstrumentId;applyFrameFormat(t=this.ufoElement.currentTime){const e=this.ufoElement.sighting.instrumentAt(t);this.framedInstrumentId=e.id;const s=he.CANVAS_HEIGHT_PX,i=je.frameWidthPx(e,s);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${s}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),s=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=s,this.sceneRenderer.resize(e,s)}async loadStars(){const t=[{magnitudeLimit:Il,url:this.getAttribute("star-catalog-src")??Lw},{magnitudeLimit:Rl,url:this.getAttribute("deep-star-catalog-src")??Nw}],e=this.instrumentReach(),s=++this.starCatalogRequest;this.starCatalogDepth=e>Il?Rl:Il;const i=await Pi.upTo(t,e);s===this.starCatalogRequest&&(this.starCatalog=i,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Rl||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=[0,...t.observerTrack.allKeyframes.filter(i=>i.pose.instrument!==void 0).map(i=>i.t)],s=Math.max(...e.map(i=>ss.gainFor(t.instrumentAt(i),{fNumber:pt(t,i)?.fNumber,fieldOfViewDeg:Re.fovOf(t,i),exposureSeconds:t.exposureAt(i)})));return Er(Cw,s)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=ls.windowEndingAt(t,this.exposureSeconds()),s=e.seconds,i=this.degreesPerPixelAt(t),n=Ra.instants(s,i),a=Math.max(n,this.ufoElement.exposureTimes(t).length,ls.instants(this.decorWithTraffic(this.ufoElement.sighting),pt(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,s,i),ls.bodyInstants(this.interpretationShown?.bodies??[],pt(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,t,i));if(a<=1){this.sceneRenderer.setExposure(1);return}const o=this.ufoElement.sighting.observerTrack.turnIsViewOnly(e.fromMs,t)?t:void 0;this.sceneRenderer.setExposure(a,r=>this.applySceneAt(e.fromMs+e.ms*r/(a-1),{viewAt:o,sky:Math.floor(r*n/a)!==Math.floor((r-1)*n/a),stepMs:e.ms/a}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:Re.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:Mo.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const s=this.ufoElement.sighting;e||this.sceneRenderer.setRecordingTime(t),this.setWeather(Ko(s,t));const i=s.instrumentAt(t);this.sceneRenderer.setInstrument(i,pt(s,t)?.fNumber),s.changesInstrument&&i.id!==this.framedInstrumentId&&this.applyFrameFormat(t),this.sceneRenderer.setLightPollution(s.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(s,t)),e||this.pushAircraftSound(s,t),this.updateMeteorShower(s,t),this.updateLightning(s,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(s),t)),this.recomputeAmongNewDecor(),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??nt.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??nt.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=pt(s,t);this.sceneRenderer.setReferences(s.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0),e||this.sceneRenderer.setReferencesTime({t,playing:this.ufoElement.playbackState==="playing",timeScale:this.ufoElement.playbackRate});const a=pt(s,0),o=Qa(s,0),r=dn(s.event.time??{},n?.lng??Rc.lng,s.event.utcOffsetHours),c=s.weatherSource!==void 0&&r?p2(r):void 0,h=Object.fromEntries(Kf(Qa(s,t)).map(P=>[P.id,e0(t,s.weatherTrack,o,a,n,P.id,P.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(e0(t,s.weatherTrack,o,a,n,void 0,c),h);const l=e?.viewAt!==void 0?pt(s,e.viewAt):void 0,d=n&&l?{...n,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg,rollDeg:l.rollDeg,fovDeg:l.fovDeg}:n;this.sceneRenderer.setObserverPose(d?{...d,pitchDeg:d.pitchDeg+this.roadGradeAt(s,e?.viewAt??t)}:Rc),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(ss.gainFor(i,{fNumber:n?.fNumber,fieldOfViewDeg:Re.fovOf(s,t),exposureSeconds:s.exposureAt(t)}),i.detailUm!==void 0,vi.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(Gr.mediumOf(i.medium,Gr.byId(s.filmAt(t))),s.exposureAt(t),n?.fNumber??i.fNumber,s.isoAt(t),s.meteringAt(t)),this.sceneRenderer.setLensGhosts(wt.optics(i,n?.fNumber??i.fNumber,s.lensAt(t),this.glassWettingOf(s).stateAt(t/1e3),t)),this.sceneRenderer.setPerception(da.perceptionOf(s.account?.observerPerception)),this.sceneRenderer.setGait(Bt.bodyAt(s,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(pt(s,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applySnapshots(s.snapshots),this.sceneRenderer.setObserverRoute(this.routeOf(s.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(s,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(s.roads),this.sceneRenderer.setTraces(s.traces,this.traceLabels(s.traces)),this.pushPhenomenaAt(t);const f=n?.lat??Rc.lat,m=n?.lng??Rc.lng,p=dn(s.event.time??{},m,s.event.utcOffsetHours),g={lat:f,lng:m,elevationM:this.altitudeOf(n)};this.pushSatellitesAt(p,t,g),this.ensureFireballs(p),this.ensureAurora(p,f,m);const M=this.skyEventsOf(s),v=M?.reentries??[];this.hearDetonations(v,t,{lat:f,lng:m,heightM:g.elevationM},e!==void 0);const y=v.filter(P=>X.mayDazzle(P));if(this.sceneRenderer.setRetinaHistory(y.length===0?void 0:P=>{const k=pt(s,P),_={lat:k?.lat??f,lng:k?.lng??m,heightM:k?this.altitudeOf(k):g.elevationM};return{views:X.viewsAt(y,P,_),pose:k}},s),this.skyEventsStartDate=p,this.sceneRenderer.setSkyEvents(M,!1,p),M&&this.loadSkyEventTexts(fu.map(P=>vn.of(P)).filter(P=>vn.eventsOf(M,P).length>0&&!this.skyEventTexts.has(P))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!p),!p){this.sceneRenderer.setAstronomy(_w);return}const w=new Date(p.getTime()+t),b=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/Ra.DEG_PER_SECOND*1e3)),E=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),A=`${Math.floor(w.getTime()/b)}|${Math.round(f/E)}|${Math.round(m/E)}|${Math.round(g.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(A===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=A;const S=Bn("Sun",w,g),x=Bn("Moon",w,g);let T=be.separationOf(S,x)<1?be.viewAt(w,g):void 0;if(T){const P=be.offsetOf(S,x,T.separationDeg);if(T.obscuration>nt.LIMB_FROM_OBSCURATION){const k=this.limbFor(w,g);k&&(T={...T,obscuration:1-ii.uncoveredFraction(k,T.sunRadiusDeg,P),limb:k})}T={...T,horizonShare:be.horizonShare(T,P,S.altitudeDeg,S.azimuthDeg,Bi.distanceKm(w,g))}}const I={...S,magnitude:_h("Sun",w)-2.5*Math.log10(be.beamFraction(T))};this.lastSun={altitudeDeg:I.altitudeDeg,azimuthDeg:I.azimuthDeg};const R={...x,phase:D1(w),magnitude:_h("Moon",w),radiusDeg:Bi.apparentRadiusDeg(w,g)},O=T1.map(P=>({body:P,position:Bn(P,w,g),magnitude:_h(P,w)}));this.sceneRenderer.setAstronomy({sun:I,moon:R,planets:O,comet:this.cometAt(w,g),novae:Lf.appearancesAt(w,g).map(({outburst:P,position:k,magnitude:_})=>({id:P.id,position:k,magnitude:_})),stars:this.starCatalog?{catalog:this.starCatalog,date:w,observer:g}:void 0,frame:{date:w,observer:g},localHour:((w.getUTCHours()+w.getUTCMinutes()/60+(s.event.utcOffsetHours??Math.round(m/15)))%24+24)%24,eclipse:T}),this.ufoElement.setSunAltitude(I.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,Pr.load(kw).then(n=>{this.limbRelief=n,this.lastSkyKey="",n&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const s=this.limbCache;if(s&&Math.abs(t.getTime()-s.atMs)<5e3&&s.lat===e.lat&&s.lng===e.lng&&s.elevationM===e.elevationM)return s.profile;const i=ii.profile(t,e,this.limbRelief);return this.limbCache={profile:i,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},i}pushSatellitesAt(t,e,s){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const i=new Date(t.getTime()+e),n=[];for(const a of this.satellites.passes.positionsAt(i,s,-1))a.magnitude!==void 0&&n.push({norad:a.object.norad,name:a.object.name,position:{altitudeDeg:a.altitudeDeg,azimuthDeg:a.azimuthDeg},magnitude:a.magnitude,heightKm:a.heightKm});this.sceneRenderer.setSatellites(n)}ensureFireballs(t){const e=this.ufoElement.sighting,s=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),i=t?.getTime(),n=e.skySources!==!1,a=i===void 0||!n?"":`${i}+${s}`;if(this.fireballs?.key===a)return;if(!n){this.fireballs={key:a,status:"outside",reentries:[]};return}if(i===void 0||!Vi.mayCover(i+s)){this.fireballs={key:a,status:"outside",reentries:[]};return}const o={key:a,status:"loading",reentries:[]};this.fireballs=o,nt.fireballArchive.between(i,i+s).then(r=>{o.status=r?"ready":"unavailable",o.records=r??[],o.reentries=o.records.map(c=>Vi.asReentry(c,i)),!(this.fireballs!==o||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(Ip)),o.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}ensureAurora(t,e,s){const i=this.ufoElement.sighting,n=Math.max((i.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),a=t?.getTime(),o=a===void 0||i.skySources===!1?"":`${a}+${n}@${e.toFixed(1)},${s.toFixed(1)}`;if(this.archivedAurora?.key===o)return;const r={key:o};if(this.archivedAurora=r,a===void 0||o===""||!Mn.mayCover(a+n)||Math.abs(Gn.latitudeOf(e,s,t))<20)return;const c=h=>Bn("Sun",new Date(h),{lat:e,lng:s,elevationM:0}).altitudeDeg<-4;!c(a)&&!c(a+n)||nt.geomagneticArchive.between(a,a+n).then(h=>{this.archivedAurora!==r||!this.isConnected||!h||(r.aurora=Mn.asAurora(h,a),this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const s=this.decorMemo;if(s&&s.base===t.decor&&s.traffic===e.objects)return s.merged;const i=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:i},i}seatedDecor(t,e){if(!t.some(a=>a.observerKeyframes?.length))return t;const s=t.map(a=>{if(!a.observerKeyframes?.length)return"";const o=Md(a,e);return`${o.side??"-"}/${o.facing??"-"}`}).join("|"),i=this.seatedMemo;if(i&&i.base===t&&i.seats===s)return i.seated;const n=t.map(a=>{if(!a.observerKeyframes?.length)return a;const o=Md(a,e);return{...a,observerSide:o.side,observerFacing:o.facing}});return this.seatedMemo={base:t,seats:s,seated:n},n}ensureTraffic(t){const e=pt(t,0),s=e?.lng===void 0?void 0:dn(t.event.time??{},e.lng,t.event.utcOffsetHours),i=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=s?.getTime(),a=n===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${n}+${i}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}|${Math.round(this.sceneRenderer.groundAltitudeM)}`;if(t.skySources===!1){this.traffic?.status!=="byHand"&&(this.traffic={key:"byHand",status:"byHand"},this.upperAirHeardLive=void 0);return}if(this.traffic?.key===a)return this.traffic.set;if(this.upperAirHeardLive=void 0,a===""||n===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:a,status:"outside"};return}let o=nt.aircraftProviders.get(this.aircraftSource.id);if(o||nt.aircraftProviders.set(this.aircraftSource.id,o=this.aircraftSource.create()),o.mayCover&&!o.mayCover(n+i)){this.traffic={key:a,status:"outside"};return}const r={key:a,status:"loading",startMs:n,observer:{lat:e.lat,lng:e.lng}};this.traffic=r;const c={lat:e.lat,lng:e.lng,heightM:this.sceneRenderer.groundAltitudeM},h=$e.MAX_GAP_S*1e3,l=nt.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:this.altitudeOf(e)},f=(m,p)=>m.TrafficDecor.from(r.tracks??[],c,n,m.TrafficDecor.MAX_OBJECTS,{models:p,sunElevationAt:g=>this.sunElevationAt(g,d)});o.between(c,n-l,n+i+h).then(async m=>{if(this.traffic!==r)return;if(m.status!=="found"){r.status=m.status==="outside"?"outside":"unavailable",m.status==="failed"&&(r.problem=m.problem,r.creditsSpent=m.creditsSpent),this.announceTraffic();return}let p;try{p=await nt.loadTrafficRuntime()}catch{this.traffic===r&&(r.status="unavailable",this.announceTraffic());return}this.traffic===r&&(r.status="ready",r.tracks=m.tracks,r.partial=m.partial,r.creditsSpent=m.creditsSpent,r.set=f(p),this.startAircraftSound(r,p),this.announceTraffic(),this.describeTraffic(o,r,p,f),r.set.shown>0&&(this.readUpperAir(r,p,n-l,n+i+h),this.readTrailTraffic(o,r,p,c,n-nt.TRAIL_LOOKBACK_MS,n+i+h)))})}trafficSunlight(t){const e=new Map,s=this.traffic,i=s?.set,n=this.lastSun;if(!i||!n||s.startMs===void 0||!s.observer)return e;for(const[a,o]of i.presence){if(t<o.fromMs||t>o.untilMs)continue;const r=i.flights.get(a),c=r?$e.positionAt(r,s.startMs+t):void 0;c&&e.set(a,{heightM:c.geo.heightM,sunElevationDeg:ms.sunElevationDeg(n,s.observer,c.geo)})}return e}trafficTooltipAt(t,e){const s=this.sceneRenderer.pickTrafficAt(t,e),i=s?this.trafficInfoAt(s):void 0;if(!i)return;const n=this.naming;return nt.trafficRuntime?.TrafficTooltip.text(i,n.names.trafficTooltip,o=>n.towards(o))}trafficInfoAt(t){const e=this.traffic,s=e?.set?.flights.get(t);if(!e||!s||e.startMs===void 0||!e.observer)return;const i=nt.trafficRuntime;if(!i)return;const n=e.descriptions?.get(Nt.keyOf(s)),a=pt(this.ufoElement.sighting,this.lastTimeMs),o={lat:e.observer.lat,lng:e.observer.lng,heightM:this.altitudeOf(a)},r=Ko(this.ufoElement.sighting,this.lastTimeMs),c=this.ufoElement.sighting.around,h=i.AmbientNoise.dbA(r,c),l=i.TrafficInfos.at(s,n,o,e.startMs+this.lastTimeMs,{ambientDbA:h,ambientShapeDb:i.AmbientNoise.shapeDb(r,c)}),d=l&&this.contrailAt(t,this.lastTimeMs);return l&&d?{...l,contrail:d}:l}contrailAt(t,e){const s=this.traffic?.contrails?.find(n=>n.id===t);if(!s)return;let i;for(const n of s.points){if(n.tMs>e)break;i=n}return i?.forms?{persistent:i.persistent,iceRelativeHumidity:i.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){if(!t.set||!t.observer)return;const s={windSpeed:0,precipitationType:"none",precipitationIntensity:0};t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,Nt.keyOf,{...t.observer,heightM:this.sceneRenderer.groundAltitudeM},{ambientDbA:e.AmbientNoise.dbA(s,this.ufoElement.sighting.around),ambientShapeDb:e.AmbientNoise.shapeDb(s,this.ufoElement.sighting.around)}),this.ufoElement.refreshSoundControls()}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound(),this.startRideSound(t);const s=this.aircraftAudio;if(!s)return;const i=nt.trafficRuntime;if(!i){s.setVoices([]);return}const n=pt(t,e),a=Ko(t,e),o={ambientDbA:i.AmbientNoise.dbA(a,t.around),referenceAmplitude:i.AmbientNoise.referenceAmplitude(a,t.around),ambientShapeDb:i.AmbientNoise.shapeDb(a,t.around),expandUnderKnee:!i.AmbientNoise.bedPlays(a,t.around)},r=t.event.place?.[0],c={lat:n?.lat??r?.lat,lng:n?.lng??r?.lng},h=c.lat!==void 0&&c.lng!==void 0?{lat:c.lat,lng:c.lng,heightM:n?.elevationM??0}:void 0,l=M=>this.decorModelSounds.get(M.model?.id??""),d=!t.vehicle&&h?i.DecorAircraftHearing.ridden(t,e,h,l):void 0,f=t.vehicle??(d?{kind:d.kind}:void 0),m=f?i.CabinHearing.voice(f,o):void 0,p={...o,ambientDbA:Math.max(o.ambientDbA,m?.levelDbA??0),...f?{throughDb:ns.insulationDb(f)}:{}},g=this.trafficVoices(e,n,p,i);h&&(this.decorAircraftHearing??=new i.DecorAircraftHearing,g.push(...this.decorAircraftHearing.voices(t,e,h,p,l)),g.push(...this.bodyVoices(t,e,p,i)),m&&g.push(m),g.sort((M,v)=>v.levelDbA-M.levelDbA),g.length=Math.min(g.length,4)),s.setVoices(g,n?.headingDeg??0)}startRideSound(t){this.aircraftAudio||ns.aircraftOf(t.vehicle)===void 0||(nt.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(nt.trafficRuntime):nt.loadTrafficRuntime().catch(()=>{}))}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(nt.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(nt.trafficRuntime):nt.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,s,i){const n=this.interpretationShown,a=t.event.place?.[0];if(!n||!a||!n.bodies.some(f=>f.sound))return[];const o=this.sceneRenderer.bodyGround,r=f=>Y.eyeOf(t,f,o),c=r(e);if(!c)return[];const h=new Map,l=(f,m)=>{let p=h.get(f.id);return p||h.set(f.id,p=new Y(f,o,r)),p.at(m)};this.bodyHearing??=new i.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(n.bodies,l,c,a,e,d,s)}trafficVoices(t,e,s,i){const n=this.traffic,a=n?.set;if(!n||!a||!n.audible||n.startMs===void 0||!n.observer)return[];const o={lat:n.observer.lat,lng:n.observer.lng,heightM:this.altitudeOf(e)};return i.TrafficSound.voices(n.audible,a.flights,n.descriptions??new Map,Nt.keyOf,o,n.startMs+t,s)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length===0)return;for(const i of e){const n=i.model?.id;i.aircraftSound||!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.decorModelsAsked.add(n),this.sceneRenderer.entryOfDecorModel(n).then(a=>{this.decorModelSounds.set(n,a?.parameters?.sound),this.decorModelsAsked.delete(n),this.ufoElement.refreshSoundControls(),this.startDecorAircraftSound(t)}))}if(e.some(i=>{if(i.aircraftSound)return i.aircraftSound!=="silent";const n=i.model?.id;return!n||i.model?.url!==void 0?!0:!this.decorModelsAsked.has(n)&&this.decorModelSounds.get(n)!=="silent"})){if(this.aircraftAudio||nt.trafficRuntime){!this.aircraftAudio&&nt.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(nt.trafficRuntime));return}nt.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio(this.filmSound);return this.filmSound||e.setLevel(this.ufoElement.level),(this.interacted||this.filmSound)&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"&&!this.filmSound),e}get aircraftFlights(){return[...this.declaredFlights,...this.recordedFlights]}get declaredFlights(){return this.ufoElement.sighting.decor.filter(t=>t.kind==="aircraft"&&gd.flies(t)).map(t=>{const e=this.sceneRenderer.decorSkyPoint(t.id);return{key:Nt.declaredKeyOf(t.id),type:this.said.read(t.title)||this.naming.decorKind(t.kind),sky:e?.sky,altitudeFt:e?e.altitudeM/.3048:void 0,firstMs:0,drawn:e!==void 0,declared:!0}})}get recordedFlights(){const t=this.traffic;if(!t?.tracks||t.startMs===void 0||!t.observer)return[];const e=t.startMs,s=this.observerAt(this.lastTimeMs,t.observer),i=new Set([...t.set?.flights.values()??[]].map(o=>Nt.keyOf(o))),n=t.nearestPassKm??=new Map(t.tracks.map(o=>[Nt.keyOf(o),Math.min(...o.points.map(r=>$e.groundDistanceKm(t.observer,r)))])),a=this.ufoElement.seekableDuration;return[...t.tracks].sort((o,r)=>n.get(Nt.keyOf(o))-n.get(Nt.keyOf(r))).map(o=>{const r=Nt.keyOf(o),c=t.descriptions?.get(r),h=t.models?.get(r),l=$e.seenFrom(o,s,e+this.lastTimeMs),d=o.points.find(f=>f.t>=e)?.t;return{key:r,type:h?.basis==="type"?h.name:c?.type,registration:c?.registration,sky:l?.sky,altitudeFt:l?.altitudeFt,firstMs:d!==void 0&&d-e<=a?d-e:void 0,drawn:i.has(r)}})}lookAtFlight(t,e=this.lastTimeMs){const s=this.traffic,i=pt(this.ufoElement.sighting,e),n=Nt.declaredIdOf(t);if(n!==void 0){const r=this.sceneRenderer.decorSkyPoint(n);return!r||i?.headingDeg===void 0?!1:(this.setLookOffset(((r.sky.azimuthDeg-i.headingDeg)%360+540)%360-180,r.sky.altitudeDeg-(i.pitchDeg??0)),!0)}const a=s?.tracks?.find(r=>Nt.keyOf(r)===t);if(!s?.observer||s.startMs===void 0||!a||i?.headingDeg===void 0)return!1;const o=$e.seenFrom(a,this.observerAt(e,s.observer),s.startMs+e);return o?(this.setLookOffset(((o.sky.azimuthDeg-i.headingDeg)%360+540)%360-180,o.sky.altitudeDeg-(i.pitchDeg??0)),!0):!1}markFlight(t){this.markedFlight=t,this.placeFlightMark()}placeFlightMark(){const t=this.markedFlight,e=t===void 0?void 0:this.sceneRenderer.flightScreenPoint(t);if(this.flightMark.toggleAttribute("hidden",!e),!e)return;const s=this.sceneCanvas.getBoundingClientRect(),i=this.stageElement.getBoundingClientRect(),n=s.left-i.left+(e.ndcX+1)/2*s.width,a=s.top-i.top+(1-e.ndcY)/2*s.height;for(const o of Array.from(this.flightMark.children))o.setAttribute("cx",String(n)),o.setAttribute("cy",String(a))}altitudeOf(t){return this.sceneRenderer.groundAltitudeM+(t?.elevationM??0)}observerAt(t,e){const s=pt(this.ufoElement.sighting,t);return{lat:s?.lat??e.lat,lng:s?.lng??e.lng,heightM:this.altitudeOf(s)}}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(Op)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,s,i){if(!t.describe||!e.set||!e.tracks)return;const n=new Set([...e.set.flights.values()].map(c=>Nt.keyOf(c))),a=e.tracks.filter(c=>n.has(Nt.keyOf(c))&&c.points.length>0),o=new Map,r=new Map;await Promise.all(a.map(async c=>{const h=new Date(c.points[0].t).toISOString().slice(0,10),l=await t.describe(c,h).catch(()=>{});l&&(r.set(Nt.keyOf(c),l),o.set(Nt.keyOf(c),s.AircraftModels.of(l)))})),!(this.traffic!==e||o.size===0)&&(e.descriptions=r,e.models=o,e.set=i(s,o),this.planContrails(e,s),this.sortOutAudible(e,s),this.announceTraffic())}async readTrailTraffic(t,e,s,i,n,a){if(e.startMs===void 0)return;const o=await t.between(i,n,a).catch(()=>{});if(this.traffic!==e||o?.status!=="found")return;const r=o.tracks.filter(l=>l.points.some(d=>d.altitudeFt>=s.AircraftContrails.MIN_ALTITUDE_FT)),c=new Map(e.models??[]);if(t.describe&&await Promise.all(r.filter(l=>l.points.length>0&&!c.has(Nt.keyOf(l))).map(async l=>{const d=await t.describe(l,new Date(l.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&c.set(Nt.keyOf(l),s.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const h=s.TrafficDecor.from(r,i,e.startMs,nt.TRAIL_MAX_AIRCRAFT,{models:c});e.trailSet=nt.alignTrailIds(h,e.set),e.models=new Map([...c,...e.models??[]]),this.planContrails(e,s),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const s=new Map;for(const[o,r]of e.flights){const c=e.presence.get(o);if(c)for(const[h,l]of t.flights){const d=t.presence.get(h);!d||Nt.keyOf(l)!==Nt.keyOf(r)||d.fromMs<=c.untilMs&&c.fromMs<=d.untilMs&&s.set(h,o)}}const i=o=>s.get(o)??`${o}-trail`,n=new Set(s.values()),a=e.objects.filter(o=>!n.has(o.id));return{...t,objects:[...t.objects.map(o=>({...o,id:i(o.id)})),...a],presence:new Map([...[...t.presence].map(([o,r])=>[i(o),r]),...a.map(o=>[o.id,e.presence.get(o.id)])]),flights:new Map([...[...t.flights].map(([o,r])=>[i(o),r]),...a.map(o=>[o.id,e.flights.get(o.id)])])}}async readUpperAir(t,e,s,i){if(!t.observer)return;const n=Oc.held(this.ufoElement.sighting.snapshots,"upperAir");let a;if(n){const c=$t.address(n.src,this.documentUrl);a=nt.upperAirProviders.get(c),a||nt.upperAirProviders.set(c,a=new To($t.json(c)))}else{const c=this.upperAirSource??e.UPPER_AIR_SOURCES[0];a=nt.upperAirProviders.get(c.id),a||nt.upperAirProviders.set(c.id,a=c.create())}const o={lat:t.observer.lat,lng:t.observer.lng},r=await a.between(o,s,i);this.traffic!==t||r.status!=="found"||(n||(this.upperAirHeardLive={...o,startMs:s,endMs:i,answer:r}),t.air=r.samples,t.airSource=r.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const s=t.trailSet??t.set;!s||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(s,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,s=this.traffic,i=s?.trailSet??s?.set,n=this.lastSun;if(!s||!i||!n||!s.contrails?.length||s.startMs===void 0||!s.observer)return e;for(const a of s.contrails){const o=i.presence.get(a.id),r=i.flights.get(a.id);if(!o||!r)continue;const c=$e.positionAt(r,s.startMs+Math.min(o.untilMs,Math.max(o.fromMs,t)));c&&e.set(a.id,{heightM:c.geo.heightM,sunElevationDeg:ms.sunElevationDeg(n,s.observer,c.geo)})}return e}sunElevationAt(t,e){const s=Bn("Sun",new Date(t.t),e);return ms.sunElevationDeg(s,e,t)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(t){t.id!==this.upperAirSource?.id&&(this.upperAirSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(t,e=!1){!e&&t.id===this.aircraftSource.id||(this.aircraftSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const t=this.traffic?.contrails?.length?this.upperAirSource??nt.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",problem:this.traffic?.problem,partial:this.traffic?.partial,creditsSpent:this.traffic?.creditsSpent,total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get archivedAuroraShown(){return this.archivedAurora?.aurora!==void 0&&!this.ufoElement.sighting.skyEvents?.auroras?.length}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){this.ufoElement.sighting.skySources===!1&&(t=void 0);const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const s=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const i=a=>{s===this.satelliteRequest&&(this.satelliteStatus=a,this.isConnected&&this.dispatchEvent(new CustomEvent(Dp)))},n=nt.tleArchive;(async()=>{if(!await n.covers(t))return i("outside");const[a,o]=await Promise.all([n.at(t),H(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(s===this.satelliteRequest){if(!a)return i("unavailable");this.satellites={snapshot:a,passes:new o.SatellitePasses(a.objects)},i("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>i("unavailable"))}get satelliteState(){const t=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:t?.coverage,credit:t?.credit,creditUrl:t?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const t=this.traffic;if(!(t?.status!=="ready"||!t.tracks||t.startMs===void 0))return{tracks:t.tracks,startMs:t.startMs,describe:e=>t.descriptions?.get(Nt.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,s=this.ufoElement.sighting,i=pt(s,0),n=s.event.place?.[0],a=i?.lat??n?.lat,o=i?.lng??n?.lng;if(!(!e||a===void 0||o===void 0))return e.passes.positionsAt(t,{lat:a,lng:o,elevationM:this.altitudeOf(i)})}satellitePassesDuring(t){const e=this.satellites,s=this.ufoElement.sighting,i=pt(s,0),n=s.event.place?.[0],a=i?.lat??n?.lat,o=i?.lng??n?.lng;if(!e||a===void 0||o===void 0)return[];const r=dn(s.event.time??{},o,s.event.utcOffsetHours);if(!r)return[];const c=Math.min(Math.max(t,0),4*36e5),h={lat:a,lng:o,elevationM:this.altitudeOf(i)},l=JSON.stringify([this.satellitesFor,r.getTime(),a,o,h.elevationM,c]);if(this.satellitePassesMemo?.key===l)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(c/1e3/600)),f=e.passes.passesDuring(r,new Date(r.getTime()+c),h,d);return this.satellitePassesMemo={key:l,passes:f},f}cometAt(t,e){const s=Sw.brightestAt(t,e);if(s)return{id:s.apparition.id,position:s.position,tailEnd:s.tailEnd,magnitude:s.magnitude}}approachOf(t,e){return this.approaches.of.has(e)||this.approaches.of.set(e,Lr.of(t,e)),this.approaches.of.get(e)}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const s=JSON.stringify([e.timeline.allKeyframes.map(p=>[p.t,p.shapes.map(g=>[g.sourceId,g.shape.angular?.widthDeg,g.shape.aim?.azimuthDeg])]),e.observerTrack.allKeyframes,e.event.place?.[0]]);s!==this.approaches.key&&(this.approaches={key:s,of:new Map});const i=e.timeline,n=this.ufoElement.canvasElement,a=this.ufoElement.frameShiftPx,o=this.projectionAt(t),r=new Map,c=new Map,h=new Set;for(const p of i.sourceIds){const g=i.getInterpolatedShapeAt(t,p);if(!g)continue;const M={...g,bounds:{...g.bounds,x:g.bounds.x+a.x,y:g.bounds.y+a.y}};r.set(p,M);const v=g.aim?this.sceneRenderer.screenPointOf(Rs.directionOf(g.aim,this.directionScratch)):{ndcX:(M.bounds.x+M.bounds.width/2)/n.width*2-1,ndcY:-((M.bounds.y+M.bounds.height/2)/n.height*2-1)},y=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,w=y?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,p):{};h.add(p),(y||g.aim)&&h.delete(p);const b=g.angular?.widthDeg??o.pxToDeg(g.bounds.width),E=this.sizeEstimateOf(p);E.add(b,w);const A=this.approachOf(e,p);c.set(p,ws.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:A&&b>0?he.distanceMAt(A.widthM,b):void 0,range:E.distanceRangeAt(b),crossing:w}))}for(const[p,g]of r)for(const[M,v]of r){if(M===p||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const w=c.get(M);w&&c.set(p,{distanceM:w.distanceM*.999,basis:w.basis});break}this.depths=c;const l=i.sourceIds,d=[];for(const[p,g]of r)d.push({sourceId:p,shape:g,distanceM:c.get(p).distanceM,renderOrder:l.indexOf(p),aim:g.aim,hidden:h.has(p)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=pt(e,t),m=(f?.rollDeg??0)+Bt.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:o,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:je.starPointsOf(e.instrumentAt(t),f?.fNumber),rollRad:m*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.showInterpretation(t),this.ufoElement.playerTitle=t?.title,this.ufoElement.refreshSoundControls(),this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(t){this.inTheRound=t}get compareAccount(){return this.comparing}set compareAccount(t){t!==this.comparing&&(this.comparing=t,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(t,e,s){const i=this.sceneRenderer.bodyGround,n=Y.eyeOf(this.ufoElement.sighting,s,i);return n?Y.lineOfSightMeetsGround(n,t,e,i):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const s=this.sceneRenderer.bodyGround,i=this.ufoElement.sighting,n=d=>Y.eyeOf(i,d,s),a=new Y(t,s,n).at(e),o=n(e);if(!a||!o)return;const r=a.eastM-o.eastM,c=a.northM-o.northM,h=a.upM-o.upM,l=Math.hypot(r,c);return{azimuthDeg:(Math.atan2(r,c)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,l)*180/Math.PI,distanceM:Math.hypot(l,h),eastM:a.eastM,northM:a.northM,aboveGroundM:a.upM-a.sizeM.heightM/2-s.heightAt(a.eastM,a.northM),sizeM:a.sizeM,attitude:a.attitude,appearance:a.appearance}}bodyProjectionAt(t,e){const s=this.sceneRenderer.bodyGround,i=this.ufoElement.sighting,n=r=>Y.eyeOf(i,r,s),a=new Y(t,s,n).at(e),o=n(e);return a&&o?Rt.projectionOf(a,o):void 0}directionToDecor(t){return this.sceneRenderer.directionToDecor(t)}directionToBody(t,e){const s=this.sceneRenderer.bodyGround,i=this.ufoElement.sighting,n=m=>Y.eyeOf(i,m,s),a=new Y(t,s,n),o=a.at(e)?e:t.track[0]?.t,r=o===void 0?void 0:a.at(o),c=o===void 0?void 0:n(o);if(!r||!c)return;const h=r.eastM-c.eastM,l=r.northM-c.northM,d=r.upM-c.upM,f=Math.hypot(h,l);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(h,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const s=this.interpretationShown,i=this.ufoElement.sighting;let n=[],a=[];const o=this.sceneRenderer.bodyGround,r=m=>Y.eyeOf(i,m,o);s&&(n=s.bodies.map(m=>new Y(m,o,r).at(t)).filter(m=>m!==void 0));const c=Qa(i,t),h=c.windDirectionDeg*Math.PI/180,l={x:c.windSpeed*Math.sin(h),z:-c.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(n,t/1e3,s?.bodies.map(m=>m.id)??[],s?.smoke??[],l);const d=s&&this.comparing?r(t):void 0;if(d&&(a=new Rt(i.timeline,this.confrontationTolerance,Rt.sizeHows(i.timeline,i.provenance),Os.seeingOf(i)).at(t,n,d,m=>m.outlineNode?this.sceneRenderer.bodyOutline?.(m.id,m.outlineNode):void 0)),this.confrontationReadings=a,!e)return;const f=JSON.stringify(a);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(Pp,{detail:a})))}async pictureAt(t,e=640){const s=document.createElement("canvas");s.width=e,s.height=Math.round(e*(this.sceneCanvas.height||9)/(this.sceneCanvas.width||16));let i=!1;for(const n of[1200,0]){this.showAt(t),i=!1;for(let a=0;a<900&&!i;a++)await new Promise(o=>requestAnimationFrame(()=>o())),i=this.snapshotTo(s);if(!i)return;n&&await new Promise(a=>setTimeout(a,n))}return s.toDataURL("image/jpeg",.85)}setDistanceHypothesis(t,e){e===void 0||!(e>0)?this.distanceHypotheses.delete(t):this.distanceHypotheses.set(t,e),this.updateAstronomy(this.lastTimeMs)}depthOf(t){return this.depths.get(t)}sizeRangeOf(t){return this.sizeEstimateOf(t).sizeRange}distanceRangeAt(t,e){const s=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!s)return{};const i=s.angular?.widthDeg??this.projectionAt(e).pxToDeg(s.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(i)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,s){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),s)return;const i=this.lastLightningT;if(this.lastLightningT=e,i===void 0||e<i||this.ufoElement.playbackState!=="playing")return;const n=this.lightningFlashes.filter(a=>a.t>i&&a.t<=e).pop();n&&Qa(t,n.t).storm&&this.handleLightningFlash(n)}ensureLightningSchedule(t){const e=Qa(t,0).precipitationIntensity,s=`${this.meteorInputsOf(t)}|${e}`;if(s===this.lightningScheduleFor)return;this.lightningScheduleFor=s;const i=t.event.time,n=t.event.place?.[0],a=i?.year!==void 0?dn(i,n?.lng??0,t.event.utcOffsetHours):void 0,o=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,r=Math.round((a?.getTime()??0)/1e3)+Math.round((n?.lat??0)*1e3)+7;this.lightningFlashes=De.schedule({durationMs:o,seed:r,intensity:e}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(t){const e=this.meteorInputsOf(t);e!==this.meteorScheduleFor&&(this.meteorScheduleFor=e,this.scheduleMeteors(t))}meteorInputsOf(t){const e=t.event.place?.[0],s=t.event.time;return JSON.stringify([e?.lat,e?.lng,s?.year,s?.month,s?.day,s?.hour,s?.minute,s?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration,t.skySources])}scheduleMeteors(t){const e=t.event.place?.[0],s=t.event.time,i=e?.lat!==void 0&&e.lng!==void 0&&s?.year!==void 0?dn(s,e.lng,t.event.utcOffsetHours):void 0;if(!i||e?.lat===void 0||e.lng===void 0||t.skySources===!1){this.sceneRenderer.setMeteorShower([],0,0);return}const n={lat:e.lat,lng:e.lng,elevationM:0},a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,o=Math.round(i.getTime()/1e3)+Math.round(e.lat*1e3),r=Me.schedule({ratePerHour:Me.observedRatePerHour(Me.apexPosition(i,n).altitudeDeg),durationMs:a,velocityKmS:Me.TYPICAL_VELOCITY_KM_S,seed:o}),c=Ll.activeAt(i).map(l=>{const d=Ll.radiantPosition(l.shower,i,n);return{entry:l,position:d,rate:Ll.observedRatePerHour(l.zhr,d.altitudeDeg,l.shower.populationIndex)}}).sort((l,d)=>d.rate-l.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(r,0,0);return}const h=ni.schedule({ratePerHour:c.rate,durationMs:a,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...r],c.position.altitudeDeg,c.position.azimuthDeg)}groundHides(t,e){return this.sceneRenderer.groundHidesDirection(t,e)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(t,e=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const s=[...this.sceneRenderer.meteorSchedule].filter(a=>a.t+a.durationMs<=this.ufoElement.seekableDuration).filter(a=>ni.magnitudeOf(a)<=e).filter(a=>{const o=this.sceneRenderer.meteorMidpoint(a);return o!==void 0&&!this.sceneRenderer.groundHidesDirection(o.altitudeDeg,o.azimuthDeg)}).sort((a,o)=>o.brightness-a.brightness);if(s.length===0)return;const i=s[t%s.length],n=this.sceneRenderer.meteorMidpoint(i);if(n)return{t:Math.round(i.t+i.durationMs*.45),...n}}lensOpticsAt(t){const e=this.ufoElement.sighting,s=e.instrumentAt(t),i=s.frame,n=pt(e,t),a=n?.fNumber??s.fNumber;if(!i||a===void 0)return;const o=je.focalLengthMmFor(s,Re.fovOf(e,t));if(o!==void 0)return{focalLengthMm:o,fNumber:a,focusDistance:n?.focusDistanceM??0,frameHeightMm:i.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return Yi.of(e.instrumentAt(t),he.CANVAS_HEIGHT_PX,Re.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new Tw,this.sizeEstimates.set(t,e)),e}}const gh="rr0-scene";function zw(){Wm(),customElements.get(gh)||customElements.define(gh,nt)}const s5=Object.freeze(Object.defineProperty({__proto__:null,AIRCRAFT_CHANGE_EVENT:Op,CONFRONTATION_EVENT:Pp,FIREBALLS_CHANGE_EVENT:Ip,REFERENCES_CHANGE_EVENT:Rp,SATELLITES_CHANGE_EVENT:Dp,SCENE_ELEMENT_NAME:gh,SceneElement:nt,registerScene:zw},Symbol.toStringTag,{value:"Module"}));class Wi{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(t,e,s){const i=new URL(`${t}.mjs`,e);return i.href.startsWith(`${Wi.CDN}/`)?`${s}/lib/${t}.mjs`:(i.pathname=i.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),i.href)}static VERSION_PARAMETER="v";static pinnable(t){return t in Wi.DIRECTORIES}static pinnedLink(t,e){const s=new URL(t);return s.searchParams.set(Wi.VERSION_PARAMETER,e),s.href}static pinned(t,e){return`${Wi.CDN}/${Wi.PACKAGE}@${e}/${Wi.DIRECTORIES[t]}/${t}.mjs`}}class Mh{static PRODUCTION="https://ufoathome.org";static home(){try{const t=new URL(import.meta.url),e=new URL(location.href);return(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname.endsWith(".localhost"))&&t.origin===e.origin?e.origin:Mh.PRODUCTION}catch{return Mh.PRODUCTION}}}const Fw=`
|
|
@@ -5221,5 +5225,5 @@ ${$t.generation}`;return this.snapshotMap?.key!==s&&(this.snapshotMap={key:s,ima
|
|
|
5221
5225
|
<button id="copy" class="share-copy" type="button"></button>
|
|
5222
5226
|
</div>
|
|
5223
5227
|
</dialog>
|
|
5224
|
-
`;class Hc extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Hc.TAG)||customElements.define(Hc.TAG,Hc)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=Fw;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.pin=t("pin"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,s=await Cp.load(t);if(e===this.languageToken)return this.messages=s,this.applyMessages(),s}set note(t){this.noteElement.textContent=t??"",this.noteElement.hidden=t===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.pin.checked;this.linkField.value=e?Wi.pinnedLink(t.link(),"0.204.
|
|
5225
|
-
${t.element()}`;this.embedMarkup.value=i,this.codeEditor&&(this.codeEditor.text=i)}applyMessages(){const t=this.messages;if(!t)return;const e=(s,i)=>{this.shadow.getElementById(s).textContent=i};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("pin-label",t.pin.replace("{version}","0.204.
|
|
5228
|
+
`;class Hc extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Hc.TAG)||customElements.define(Hc.TAG,Hc)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=Fw;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.pin=t("pin"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,s=await Cp.load(t);if(e===this.languageToken)return this.messages=s,this.applyMessages(),s}set note(t){this.noteElement.textContent=t??"",this.noteElement.hidden=t===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.pin.checked;this.linkField.value=e?Wi.pinnedLink(t.link(),"0.204.2"):t.link(),this.fitLink();const i=`<script type="module" src="${e?Wi.pinned(t.module,"0.204.2"):Wi.current(t.module,import.meta.url,Mh.home())}"><\/script>
|
|
5229
|
+
${t.element()}`;this.embedMarkup.value=i,this.codeEditor&&(this.codeEditor.text=i)}applyMessages(){const t=this.messages;if(!t)return;const e=(s,i)=>{this.shadow.getElementById(s).textContent=i};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("pin-label",t.pin.replace("{version}","0.204.2")),this.pin.parentElement.title=t.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",t.close),this.linkField.setAttribute("aria-label",t.link)}show(t){this.linkBox.hidden=t!=="link",this.embedBox.hidden=t!=="embed",this.linkOption.setAttribute("aria-pressed",String(t==="link")),this.embedOption.setAttribute("aria-pressed",String(t==="embed")),t==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=H(async()=>{const{ShareCodeEditor:t}=await import("./ShareCodeEditor-DyEYu_9d.js");return{ShareCodeEditor:t}},__vite__mapDeps([57,58]),import.meta.url).then(({ShareCodeEditor:t})=>{this.codeEditor=new t(this.shadow.getElementById("embed-code"),this.embedMarkup.value,e=>{this.embedMarkup.value=e},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(t,e){try{await navigator.clipboard.writeText(t),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{e.select()}}}export{ji as $,Mh as A,tt as B,Pp as C,qt as D,vs as E,s1 as F,Et as G,fn as H,D1 as I,pi as J,Na as K,ya as L,No as M,U as N,Lo as O,Q as P,it as Q,Js as R,Hc as S,t2 as T,fu as U,vn as V,wn as W,t5 as X,Sp as Y,fe as Z,xp as _,qw as a,ns as a$,Wh as a0,Tf as a1,Q2 as a2,dh as a3,ko as a4,Yt as a5,$t as a6,Nm as a7,Ku as a8,Wm as a9,C as aA,Eo as aB,ss as aC,Rl as aD,Me as aE,Ll as aF,Sw as aG,ph as aH,Lf as aI,be as aJ,Bi as aK,Vi as aL,dt as aM,zs as aN,Xw as aO,Es as aP,H1 as aQ,uo as aR,Ce as aS,Y as aT,qs as aU,me as aV,ou as aW,Nt as aX,$e as aY,jt as aZ,hs as a_,Ys as aa,gp as ab,Rt as ac,Op as ad,Rp as ae,Ip as af,Dp as ag,Re as ah,da as ai,Qw as aj,J1 as ak,Z1 as al,j1 as am,Cm as an,Do as ao,av as ap,Pw as aq,vi as ar,Yi as as,Er as at,wt as au,Gr as av,Cd as aw,jc as ax,vr as ay,yr as az,so as b,Lr as b0,W1 as b1,Zt as b2,oh as b3,Ca as b4,Rw as b5,ad as b6,Ow as b7,Mp as b8,$ as b9,Jw as bA,e5 as bB,s5 as bC,ze as ba,ki as bb,qi as bc,Vt as bd,Zn as be,_r as bf,z as bg,kg as bh,Ta as bi,Z as bj,va as bk,Dh as bl,W as bm,mi as bn,Gn as bo,nh as bp,Hs as bq,Ia as br,ks as bs,_n as bt,Dt as bu,V as bv,Vn as bw,Fm as bx,Qh as by,G as bz,gh as c,jw as d,pe as e,n2 as f,io as g,If as h,Zw as i,Ym as j,Qe as k,lo as l,e0 as m,Bn as n,_h as o,Z2 as p,Wu as q,zw as r,dn as s,X as t,Ln as u,Ie as v,yt as w,Ps as x,In as y,at as z};
|