@rr0/ufoathome 0.161.0 → 0.162.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist-embed-scene/rr0-scene.mjs +4 -4
  2. package/dist-embed-sighting/{AdsbLolArchiveProvider-CQ9jtd4F.js → AdsbLolArchiveProvider-CX1R8zJF.js} +1 -1
  3. package/dist-embed-sighting/BallesterGuaspAssessor-CCjRjJck.js +1 -0
  4. package/dist-embed-sighting/BeamSystem-B0H346X_.js +1 -0
  5. package/dist-embed-sighting/{ContrailSystem-BqRjqAEx.js → ContrailSystem-BeK11Jxe.js} +1 -1
  6. package/dist-embed-sighting/GLTFLoader-B_T3zy3i.js +1 -0
  7. package/dist-embed-sighting/HeadlightSystem-DjtbpwEp.js +34 -0
  8. package/dist-embed-sighting/HynekAssessor-B8Iw0Cbz.js +1 -0
  9. package/dist-embed-sighting/NearestApproach-B5s-b6tU.js +1 -0
  10. package/dist-embed-sighting/PoherAssessor-CwQN9pB1.js +1 -0
  11. package/dist-embed-sighting/{RailwaySystem-YNlv2jnz.js → RailwaySystem-9blFcIdg.js} +1 -1
  12. package/dist-embed-sighting/ReferenceSystem-DFM_jZ-Q.js +1 -0
  13. package/dist-embed-sighting/SightingMessages_es-Dsr6169b.js +1 -0
  14. package/dist-embed-sighting/SightingMessages_fr-DQNbBD0c.js +1 -0
  15. package/dist-embed-sighting/{SightingMessages_it-BC3oCPqe.js → SightingMessages_it-WE-_Cuu4.js} +1 -1
  16. package/dist-embed-sighting/{TraceSystem-Cr68QBMq.js → TraceSystem-CLYZFxAf.js} +2 -2
  17. package/dist-embed-sighting/{WaterSystem-DSCbpNaj.js → WaterSystem-BulddAwi.js} +1 -1
  18. package/dist-embed-sighting/rr0-sighting.mjs +17 -17
  19. package/dist-embed-sighting-editor/BallesterGuaspAssessor-gX_y6kL8.js +1 -0
  20. package/dist-embed-sighting-editor/{BeamSystem-CFF1njA3.js → BeamSystem-BBonCZQ1.js} +1 -1
  21. package/dist-embed-sighting-editor/{ContrailSystem-B99N4pbI.js → ContrailSystem-BXARgrR4.js} +1 -1
  22. package/dist-embed-sighting-editor/{GLTFLoader-BrPQY4ob.js → GLTFLoader-BVRuOnnK.js} +1 -1
  23. package/dist-embed-sighting-editor/{HeadlightSystem-BYTfcIPd.js → HeadlightSystem-9ywZKJNB.js} +1 -1
  24. package/dist-embed-sighting-editor/HynekAssessor-B9lO770Q.js +1 -0
  25. package/dist-embed-sighting-editor/NearestApproach-DCFh8vV6.js +1 -0
  26. package/dist-embed-sighting-editor/PoherAssessor-CzLQhAxP.js +1 -0
  27. package/dist-embed-sighting-editor/{RailwaySystem-CCk8DP7w.js → RailwaySystem-BfDjza60.js} +1 -1
  28. package/dist-embed-sighting-editor/{ReferenceSystem-BDjiP56B.js → ReferenceSystem-DHPnvAXN.js} +1 -1
  29. package/dist-embed-sighting-editor/{RoadMarkings-V8WtA9-k.js → RoadMarkings-HF9xJtTp.js} +1 -1
  30. package/dist-embed-sighting-editor/{SightingEditorMessages_es-C5pk12_g.js → SightingEditorMessages_es-DGdkm-Yt.js} +1 -1
  31. package/dist-embed-sighting-editor/{SightingEditorMessages_fr-Cevzw3sm.js → SightingEditorMessages_fr-thlWKHJq.js} +1 -1
  32. package/dist-embed-sighting-editor/{SightingEditorMessages_it-r9D_FMqz.js → SightingEditorMessages_it-dkt2lxRe.js} +1 -1
  33. package/dist-embed-sighting-editor/{TraceSystem-C7ya-Gvd.js → TraceSystem-C1HaC0DX.js} +2 -2
  34. package/dist-embed-sighting-editor/{WaterSystem-HW6EhABp.js → WaterSystem-BDkfNF8C.js} +1 -1
  35. package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +16 -16
  36. package/package.json +1 -1
  37. package/dist-embed-sighting/BallesterGuaspAssessor-E4mL2MjD.js +0 -1
  38. package/dist-embed-sighting/BeamSystem-CVcdt0fc.js +0 -1
  39. package/dist-embed-sighting/GLTFLoader-CWl8CQPI.js +0 -1
  40. package/dist-embed-sighting/HeadlightSystem-xiiaXn1a.js +0 -34
  41. package/dist-embed-sighting/HynekAssessor-DPsLpEGQ.js +0 -1
  42. package/dist-embed-sighting/ReferenceSystem-By8XvGKa.js +0 -1
  43. package/dist-embed-sighting/SightingMessages_es-dFoOi4Xe.js +0 -1
  44. package/dist-embed-sighting/SightingMessages_fr-DK90WaSj.js +0 -1
  45. package/dist-embed-sighting-editor/BallesterGuaspAssessor-DUq2LwUo.js +0 -1
  46. package/dist-embed-sighting-editor/HynekAssessor-BtF8_xV5.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./BallesterGuaspAssessor-E4mL2MjD.js","./CoverageAssessor-C7k3p3iN.js","./ContrailSystem-BqRjqAEx.js","./ContrailGrowth-DwHS8If9.js","./trafficRuntime-CfPqH9j0.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./HynekAssessor-B8Iw0Cbz.js","./NearestApproach-B5s-b6tU.js","./BallesterGuaspAssessor-CCjRjJck.js","./CoverageAssessor-C7k3p3iN.js","./ContrailSystem-BeK11Jxe.js","./ContrailGrowth-DwHS8If9.js","./trafficRuntime-CfPqH9j0.js"])))=>i.map(i=>d[i]);
2
2
  class Jt{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=Jt.outline(Jt.BOOKMARK);static MILESTONES_ON=Jt.solid(Jt.BOOKMARK);static PICTURES_OFF=Jt.outline(`${Jt.PICTURE}${Jt.PICTURE_HILLS}`);static PICTURES_ON=Jt.solid(`${Jt.PICTURE}${Jt.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=Jt.outline(`${Jt.TRACE_LINE}${Jt.TRACE_MARK}`);static TRACES_ON=Jt.solid(`${Jt.TRACE_LINE}${Jt.TRACE_MARK}`);static MAP_OFF=Jt.outline(`${Jt.PIN}${Jt.PIN_HOLE}`);static MAP_ON=Jt.solid(`${Jt.PIN}${Jt.PIN_HOLE}`);static SHARE=Jt.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static FOLDED=Jt.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Jt.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Jt.svg("M7.4 5v14l11-7z");static PAUSE=Jt.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Jt.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=Jt.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=Jt.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Jt.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}class Th{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(t){const e=t.trim().toUpperCase(),i=Th.ISO.exec(e);if(!i||e==="P"||e.endsWith("T"))return;const[,n,s,r,a,c]=i,h=u=>u===void 0?0:Number(u.replace(",",".")),l=h(n)*604800+h(s)*86400+h(r)*3600+h(a)*60+h(c);return Number.isFinite(l)?l:void 0}static parse(t){let e=t.trim();if(e==="")return;const i=e.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(e=e.slice(0,-1).trim());const s=e.split("/");if(s.length>2)return;const r=s.map(u=>Th.seconds(u));if(r.some(u=>u===void 0))return;const[a,c]=r,h=Math.min(a,c??a),l=Math.max(a,c??a);return{doubt:n,minSeconds:h,maxSeconds:l,chosenSeconds:(h+l)/2}}static isExact(t){const e=Th.parse(t);return e!==void 0&&e.doubt===""&&e.minSeconds===e.maxSeconds}static format(t){const e=Math.max(0,Math.round(t*10)/10),i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(t){const e=Math.round(t*10)/10;if(e<60)return`${e} s`;const i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10,r=[];return i>0&&r.push(`${i} h`),n>0&&r.push(`${n} min`),s>0&&r.push(`${s} s`),r.join(" ")}}class ci{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(t){return 2*Math.atan(t.sizeM/(2*t.distanceM))*180/Math.PI}static inMoons(t){return t/ci.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(t,e,i){if(!(!t||!e))return{widthDeg:t.widthDeg+(e.widthDeg-t.widthDeg)*i,heightDeg:t.heightDeg+(e.heightDeg-t.heightDeg)*i}}static sizeMAt(t,e){return 2*t*Math.tan(e*Math.PI/360)}static distanceMAt(t,e){return t/(2*Math.tan(e*Math.PI/360))}}function US(o,t,e){if(!o||!t)return e<1?o:t;const i=((t.azimuthDeg-o.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((o.azimuthDeg+i*e)%360+360)%360,altitudeDeg:o.altitudeDeg+(t.altitudeDeg-o.altitudeDeg)*e}}function FS(o,t,e){const{bounds:i}=o;return t>=i.x&&t<=i.x+i.width&&e>=i.y&&e<=i.y+i.height}function gs(o,t,e){return o+(t-o)*e}function Pv(o){const t=/^#([0-9a-f]{6})$/i.exec(o);if(!t)return;const e=parseInt(t[1],16);return[e>>16&255,e>>8&255,e&255]}function zS(o){return`#${o.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`}function BS(o,t,e){const i=Pv(o),n=Pv(t);return!i||!n?e<1?o:t:zS([gs(i[0],n[0],e),gs(i[1],n[1],e),gs(i[2],n[2],e)])}function HS(o,t,e){const i={x:gs(o.bounds.x,t.bounds.x,e),y:gs(o.bounds.y,t.bounds.y,e),width:gs(o.bounds.width,t.bounds.width,e),height:gs(o.bounds.height,t.bounds.height,e)},n=gs(o.angle,t.angle,e),s=gs(o.transparency,t.transparency,e),r=gs(o.haloScale,t.haloScale,e),a=gs(o.blur??0,t.blur??0,e),c=gs(o.brightness??0,t.brightness??0,e),h=BS(o.color,t.color,e),l=ci.lerpAngular(o.angular,t.angular,e),u=US(o.aim,t.aim,e);return o.kind==="polygon"&&t.kind==="polygon"&&o.points.length===t.points.length?{...o,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:h,angular:l,aim:u,points:o.points.map((d,f)=>({x:gs(d.x,t.points[f].x,e),y:gs(d.y,t.points[f].y,e)}))}:{...e<1?o:t,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:h,angular:l,aim:u}}class ja{static DEFAULT_COLOR="#e8e6df";static complete(t,e=[]){const i=new Map;return t.map((n,s)=>({keyframe:n,index:s})).sort((n,s)=>n.keyframe.t-s.keyframe.t).map(({keyframe:n,index:s})=>({t:n.t,shapes:(n.shapes??[]).map((r,a)=>{const c=`timeline.keyframes.${s}.shapes.${a}.shape`,h=ja.completed(r,i.get(r.sourceId),c,e);return i.set(r.sourceId,h),{sourceId:r.sourceId,shape:h}})}))}static thin(t,e){const i=new Map,n=new Set;return t.map((s,r)=>({t:s.t,shapes:s.shapes.map(a=>{const c=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!c)return{sourceId:a.sourceId,shape:a.shape};const h=ja.thinned(a.shape,c);if(e){const l=h;e(r,a.sourceId)?(delete l.bounds,delete l.points,n.add(a.sourceId)):n.delete(a.sourceId)&&(l.bounds=a.shape.bounds,a.shape.kind==="polygon"&&(l.points=a.shape.points),a.shape.aim&&(l.aim=a.shape.aim),a.shape.angular&&(l.angular=a.shape.angular))}return{sourceId:a.sourceId,shape:h}})}))}static thinned(t,e){const i=e,n={};for(const[s,r]of Object.entries(t))(typeof r=="object"&&r!==null&&!Array.isArray(r)&&"value"in r||r!==i[s]&&JSON.stringify(r)!==JSON.stringify(i[s]))&&(n[s]=r);return"bounds"in n&&(t.aim&&(n.aim=t.aim),t.angular&&(n.angular=t.angular)),n}static completed(t,e,i,n){const s=t.shape??{},r=e??ja.firstAppearance(s,i,n),a={...r};s.bounds&&e&&(e.aim||e.angular)&&!s.aim&&!s.angular&&n.push({kind:"pixels-over-angles",path:i}),s.bounds&&(s.aim||delete a.aim,s.angular||delete a.angular);const c=s.kind??r.kind??"oval",h={...a,...s,kind:c};if(c==="polygon"&&!h.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:l,height:u}=h.bounds;return{...h,points:[{x:0,y:0},{x:l,y:0},{x:l,y:u},{x:0,y:u}]}}return h}static firstAppearance(t,e,i){return t.kind||i.push({kind:"defaulted",path:`${e}.kind`,expected:'"oval"'}),t.color||i.push({kind:"defaulted",path:`${e}.color`,expected:`"${ja.DEFAULT_COLOR}"`}),!t.bounds&&!t.aim&&i.push({kind:"unplaced",path:e}),!t.bounds&&!t.angular&&i.push({kind:"unsized",path:e}),{kind:t.kind??"oval",bounds:{...ja.NEUTRAL_BOUNDS},color:ja.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:ci.CANVAS_WIDTH_PX/2,y:ci.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Qu{keyframes=[];order=[];groups=[];span=0;addKeyframe(t,e){const i=this.findInsertIndex(t);if(this.keyframes[i]?.t===t){const n=new Set(e.map(s=>s.sourceId));this.keyframes[i]={t,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...e]}}else this.keyframes.splice(i,0,{t,shapes:[...e]});for(const n of e)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getKeyframeAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e];return i?.t===t?i:void 0}getShapeAt(t,e){return this.getKeyframeAt(t)?.shapes.find(i=>i.sourceId===e)?.shape}getLatestShapeAt(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return n.shape}}getInterpolatedShapeAt(t,e){const i=this.findShapeAtOrBefore(t,e);if(i?.t===t)return i.shape;const n=this.findShapeAtOrAfter(t,e);return i?n?HS(i.shape,n.shape,(t-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(t,e){for(let i=this.findInsertIndex(t);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(t,e,i,n){const s=this.sourceIds;for(let r=s.length-1;r>=0;r--){if(n?.has(s[r]))continue;const a=this.getInterpolatedShapeAt(t,s[r]);if(a&&FS(a,e,i))return{sourceId:s[r],shape:a}}}removeSource(t){for(let e=this.keyframes.length-1;e>=0;e--){const i=this.keyframes[e].shapes.filter(n=>n.sourceId!==t);i.length===0?this.keyframes.splice(e,1):i.length!==this.keyframes[e].shapes.length&&(this.keyframes[e]={t:this.keyframes[e].t,shapes:i})}this.order=this.order.filter(e=>e!==t),this.removeFromGroup(t)}removeShapeAt(t,e){const i=this.findInsertIndex(t),n=this.keyframes[i];if(n?.t!==t)return;const s=n.shapes.filter(r=>r.sourceId!==e);s.length===0?this.keyframes.splice(i,1):s.length!==n.shapes.length&&(this.keyframes[i]={t,shapes:s})}group(t,e){const i=new Set(t),n=[];for(const r of t){const a=this.topOf(r),c=a!==r&&this.leavesOf(a).every(h=>i.has(h))?a:r;c===r&&a!==r&&this.removeFromGroup(r),n.includes(c)||n.push(c)}if(n.length<2)return;const s=e??this.freshGroupId();return this.groups.push({id:s,members:n}),s}ungroup(t){const e=this.topOf(t);e!==t&&(this.groups=this.groups.filter(i=>i.id!==e))}groupMembers(t){const e=this.topOf(t);return e===t?void 0:this.leavesOf(e)}get allGroups(){return this.groups}setGroups(t,e=!0){this.groups=t.map(i=>({...i,members:[...i.members]})),e&&this.pruneGroups()}groupOf(t){return this.groups.find(e=>e.id===t)}leavesOf(t,e=new Set){const i=this.groupOf(t);return i?e.has(t)?[]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e))):[t]}parentOf(t){return this.groups.find(e=>e.members.includes(t))}topOf(t){let e=t;for(let i=this.parentOf(e),n=0;i&&n<100;i=this.parentOf(e),n++)e=i.id;return e}freshGroupId(){for(let t=this.groups.length+1;;t++){const e=`group-${t}`;if(!this.groupOf(e)&&!this.order.includes(e))return e}}removeFromGroup(t){const e=this.parentOf(t);e&&(e.members=e.members.filter(i=>i!==t),this.collapse())}pruneGroups(){const t=e=>this.order.includes(e)||this.groupOf(e)!==void 0;for(const e of this.groups)e.members=e.members.filter(t);this.collapse()}collapse(){for(let t=this.groups.find(e=>e.members.length<2);t;t=this.groups.find(e=>e.members.length<2)){const e=t;this.groups=this.groups.filter(i=>i!==e);for(const i of this.groups)i.members=i.members.flatMap(n=>n===e.id?e.members:[n])}}bringToFront(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.push(t))}sendToBack(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.unshift(t))}get duration(){const t=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(t,this.span)}get hasSpan(){return this.span>0}setSpan(t){this.span=Math.max(0,t)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groupsJson(),span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groupsJson()}}groupsJson(){return this.groups.map(t=>({...t,members:[...t.members]}))}static fromJSON(t,e,i=!0){const n=new Qu;for(const s of ja.complete(t.keyframes??[],e))n.addKeyframe(s.t,s.shapes);if(t.span!==void 0&&t.span>0&&(n.span=t.span),t.order){const s=n.order.filter(r=>!t.order.includes(r));n.order=[...t.order,...s]}return t.groups&&(n.groups=t.groups.filter(s=>typeof s?.id=="string"&&Array.isArray(s.members)).map(s=>({...s,members:[...s.members]})),i&&n.pruneGroups()),n}}function GS(o,t,e){return Math.max(t,Math.min(e,o))}function VS(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function Rc(o,t,e){return o+(t-o)*e}function WS(o,t,e){return{lat:o.lat===void 0||t.lat===void 0?void 0:Rc(o.lat,t.lat,e),lng:o.lng===void 0||t.lng===void 0?void 0:Rc(o.lng,t.lng,e),elevationM:Rc(o.elevationM,t.elevationM,e),headingDeg:o.headingDeg===void 0||t.headingDeg===void 0?void 0:VS(o.headingDeg,t.headingDeg,e),pitchDeg:Rc(o.pitchDeg,t.pitchDeg,e),rollDeg:Rc(o.rollDeg??0,t.rollDeg??0,e),fovDeg:Rc(o.fovDeg,t.fovDeg,e),fNumber:o.fNumber,focusDistanceM:o.focusDistanceM,filter:o.filter}}class pn{static at(t,e,i,n,s){const r=t[i],c=t[i+1]-r;if(c<=0)return e[i];const h=pn.tangent(t,e,i,s),l=pn.tangent(t,e,i+1,s),u=(n-r)/c,d=u*u,f=d*u;return(2*f-3*d+1)*e[i]+(f-2*d+u)*c*h+(-2*f+3*d)*e[i+1]+(f-d)*c*l}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(t,e,i,n){const s=t[i],a=t[i+1]-s;if(a<=0)return e[i];const c=l=>l+1<e.length?e[l+1]===e[l]:!0,h=e[i+1]!==e[i];if(h&&c(i+1)){const l=pn.tangent(t,e,i,!0),u=pn.ARRIVAL*(e[i+1]-e[i])/a;return pn.hermite(e[i],l,e[i+1],u,a,(n-s)/a)}return!h&&i>0&&e[i-1]!==e[i]?e[i]+pn.settle(t,e,i,n-s,a):pn.at(t,e,i,n,!0)}static settle(t,e,i,n,s){const r=t[i]-t[i-1];if(r<=0||n<=0)return 0;const a=pn.ARRIVAL*(e[i]-e[i-1])/r,c=Math.min(pn.SETTLE_MS,.4*r),h=Number.isFinite(s)?(1-Math.min(1,n/s))**2:1;return a*n*Math.exp(-n/c)*h}static hermite(t,e,i,n,s,r){const a=r*r,c=a*r;return(2*c-3*a+1)*t+(c-2*a+r)*s*e+(-2*c+3*a)*i+(c-a)*s*n}static BRAKE_S=.8;static paced(t,e,i,n){if(!i&&!n)return t;const s=e>0?Math.min(.5,pn.BRAKE_S/e):.5;if(i&&n){const a=1/(1-s);return t<=s?a*t*t/(2*s):t>=1-s?1-a*(1-t)*(1-t)/(2*s):a*(t-s/2)}const r=a=>{const c=1/(1-s/2);if(a<=1-s)return c*a;const h=a-(1-s);return c*(1-s)+c*(h-h*h/(2*s))};return n?r(t):1-r(1-t)}static tangent(t,e,i,n){const s=t.length-1,r=f=>(e[f+1]-e[f])/(t[f+1]-t[f]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),c=r(i);if(a*c<=0)return 0;const h=t[i]-t[i-1],l=t[i+1]-t[i],u=2*l+h,d=l+2*h;return(u+d)/(u/a+d/c)}}class mu{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,pose:e}:this.keyframes.splice(i,0,{t,pose:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestPoseAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].pose:void 0}getInterpolatedPoseAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.pose;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.pose;if(!n)return this.settledAfterEnd(e-1,t);const s=WS(i.pose,n.pose,GS((t-i.t)/(n.t-i.t),0,1));return this.humanly(e-1,t,s)}settledAfterEnd(t,e){const i=this.keyframes[t];if(t<1)return i.pose;const n=this.keyframes[t-1],s=[n.t,i.t],r=(l,u)=>l===void 0||u===void 0?0:pn.settle(s,[l,u],1,e-i.t,1/0),a=n.pose.headingDeg===void 0||i.pose.headingDeg===void 0?void 0:((i.pose.headingDeg-n.pose.headingDeg)%360+540)%360-180,c=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,h=i.pose.pitchDeg+r(n.pose.pitchDeg,i.pose.pitchDeg);return c===i.pose.headingDeg&&h===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:c,pitchDeg:h}}humanly(t,e,i){const n=Math.max(0,t-1),s=Math.min(this.keyframes.length-1,t+2),r=this.keyframes.slice(n,s+1),a=t-n,c=r.map(y=>y.t),h=(y,b)=>{const S=r.map(_=>y(_.pose));if(!S.some(_=>_===void 0))return pn.at(c,S,a,e,b)},l=y=>{const b=r.map(S=>y(S.pose));if(!b.some(S=>S===void 0))return pn.gaze(c,b,a,e)},u=r.map(y=>y.pose.headingDeg);let d;if(u.every(y=>y!==void 0)){const y=[u[0]];for(let b=1;b<u.length;b++)y.push(y[b-1]+((u[b]-u[b-1])%360+540)%360-180);d=(pn.gaze(c,y,a,e)%360+360)%360}const f=this.keyframes[t],p=this.keyframes[t+1],m=(y,b)=>y.lat===b.lat&&y.lng===b.lng&&y.elevationM===b.elevationM,g=!m(f.pose,p.pose),v=g&&t>0&&m(this.keyframes[t-1].pose,f.pose),M=g&&t+2<this.keyframes.length&&m(p.pose,this.keyframes[t+2].pose);let w;if(v||M){const y=pn.paced((e-f.t)/(p.t-f.t),(p.t-f.t)/1e3,v,M),b=(S,_)=>S===void 0||_===void 0?void 0:S+(_-S)*y;w={lat:b(f.pose.lat,p.pose.lat),lng:b(f.pose.lng,p.pose.lng),elevationM:b(f.pose.elevationM,p.pose.elevationM)}}return{...i,lat:w?w.lat:h(y=>y.lat,!1)??i.lat,lng:w?w.lng:h(y=>y.lng,!1)??i.lng,elevationM:w?w.elevationM:h(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:l(y=>y.pitchDeg)??i.pitchDeg,rollDeg:h(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:h(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new mu;for(const i of t.keyframes)e.addKeyframe(i.t,i.pose);return e}}class Qa{static MAX_CHANGE_PER_S=.05;points;followed;constructor(t){let e="none",i=0;this.points=t.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(e=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:e,lastFallingIntensity:i,intensity:s.precipitationType==="none"?0:s.precipitationIntensity,type:s.precipitationType})),this.followed=[];for(let n=0;n<this.points.length;n++){if(n===0){this.followed.push(this.points[0].intensity);continue}const s=this.points[n-1],r=this.points[n];this.followed.push(Qa.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(t){if(this.points.length===0||t<this.points[0].t)return;let e=this.points.length-1;for(;e>0&&this.points[e].t>t;)e--;const i=this.points[e],n=this.points[e+1],s=n?Qa.follow(this.followed[e],i.intensity,n.intensity,(n.t-i.t)/1e3,(t-i.t)/1e3):Qa.follow(this.followed[e],i.intensity,i.intensity,1,(t-i.t)/1e3);return{type:Qa.typeBetween(i,n,t,s),intensity:s,character:Qa.characterBetween(i,n,t)}}static characterBetween(t,e,i){return t.type==="none"?e&&e.type!=="none"?e.intensity:t.lastFallingIntensity:!e||e.type==="none"?t.intensity:t.intensity+(e.intensity-t.intensity)*(i-t.t)/(e.t-t.t||1)}static typeBetween(t,e,i,n){return t.type==="none"?e&&e.type!=="none"&&i>t.t?e.type:n>0?t.lastFalling:"none":e&&e.type==="none"&&n<=0?"none":t.type}static follow(t,e,i,n,s){const r=Qa.MAX_CHANGE_PER_S,a=n>0?(i-e)/n:0,c=u=>e+a*Math.min(Math.max(u,0),n);let h=t,l=0;for(let u=0;u<8&&l<s;u++){const d=c(l)-h;if(Math.abs(d)<1e-9){const w=l<n?a:0;if(Math.abs(w)<=r){const b=l<n?Math.min(s,n):s;h=c(b),l=b;continue}const y=Math.min(s,n);h+=Math.sign(w)*r*(y-l),l=y;continue}const f=Math.sign(d),p=l<n?a:0,m=r-f*p,g=m>0?l+Math.abs(d)/m:1/0,v=l<n?n:1/0,M=Math.min(s,g,v);h+=f*r*(M-l),l=M,M===g&&(h=c(l))}return Math.min(1,Math.max(0,h))}}const b1=1e3,XS=.65,$S=.05,A0={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function kf(o){if(o.cloudLayers!==void 0)return o.cloudLayers;const t=[],e=o.lowerCloudCover??o.cloudCover;return e>0&&t.push({id:"lower",type:"cumulus",baseM:o.cloudBaseM??b1,thicknessM:650,coverage:e,sizeM:1400,density:1,darkness:o.cloudDarkness}),(o.highCloudCover??0)>0&&t.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:o.highCloudCover,sizeM:2200,density:.35,darkness:o.cloudDarkness,iceCrystalAlignment:o.iceCrystalAlignment}),t}function Ei(o,t,e){return o+(t-o)*e}function x1(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function YS(o,t,e){return Math.max(t,Math.min(e,o))}function KS(o=[],t=[],e){if(!(!o.length&&!t.length))return[...new Set([...o.map(i=>i.id),...t.map(i=>i.id)])].map(i=>{const n=o.find(c=>c.id===i),s=t.find(c=>c.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:Ei(r.eastM,a.eastM,e),northM:Ei(r.northM,a.northM,e),baseM:Ei(r.baseM,a.baseM,e),thicknessM:Ei(r.thicknessM,a.thicknessM,e),widthM:Ei(r.widthM,a.widthM,e),depthM:Ei(r.depthM,a.depthM,e),rotationDeg:x1(r.rotationDeg,a.rotationDeg,e),density:Ei(r.density,a.density,e),darkness:Ei(r.darkness??0,a.darkness??0,e)}})}function qS(o,t,e){if(o.cloudLayers===void 0&&t.cloudLayers===void 0)return;const i=kf(o),n=kf(t);return e>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(u=>u.id===r),c=n.find(u=>u.id===r),h=a??{...c,coverage:0},l=c??{...a,coverage:0};return{...h,instances:KS(a?.instances,c?.instances,e),baseM:Ei(h.baseM,l.baseM,e),thicknessM:Ei(h.thicknessM,l.thicknessM,e),coverage:Ei(h.coverage,l.coverage,e),sizeM:Ei(h.sizeM,l.sizeM,e),density:Ei(h.density,l.density,e),darkness:Ei(h.darkness??o.cloudDarkness,l.darkness??t.cloudDarkness,e),iceCrystalAlignment:h.iceCrystalAlignment===void 0||l.iceCrystalAlignment===void 0?void 0:Ei(h.iceCrystalAlignment,l.iceCrystalAlignment,e),windSpeed:h.windSpeed===void 0&&l.windSpeed===void 0?void 0:Ei(h.windSpeed??o.windSpeed,l.windSpeed??t.windSpeed,e),windDirectionDeg:h.windDirectionDeg===void 0&&l.windDirectionDeg===void 0?void 0:x1(h.windDirectionDeg??o.windDirectionDeg,l.windDirectionDeg??t.windDirectionDeg,e)}})}function ZS(o,t,e){return{cloudLayers:qS(o,t,e),cloudCover:Ei(o.cloudCover,t.cloudCover,e),cloudDarkness:Ei(o.cloudDarkness,t.cloudDarkness,e),highCloudCover:o.highCloudCover===void 0||t.highCloudCover===void 0?void 0:Ei(o.highCloudCover,t.highCloudCover,e),iceCrystalAlignment:o.iceCrystalAlignment===void 0||t.iceCrystalAlignment===void 0?void 0:Ei(o.iceCrystalAlignment,t.iceCrystalAlignment,e),rareIceCrystals:o.rareIceCrystals===void 0||t.rareIceCrystals===void 0?void 0:Ei(o.rareIceCrystals,t.rareIceCrystals,e),lowerCloudCover:o.lowerCloudCover===void 0||t.lowerCloudCover===void 0?void 0:Ei(o.lowerCloudCover,t.lowerCloudCover,e),cloudBaseM:o.cloudBaseM===void 0||t.cloudBaseM===void 0?void 0:Ei(o.cloudBaseM,t.cloudBaseM,e),relativeHumidity:o.relativeHumidity===void 0||t.relativeHumidity===void 0?void 0:Ei(o.relativeHumidity,t.relativeHumidity,e),precipitationType:e<1?o.precipitationType:t.precipitationType,precipitationIntensity:Ei(o.precipitationIntensity,t.precipitationIntensity,e),windDirectionDeg:x1(o.windDirectionDeg,t.windDirectionDeg,e),windSpeed:Ei(o.windSpeed,t.windSpeed,e),storm:e<1?o.storm:t.storm}}class gu{keyframes=[];ramp;addKeyframe(t,e){this.ramp=void 0;const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,weather:e}:this.keyframes.splice(i,0,{t,weather:e})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(t){this.ramp=void 0;const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestWeatherAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].weather:void 0}getInterpolatedWeatherAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.weather;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];return i?n?ZS(i.weather,n.weather,YS((t-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(t){const e=this.getInterpolatedWeatherAt(t);if(!e)return;const i=(this.ramp??=new Qa(this.keyframes)).at(t);if(!i)return e;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...e,precipitationType:n,precipitationIntensity:r,precipitationAmount:a}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new gu;for(const i of t.keyframes)e.addKeyframe(i.t,{...A0,...i.weather});return e}}class vu{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,sound:e}:this.keyframes.splice(i,0,{t,sound:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}getLatestSoundAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].sound:void 0}getInterpolatedSoundAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.sound;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.sound;if(!n)return i.sound;const s=(t-i.t)/(n.t-i.t);return this.lerp(i.sound,n.sound,Math.max(0,Math.min(1,s)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new vu;for(const i of t.keyframes)e.addKeyframe(i.t,i.sound);return e}lerp(t,e,i){return{kind:i<1?t.kind:e.kind,volume:t.volume+(e.volume-t.volume)*i,pitchHz:t.pitchHz+(e.pitchHz-t.pitchHz)*i,src:i<1?t.src:e.src}}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}}const JS=100,jS={kind:"none",volume:0,pitchHz:JS};class ch{static DEFAULT_FOCAL_MM=50;static FOCAL_RANGE_MM={minMm:14,maxMm:135};static BODIES=[{id:"eos-450d",name:"Canon EOS 450D (APS-C)",widthMm:22.2,heightMm:14.8,pixelUm:5.2,year:2008},{id:"eos-60da",name:"Canon EOS 60Da (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.3,year:2012},{id:"eos-70d",name:"Canon EOS 70D (APS-C)",widthMm:22.5,heightMm:15,pixelUm:4.1,year:2013},{id:"eos-80d",name:"Canon EOS 80D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:3.7,year:2016},{id:"eos-7d",name:"Canon EOS 7D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.1,year:2009},{id:"eos-7d-ii",name:"Canon EOS 7D Mark II (APS-C)",widthMm:22.4,heightMm:15,pixelUm:4.1,year:2014},{id:"eos-5d",name:"Canon EOS 5D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:8.2,year:2005},{id:"eos-5d-ii",name:"Canon EOS 5D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:6.4,year:2008},{id:"eos-5d-iii",name:"Canon EOS 5D Mark III (full frame)",widthMm:36,heightMm:24,pixelUm:6.25,year:2012},{id:"eos-5d-iv",name:"Canon EOS 5D Mark IV (full frame)",widthMm:36,heightMm:24,pixelUm:5.36,year:2016},{id:"eos-6d",name:"Canon EOS 6D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:6.55,year:2012},{id:"eos-6d-ii",name:"Canon EOS 6D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:5.77,year:2017},{id:"nikon-d3",name:"Nikon D3 / D700 (full frame)",widthMm:36,heightMm:23.9,pixelUm:8.44,year:2007},{id:"nikon-d7000",name:"Nikon D7000 (DX)",widthMm:23.6,heightMm:15.6,pixelUm:4.78,year:2010},{id:"nikon-d7100",name:"Nikon D7100 / D7200 (DX)",widthMm:23.5,heightMm:15.6,pixelUm:3.9,year:2013},{id:"nikon-d500",name:"Nikon D500 / D7500 (DX)",widthMm:23.5,heightMm:15.7,pixelUm:4.2,year:2016}];static instruments(){return ch.BODIES.map(t=>({id:t.id,category:"dslr",name:t.name,projection:"rectilinear",frame:{widthMm:t.widthMm,heightMm:t.heightMm,focalLengthMm:ch.DEFAULT_FOCAL_MM,focalRangeMm:ch.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:t.year},apertureBlades:7,detailUm:t.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(ch.BODIES.map(t=>[t.id,t.name]))}}class rr{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*rr.DEFAULT_EYEPIECE_MM*Math.tan(rr.DEFAULT_APPARENT_FIELD_DEG*Math.PI/360);static RANGE={min:26/40*.63,max:26/6*3};static BINOCULARS=[{id:"binoculars-zeiss-6x30",name:"Carl Zeiss 6x30",magnification:6,apertureMm:30,trueFieldDeg:5,fromYear:1960},{id:"binoculars-zeiss-dialyt-10x40",name:"Carl Zeiss Dialyt 10x40 B T*",magnification:10,apertureMm:40,trueFieldDeg:6.3,fromYear:1975},{id:"binoculars-jenoptem-10x50",name:"Jenoptem 10x50 W",magnification:10,apertureMm:50,trueFieldDeg:7.3,fromYear:1960},{id:"binoculars-swarovski-7x50-habicht",name:"Swarovski 7x50 SL Habicht",magnification:7,apertureMm:50,trueFieldDeg:6.6,fromYear:1960},{id:"binoculars-swarovski-7x50-slc",name:"Swarovski 7x50 SLC",magnification:7,apertureMm:50,trueFieldDeg:7.1,fromYear:1990},{id:"binoculars-nikon-10x42-edg",name:"Nikon 10x42 EDG",magnification:10,apertureMm:42,trueFieldDeg:6.5,fromYear:2011},{id:"binoculars-canon-15x50-is",name:"Canon 15x50 IS All Weather",magnification:15,apertureMm:50,trueFieldDeg:4.5,fromYear:2008},{id:"binoculars-celestron-15x70",name:"Celestron 15x70 SkyMaster",magnification:15,apertureMm:70,trueFieldDeg:4.4,fromYear:1990},{id:"binoculars-miyauchi-25x141",name:"Miyauchi BR-141 Galaxy 45 25x141",magnification:25,apertureMm:141,trueFieldDeg:2.6,fromYear:2e3}];static TELESCOPES=[{id:"telescope-generic-60-700",name:"Telescope 60/700",apertureMm:60,focalLengthMm:700},{id:"telescope-generic-60-1000",name:"Telescope 60/1000",apertureMm:60,focalLengthMm:1e3},{id:"telescope-celestron-onyx-80edf",name:"Celestron Onyx 80EDF",apertureMm:80,focalLengthMm:500,fromYear:2010},{id:"telescope-celestron-c5",name:"Celestron C5 f/10",apertureMm:125,focalLengthMm:1250,fromYear:1970},{id:"telescope-celestron-c8",name:"Celestron C8 f/10",apertureMm:203,focalLengthMm:2032,fromYear:1970},{id:"telescope-celestron-c11",name:"Celestron C11 f/10",apertureMm:280,focalLengthMm:2800,fromYear:1970},{id:"telescope-celestron-c14",name:"Celestron C14 f/11",apertureMm:355.6,focalLengthMm:3910,fromYear:1970},{id:"telescope-meade-etx-80",name:"Meade ETX 80 f/5",apertureMm:80,focalLengthMm:400,fromYear:1996},{id:"telescope-meade-etx-90",name:"Meade ETX 90 f/13.8",apertureMm:90,focalLengthMm:1242,fromYear:1996},{id:"telescope-meade-etx-125",name:"Meade ETX 125 f/15",apertureMm:127,focalLengthMm:1900,fromYear:1996},{id:"telescope-meade-lx200-8",name:"Meade LX200 8 in f/10",apertureMm:200,focalLengthMm:2e3,fromYear:1992},{id:"telescope-meade-lx200-10",name:"Meade LX200 10 in f/10",apertureMm:250,focalLengthMm:2500,fromYear:1992},{id:"telescope-meade-lx200-12",name:"Meade LX200 12 in f/10",apertureMm:305,focalLengthMm:3048,fromYear:1992},{id:"telescope-meade-lx200-14",name:"Meade LX200 14 in f/10",apertureMm:355,focalLengthMm:3556,fromYear:1992},{id:"telescope-meade-lx200-16",name:"Meade LX200 16 in f/10",apertureMm:406,focalLengthMm:4064,fromYear:1992}];static instruments(){const t=rr.BINOCULARS.map(n=>({id:n.id,category:"binoculars",name:n.name,projection:"rectilinear",visualAid:{apertureMm:n.apertureMm,magnification:n.magnification,trueFieldDeg:n.trueFieldDeg},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}})),e=rr.FIELD_STOP_MM,i=rr.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:e*16/9,heightMm:e,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*rr.RANGE.min,maxMm:n.focalLengthMm*rr.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:rr.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...t,...i]}static names(){return Object.fromEntries(rr.instruments().map(t=>[t.id,t.name]))}}const cd=[{id:"eye",category:"eye",name:"Naked eye",projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",category:"camera",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"roamer-1-120",category:"camera",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",category:"camera",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",category:"camera",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"slr-35mm-zoom",category:"camera",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",category:"phone",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"phone-portrait",category:"phone",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"dashcam",mounted:!0,category:"video",name:"Dashcam",projection:"equidistant",frame:{widthMm:5.76,heightMm:3.24,focalLengthMm:3.2},fNumber:2,exposureSeconds:1/30,exposureRangeSeconds:{min:1/1e4,max:1/30},years:{from:2008},apertureBlades:void 0,detailUm:3,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},{id:"cctv",mounted:!0,category:"video",name:"Security camera",projection:"rectilinear",frame:{widthMm:4.8,heightMm:3.6,focalLengthMm:3.6},fNumber:2,exposureSeconds:1/50,exposureRangeSeconds:{min:1/1e5,max:1/50},years:{from:1990},apertureBlades:void 0,detailUm:6,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},...ch.instruments(),...rr.instruments()];class ki{static get default(){return cd[0]}static byId(t){return cd.find(e=>e.id===t)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(t){const e=t.frame;return e?ki.fieldOf(t.projection,e.heightMm,e.focalLengthMm):t.visualAid?.trueFieldDeg??ki.UNAIDED_FIELD_DEG}static fieldOf(t,e,i){return(t==="equidistant"?e/i:2*Math.atan(e/(2*i)))*180/Math.PI}static aspectOf(t){const e=t.frame;return e?e.widthMm/e.heightMm:ki.UNAIDED_ASPECT}static frameWidthPx(t,e){return Math.round(e*ki.aspectOf(t))}static CATEGORIES=["eye","camera","dslr","phone","video","binoculars","telescope"];static unavailability(t,e){const i=t.years;if(!(e===void 0||!i)){if(e<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&e>i.to)return{kind:"after",to:i.to}}}static availableAt(t){return t===void 0?cd:cd.filter(e=>!e.years||t>=e.years.from&&(e.years.to===void 0||t<=e.years.to))}static fieldOfViewDegAt(t,e){const i=t.frame;if(!(!i||e<=0))return ki.fieldOf(t.projection,i.heightMm,e)}static focalLengthMmFor(t,e){const i=t.frame;if(!(!i||e<=0||e>=180))return t.projection==="equidistant"?i.heightMm/(e*Math.PI/180):i.heightMm/(2*Math.tan(e*Math.PI/360))}static bladesShowing(t,e){if(t.apertureBlades===void 0)return 0;const i=e??t.fNumber,n=t.fNumberRange?.min;if(i===void 0||n===void 0)return 1;const s=Math.max(0,Math.min(1,(i/n-1)/.3));return s*s*(3-2*s)}static starPointsOf(t,e){const i=t.apertureBlades;return i===void 0||i<3||ki.bladesShowing(t,e)<.5?0:i%2===0?i:i*2}}class os{constructor(t){this.entries=t}static empty(){return new os(new Map)}get size(){return this.entries.size}at(t){return this.entries.get(t)}paths(){return[...this.entries.keys()]}set(t,e){e.basis==="stated"&&e.rationale===void 0&&e.how===void 0?this.entries.delete(t):this.entries.set(t,e)}clear(t){for(const e of this.entries.keys())(e===t||e.startsWith(`${t}.`))&&this.entries.delete(e)}static strip(t){const e=new os(new Map);return{recording:os.stripValue(t,[],e),provenance:e}}static restore(t,e){if(e.size===0)return t;const i={...t},n=new Set([i]);for(const s of e.paths()){const r=e.at(s),a=s.split("."),c=os.writableHolderOf(i,a,n);if(!c)continue;const h=a[a.length-1],l=c[h];l!==void 0&&(r.of!==void 0&&JSON.stringify(r.of)!==JSON.stringify(l)||(c[h]={value:l,...r.basis==="stated"?{}:{basis:r.basis},...r.rationale===void 0?{}:{rationale:r.rationale},...r.how===void 0?{}:{how:r.how}}))}return i}static isWrapper(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}static stripValue(t,e,i){return os.isWrapper(t)?(i.set(e.join("."),{basis:t.basis??"stated",...t.rationale===void 0?{}:{rationale:t.rationale},...t.how===void 0?{}:{how:t.how},of:t.value}),os.stripValue(t.value,e,i)):Array.isArray(t)?t.map((n,s)=>os.stripValue(n,[...e,String(s)],i)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([n,s])=>[n,os.stripValue(s,[...e,n],i)])):t}static writableHolderOf(t,e,i){let n=t;for(const s of e.slice(0,-1)){const r=n[s];if(typeof r!="object"||r===null)return;if(i.has(r)){n=r;continue}const a=Array.isArray(r)?[...r]:{...r};i.add(a),n[s]=a,n=a}return n}}class Is extends Error{}class _0{constructor(t){this.name=t}validate(t){return!0}}class eb extends _0{min;max;constructor(t,e,i){super(t),this.min=e,this.max=i}validate(t){if(typeof t!="number")throw new Is(`${this.name} value must be a number, but was ${t}`);if(t<this.min||t>this.max)throw new Is(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${t}`);return super.validate(t)}}class pi{name;min;max;duration;subUnit;validator;constructor(t,e,i,n,s=new eb(t,e,i)){this.name=t,this.min=e,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(t){return this.validator.validate(t)}[Symbol.iterator](){let t=this.min;return{next:()=>{const e={done:t>this.max,value:t};return t++,e}}}}class S1{millisecond;second;minute;hour;day;month;year}class QS extends S1{}class ib extends QS{millisecond=new pi("millisecond",0,999,void 0);second=new pi("second",0,59,this.millisecond);minute=new pi("minute",0,59,this.second);hour=new pi("hour",0,23,this.minute);day=new pi("day",1,31,this.hour);month=new pi("month",1,12,this.day);year=new pi("year",0,9999,this.month)}const re=new ib;class nb extends eb{constructor(t=1,e=12){super("month",t,e)}}class hh extends pi{static Month28=new hh(28);static Month29=new hh(29);static ThirtyDays=new hh(30);static ThirtyOneDays=new hh(31);constructor(t,e=new nb(1,t)){super("month",1,t,re.day,e)}static create(t,e){switch(t){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return e%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new Is("Unsupported month",t,e)}}}class Xr{static instance=new Xr;render(t){return t.value.toString()}}class Yn{unit;#t;constructor(t,e){this.unit=e,this.value=typeof t=="number"?t:t.value}get value(){return this.#t}set value(t){this.unit.validate(t),this.#t=t}get duration(){return this.value*this.unit.duration}#e(t){if(this.constructor.name!==t.constructor.name)throw new _0(`${this.unit.name} "${this.toString()}" cannot be compared with ${t.unit?.name} "${t.toString()}"`)}compare(t){return this.#e(t),this.value-t.value}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}previous(t=this.unit){const e=this.value-1;return new this.constructor(e,t)}next(t=this.unit){const e=this.value+1;return new this.constructor(e,t)}toString(t=Xr.instance){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Ot{static#t=new Map;static register(t,e){Ot.#t.set(t,e)}static get(t){const e=Ot.#t.get(t);if(!e)throw new Is(`No default parser registered for ${t.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return e()}}class $h extends Yn{constructor(t=new Date().getFullYear(),e=re.year){super(t,e)}static fromString(t,e=Ot.get($h)){return new $h(e.parse(t))}}class aa extends Xr{static default=new aa("0",2);constructor(t,e){super(),this.char=t,this.size=e}render(t){return super.render(t).padStart(this.size,this.char)}}class Yh extends Yn{constructor(t=new Date().getMonth()+1,e=re.month){super(t,e)}static fromString(t,e=Ot.get(Yh)){return new Yh(e.parse(t))}toString(t=aa.default){return super.toString(t)}}class Kh extends Yn{constructor(t=new Date().getDate(),e=re.day){super(t,e)}static fromString(t,e=Ot.get(Kh)){const i=e.parse(t);return new Kh(i)}toString(t=aa.default){return super.toString(t)}}class qh extends Yn{constructor(t=new Date().getHours(),e=re.hour){super(t,e)}static fromString(t,e=Ot.get(qh)){return new qh(e.parse(t))}toString(t=aa.default){return super.toString(t)}}class Zh extends Yn{constructor(t=new Date().getMinutes(),e=re.minute){super(t,e)}static fromString(t,e=Ot.get(Zh)){return new Zh(e.parse(t))}toString(t=aa.default){return super.toString(t)}}class Jh extends Yn{constructor(t=new Date().getSeconds(),e=re.second){super(t,e)}static fromString(t,e=Ot.get(Jh)){return new Jh(e.parse(t),re.second)}toString(t=aa.default){return super.toString(t)}}class Oo extends Yn{static renderer=new aa("0",3);constructor(t,e=re.millisecond){super(t,e)}static parseFraction(t){return parseInt(t.padEnd(3,"0").substring(0,3),10)}toString(t=Oo.renderer){return super.toString(t)}}class tE{render(t){return t.toString()}}class eE extends tE{render(t){const e=t.value,i=Math.abs(e),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=e<0?"-":"+",a=n.toString().padStart(2,"0"),c=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+c}}}class Ro{value;name="timeshift";renderer;constructor(t=0){this.value=t}static fromString(t,e=Ot.get(Ro),i=void 0){const n=e.parse(t,i);return new Ro(n)}toString(t=new eE){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Vn{static timeshift(t,e){return t+(Vn.isDaylight(e)?60:0)}static isDaylight(t){const{year:e,month:i,day:n}=t,s=t.hour??12;if(![e,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=Vn.rule(e);if(!r)return!1;const a=Vn.rank(i,n,s);return a>=Vn.rank(r.start.month,r.start.day,2)&&a<Vn.rank(r.end.month,r.end.day,2)}static rule(t){if(t<1967)return;const e={month:10,day:Vn.sunday(t,10,-1)};return t>=2007?{start:{month:3,day:Vn.sunday(t,3,2)},end:{month:11,day:Vn.sunday(t,11,1)}}:t>=1987?{start:{month:4,day:Vn.sunday(t,4,1)},end:e}:t===1975?{start:{month:2,day:23},end:e}:t===1974?{start:{month:1,day:6},end:e}:{start:{month:4,day:Vn.sunday(t,4,-1)},end:e}}static sunday(t,e,i){const n=new Date(Date.UTC(2e3,e-1,1));n.setUTCFullYear(t);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,Vn.isLeap(t)?29:28,31,30,31,30,31,31,30,31,30,31][e-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(t){return t%4===0&&(t%100!==0||t%400===0)}static rank(t,e,i){return(t*100+e)*100+i}}const iE={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},nE={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},sE={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},rE={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},aE={name:"PT",timeshift:o=>Vn.timeshift(-480,o),title:"Pacific Time (US)"},oE={name:"MT",timeshift:o=>Vn.timeshift(-420,o),title:"Mountain Time (US)"},cE={name:"CT",timeshift:o=>Vn.timeshift(-360,o),title:"Central Time (US)"},hE={name:"ET",timeshift:o=>Vn.timeshift(-300,o),title:"Eastern Time (US)"},lE={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},uE={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},dE={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},fE={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},pE={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},mE={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},gE={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},vE={name:"Z",timeshift:"Z",title:"UTC"},ME={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},yE={name:"BST",timeshift:"+01",title:"British Summer Time"},wE={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},bE={name:"CET",timeshift:"+01",title:"Central European Time"},xE={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},SE={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},EE={name:"BJT",timeshift:"+08",title:"Beijing Time"},AE={name:"CST",timeshift:"-06",title:"Central Standard Time"},_E={name:"JST",timeshift:"+09",title:"Japan Standard Time"},TE={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},RE={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},IE={name:"LST",timeshift:"?",title:"Local Sideral Time"},Nv=[mE,TE,pE,EE,yE,AE,uE,bE,wE,cE,lE,fE,dE,hE,ME,SE,_E,IE,sE,xE,rE,oE,RE,nE,iE,aE,gE,vE];class T0{static instance=new T0;renderComponent(t,e){return t[e].toString()}renderSecond(t){return this.renderComponent(t,"second")+(t.millisecond?"."+t.millisecond.toString():"")}render(t){const e=[];t.year&&e.push(this.renderComponent(t,"year")),t.month&&e.push(this.renderComponent(t,"month")),t.day&&e.push(this.renderComponent(t,"day"));const i=[];t.hour&&i.push(this.renderComponent(t,"hour")),t.minute&&i.push(this.renderComponent(t,"minute")),t.second&&i.push(this.renderSecond(t));const n=e.join("-"),s=t.timeshift?t.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class Wo extends Is{constructor(t="method is abstract"){super(t)}}class E1{units;constructor(t){this.units=t}newYear(t){throw new Wo}newMonth(t){throw new Wo}newDay(t){throw new Wo}newHour(t){throw new Wo}newMinute(t){throw new Wo}newSecond(t){throw new Wo}}class DE extends S1{millisecond=new pi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new pi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new pi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new pi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new pi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new pi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new pi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const td=new DE;class R0{static instance=new R0;render(t){const e=gr.toSpec(t);let i="P";const n=e.years;n&&(i+=n.toString()+"Y");const s=e.months;s&&(i+=s.toString(Xr.instance)+"MM");const r=e.days;r&&(i+=r.toString(Xr.instance)+"D");const a=e.hours;a&&(i+=a.toString(Xr.instance)+"H");const c=e.minutes;c&&(i+=c.toString(Xr.instance)+"M");const h=e.seconds;return h&&(i+=h.toString(Xr.instance)+"S"),i}}class gr extends Yn{constructor(t={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof t=="number"?t:+(t.years?t.years*re.year.duration:0)+(t.months?t.months*re.month.duration:0)+(t.days?t.days*re.day.duration:0)+(t.hours?t.hours*re.hour.duration:0)+(t.minutes?t.minutes*re.minute.duration:0)+(t.seconds?t.seconds*re.second.duration:0)},new pi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(t,e=OE){let i=typeof t=="number"?t:t.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/re.year.duration,a=Math.floor(r);a>0&&(s.years=e.newYear(n*a),i-=a*re.year.duration);const c=i/re.month.duration,h=Math.floor(c);h>0&&(s.months=e.newMonth(n*h),i-=h*re.month.duration);const l=i/re.day.duration,u=Math.floor(l);u>0&&(s.days=e.newDay(n*u),i-=u*re.day.duration);const d=i/re.hour.duration,f=Math.floor(d);f>0&&(s.hours=e.newHour(n*f),i-=f*re.hour.duration);const p=i/re.minute.duration,m=Math.floor(p);m>0&&(s.minutes=e.newMinute(n*m),i-=m*re.minute.duration);const g=i/re.second.duration,v=Math.floor(n*g);return v>0&&(s.seconds=e.newSecond(v)),s}static fromString(t,e=Ot.get(gr)){return new gr(e.parse(t))}static between(t,e){const i=e.getTime(),n=t.getTime();return new gr(i-n)}toSpec(){return gr.toSpec(this)}toString(t=R0.instance){return t.render(this)}}class sb extends E1{constructor(t){super(t)}newYear(t){return new $h(t,this.units.year)}newMonth(t){return new Yh(t,this.units.month)}newDay(t){return new Kh(t,this.units.day)}newHour(t){return new qh(t,this.units.hour)}newMinute(t){return new Zh(t,this.units.minute)}newSecond(t){return new Jh(t,this.units.second)}newMillisecond(t){return new Oo(t,this.units.millisecond)}newTimeshift(t){return new Ro(typeof t=="number"?t:t.value)}}const CE=new sb(re),OE=new sb(td);class En{#t;#e;#i;#n;#s;#r;#a;#o;constructor(t={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:En.timeshiftOf(new Date)}){this.year=t.year,this.month=t.month,this.day=t.day,this.hour=t.hour,this.minute=t.minute,this.second=t.second,this.millisecond=t.millisecond,this.timeshift=t.timeshift}get year(){return this.#t}set year(t){const e=typeof t=="number";this.#t&&e?this.#t.value=t:this.#t=e?this.factory.newYear(t):!t||t.start||t instanceof Yn?t:this.factory.newYear(t)}get month(){return this.#e}set month(t){const e=typeof t=="number";this.#e&&e?this.#e.value=t:this.#e=e?this.factory.newMonth(t):!t||t.start||t instanceof Yn?t:this.factory.newMonth(t)}get day(){return this.#i}set day(t){const e=typeof t=="number";this.#i&&e?this.#i.value=t:this.#i=e?this.factory.newDay(t):!t||t.start||t instanceof Yn?t:this.factory.newDay(t)}get hour(){return this.#n}set hour(t){const e=typeof t=="number";this.#n&&e?this.#n.value=t:this.#n=e?this.factory.newHour(t):!t||t.start||t instanceof Yn?t:this.factory.newHour(t)}get minute(){return this.#s}set minute(t){const e=typeof t=="number";this.#s&&e?this.#s.value=t:this.#s=e?this.factory.newMinute(t):!t||t.start||t instanceof Yn?t:this.factory.newMinute(t)}get second(){return this.#r}set second(t){const e=typeof t=="number";this.#r&&e?this.#r.value=t:this.#r=e?this.factory.newSecond(t):!t||t.start||t instanceof Yn?t:this.factory.newSecond(t)}get millisecond(){return this.#a}set millisecond(t){const e=typeof t=="number";this.#a&&e?this.#a.value=t:this.#a=e||t&&!(t instanceof Yn)?this.factory.newMillisecond(t):t}get timeshift(){return this.#o}set timeshift(t){const e=typeof t=="number";this.#o&&e?this.#o.value=t:this.#o=e||t&&!(t instanceof Ro)?this.factory.newTimeshift(t):t}get factory(){return CE}static fromString(t,e=Ot.get(En)){const{year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:h,timeshift:l}=e.parse(t);return new En({year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:h,timeshift:l})}static timeshiftOf(t){return-t.getTimezoneOffset()||0}static fromDate(t){return new En({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:En.timeshiftOf(t)})}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return En.fromString(i)}#c(t){if(this.constructor.name!==t.constructor.name)throw new _0(`Date "${this.toString()}" cannot be compared with "${t.toString()}"`)}compare(t){return this.#c(t),this.getTime()-t.getTime()}delta(t){const e=this.compare(t);return new gr(e)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}clone(){return new En(this.toSpec())}previous(){let t=this.clone();try{t.second=this.second.previous()}catch{try{t.minute=this.minute.previous()}catch{try{t.hour=this.hour.previous()}catch{try{t.day=this.day.previous()}catch{try{t.month=this.month.previous()}catch{t.year=this.year.previous()}}}}}return t}next(){let t=this.clone();try{t.second=this.second.next()}catch{try{t.minute=this.minute.next()}catch{try{t.hour=this.hour.next()}catch{try{t.day=this.day.next()}catch{try{t.month=this.month.next()}catch{t.year=this.year.next()}}}}}return t}toString(t=T0.instance){return t.render(this)}toSpec(){const t={},e=this.year?.toSpec();e&&(t.year=e);const i=this.month?.toSpec();i&&(t.month=i);const n=this.day?.toSpec();n&&(t.day=n);const s=this.hour?.toSpec();s&&(t.hour=s);const r=this.minute?.toSpec();r&&(t.minute=r);const a=this.second?.toSpec();a&&(t.second=a);const c=this.millisecond?.toSpec();c&&(t.millisecond=c);const h=this.timeshift?.toSpec();return h&&(t.timeshift=h),t}toJSON(){return this.toSpec()}}class A1{static instance=new A1;render(t){return(t.start?t.start.toString():"")+"/"+(t.end?t.end.toString():"")}}class Mu{constructor(t,e){this.start=t,this.end=e}_start;get start(){return this._start}set start(t){if(typeof t=="string"&&(t=En.fromString(t)),t&&!(t instanceof En)&&!(t instanceof gr))throw new Is("Interval start is not a level 0 date or duration: "+t);this._start=t}_end;get end(){return this._end}set end(t){if(typeof t=="string"&&(t=En.fromString(t)),t&&!(t instanceof En)&&!(t instanceof gr))throw new Is("Interval end is not a level 0 date or duration: "+t);this._end=t}static fromString(t,e=Ot.get(Mu)){const{start:i,end:n}=e.parse(t);return new Mu(i,n)}toString(t=A1.instance){return t.render(this)}[Symbol.iterator](){let t=this.start;return{next:()=>{const e={done:t>this.end,value:t};return t++,e}}}}class ed extends Xr{static instance=new ed(aa.default);constructor(t){super(),this.valueRenderer=t}render(t){return(this.valueRenderer?this.valueRenderer.render(t):super.render(t))+this.qualifier(t)}qualifier(t){return t.uncertain?t.approximate?"%":"?":t.approximate?"~":""}}class na extends Yn{#t;#e;constructor(t,e){super(t,e),this.#t=t.uncertain||!1,this.#e=t.approximate||!1}get uncertain(){return this.#t}set uncertain(t){return this.#t=t}get approximate(){return this.#e}set approximate(t){return this.#e=t}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(t){return this.isCertainAndPrecise()&&super.isEqual(t)}isBefore(t){return this.isCertainAndPrecise()&&super.isBefore(t)}isAfter(t){return this.isCertainAndPrecise()&&super.isAfter(t)}toString(t=ed.instance){return super.toString(t)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class rb extends ib{year=new pi("year",-9999,9999,this.month);yearExtended=new pi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const wf=new rb;class fo extends na{constructor(t,e=wf.year){super(t,e)}static fromString(t,e=wf.year,i=Ot.get(fo)){const n=i.parse(t),s=n.value.start;if(t.startsWith("Y")&&(e=wf.yearExtended),s!==void 0){const r=new fo(Object.assign({...n},{value:Math.max(s,e.min)})),a=new fo(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new fo(n,e)}}class ab extends _0{monthValidator=new nb;validate(t){switch(t){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(t)}}}class po extends na{constructor(t,e=new pi(re.month.name,1,24,re.day,new ab)){super(t,e)}static fromString(t,e=Ot.get(po)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=re.month;const r=new po(Object.assign({...i},{value:Math.max(n,s.min)})),a=new po(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new po(i)}toString(t){return super.toString(t).padStart(2,"0")}}class mo extends na{constructor(t,e=re.day){super(t,e)}static fromString(t,e=Ot.get(mo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=re.day;const r=new mo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new mo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new mo(i)}toString(t){return super.toString(t).padStart(2,"0")}}class go extends na{constructor(t,e=re.hour){super(t,e)}static fromString(t,e=Ot.get(go)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=re.hour;const r=new go(Object.assign({...i},{value:Math.max(n,s.min)})),a=new go(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new go(i)}}class vo extends na{constructor(t,e=re.minute){super(t,e)}static fromString(t,e=Ot.get(vo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=re.minute,r=new vo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new vo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new vo(i)}toString(t=ed.instance){return super.toString(t)}}class Mo extends na{constructor(t,e=re.second){super(t,e)}static fromString(t,e=Ot.get(Mo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=re.second,r=new Mo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Mo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Mo(i)}}class gc extends Ro{static fromString(t,e=Ot.get(gc),i=void 0){return new gc(e.parse(t,i))}}class ob extends E1{constructor(t){super(t)}newYear(t){return new fo(t,this.units.year)}newMonth(t){return new po(t,this.units.month)}newDay(t){return new mo(t,this.units.day)}newHour(t){return new go(t,this.units.hour)}newMinute(t){return new vo(t,this.units.minute)}newSecond(t){return new Mo(t,this.units.second)}newMillisecond(t){return new Oo(t,this.units.millisecond)}newTimeshift(t){return new gc(typeof t=="number"?t:t.value)}}const PE=new ob(wf),NE=new ob(td);class Ss extends En{constructor(t){super(t)}get factory(){return PE}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(t){return new Ss({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:En.timeshiftOf(t)})}static fromString(t,e=Ot.get(Ss)){const i=e.parse(t);return new Ss(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Ss.fromString(i)}clone(){return new Ss(this.toSpec())}}const fn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class I0 extends R0{static instance=new I0;render(t){return super.render(t)}}class hn extends na{constructor(t){super(typeof t=="number"||t.hasOwnProperty("value")?t:{value:hn.getValue(t,fn.year)+hn.getValue(t,fn.month)+hn.getValue(t,fn.day)+hn.getValue(t,fn.hour)+hn.getValue(t,fn.minute)+hn.getValue(t,fn.second),uncertain:hn.getBoolean(t,fn.uncertain),approximate:hn.getBoolean(t,"approximate")},td.millisecond)}static getBoolean(t,e){return t[e]||t[fn.year+"s"]?.[e]||t[fn.month+"s"]?.[e]||t[fn.day+"s"]?.[e]||t[fn.hour+"s"]?.[e]||t[fn.minute+"s"]?.[e]||t[fn.second+"s"]?.[e]||!1}static getValue(t,e){let i=0,n=t[e+"s"];if(n instanceof na?n=n.value:typeof t=="number"&&(n=t),n){const s=re[e];i=n*s.duration}return i}static toSpec(t,e=NE){return{...gr.toSpec(t,e),uncertain:t.uncertain||!1,approximate:t.approximate||!1}}static fromString(t,e=Ot.get(hn)){const i=e.parse(t);return new hn(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new hn(i-n)}toString(t=I0.instance){return super.toString(t)}toSpec(){return hn.toSpec(this)}}class yu extends Mu{constructor(t,e){super(t,e)}get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=Ss.fromString(t)),t&&!(t instanceof Ss)&&!(t instanceof hn))throw new Is("Interval start is not a level 1 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Ss.fromString(t)),t&&!(t instanceof Ss)&&!(t instanceof hn))throw new Is("Interval end is not a level 1 date or duration: "+t);this._end=t}static fromString(t,e=Ot.get(yu)){const{start:i,end:n}=e.parse(t);return new yu(i,n)}}class hl extends na{uncertainComponent;approximateComponent;constructor(t,e){super(t,e),this.uncertainComponent=t.uncertainComponent||!1,this.approximateComponent=t.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(t){return super.uncertain=t}get approximate(){return super.approximate||this.approximateComponent}set approximate(t){return super.approximate=t}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class LE extends rb{year=new pi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Gm=new LE;class Sa extends hl{constructor(t,e=Gm.year){super(t,e)}static fromString(t,e=Gm.year,i=Ot.get(Sa)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Sa(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Sa(Object.assign({...n},{value:Math.min(n.value.end,e.max)})),c={start:r,end:a},h=n.value.estimate;return h&&(c.estimate=h),c}else return new Sa(n)}}class kE extends ab{validate(t){switch(t){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(t)}}}class Ea extends hl{constructor(t,e=new pi(re.month.name,1,41,re.day,new kE)){super(t,e)}static fromString(t,e=Ot.get(Ea)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=re.month,r=new Ea(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ea(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ea(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Aa extends hl{constructor(t,e=re.day){super(t,e)}static fromString(t,e=Ot.get(Aa)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=re.day,r=new Aa(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Aa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Aa(i)}toString(t){return super.toString(t).padStart(2,"0")}}class _a extends hl{constructor(t,e=re.hour){super(t,e)}static fromString(t,e=Ot.get(_a)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=re.hour,r=new _a(Object.assign({...i},{value:Math.max(n,s.min)})),a=new _a(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new _a(i)}}class Ta extends hl{constructor(t,e=re.minute){super(t,e)}static fromString(t,e=Ot.get(Ta)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=re.minute,r=new Ta(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ta(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ta(i)}}class Ra extends hl{constructor(t,e=re.second){super(t,e)}static fromString(t,e=re.second,i=Ot.get(Ra)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Ra(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Ra(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new Ra(n,e)}}class cb extends gc{}class UE extends ed{qualifier(){return""}}class to extends T0{static instance=new to;static valueRenderer=new UE(aa.default);static names=["year","month","day","hour","minute","second"];static qualifier(t,e){return t?e?"%":"?":e?"~":""}renderComponent(t,e){const i=t[e],n=to.names.slice(to.names.indexOf(e)+1).map(a=>t[a]).filter(Boolean),s=to.qualifier(i.uncertainComponent,i.approximateComponent),r=to.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(to.valueRenderer)+r}}class hb extends E1{constructor(t){super(t)}newYear(t){return new Sa(t,this.units.year)}newMonth(t){return new Ea(t,this.units.month)}newDay(t){return new Aa(t,this.units.day)}newHour(t){return new _a(t,this.units.hour)}newMinute(t){return new Ta(t,this.units.minute)}newSecond(t){return new Ra(t,this.units.second)}newMillisecond(t){return new Oo(t,this.units.millisecond)}newTimeshift(t){return new cb(typeof t=="number"?t:t.value)}}const FE=new hb(Gm),zE=new hb(td);class hs extends Ss{constructor(t){super(t)}toString(t=to.instance){return super.toString(t)}get year(){return super.year}set year(t){super.year=t}get month(){return super.month}set month(t){super.month=t}get factory(){return FE}static fromDate(t){return new hs({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:En.timeshiftOf(t)})}static fromString(t,e=Ot.get(hs)){const i=e.parse(t);return new hs(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return hs.fromString(i)}clone(){return new hs(this.toSpec())}}class ka{regExp;constructor(t,e){this.name=t,this.regExp=new RegExp(`^(?:${e})$`)}regexGroups(t){const e=this.regExp.exec(t);if(!e)throw new Is(`Invalid ${this.name} "${t}"`);return e.groups}parseGroups(t){throw new Wo(`${this.constructor.name} is abstract`)}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}class lh extends I0{static instance=new lh;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(t,e){return t?e?"%":"?":e?"~":""}render(t){const e=lh.qualifier(t.uncertainDuration,t.approximateDuration);if(!t.hasQualifiedComponent)return e+super.render(t);let i=e+"P";for(const[n,s]of lh.designators){const r=t.components[n];r&&(i+=lh.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+s)}return i}}class cn extends hn{#t;constructor(t){if(super(typeof t=="number"?t:{value:cn.valueFromSpec(t),uncertain:t.uncertain===!0,approximate:t.approximate===!0},td.millisecond),typeof t!="number"){const e={};for(const i of cn.componentNames)t[i]instanceof na&&(e[i]=t[i]);Object.keys(e).length>0&&(this.#t=e)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#t}#e(t){return this.#t?Object.values(this.#t).some(e=>e[t]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#e("uncertain")}set uncertain(t){super.uncertain=t}get approximate(){return super.approximate||this.#e("approximate")}set approximate(t){super.approximate=t}get hasQualifiedComponent(){return this.#t?Object.values(this.#t).some(t=>t.uncertainComponent||t.approximateComponent):!1}static valueFromSpec(t){return cn.getValue(t,fn.year)+cn.getValue(t,fn.month)+cn.getValue(t,fn.day)+cn.getValue(t,fn.hour)+cn.getValue(t,fn.minute)+cn.getValue(t,fn.second)}static toSpec(t,e=zE){const i=hn.toSpec(t,e);if(t instanceof cn&&t.hasQualifiedComponent)for(const n of cn.componentNames)delete i[n],t.components[n]&&(i[n]=t.components[n]);return i}static fromString(t,e=Ot.get(cn)){const i=e.parse(t);return new cn(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new cn(i-n)}toSpec(){return cn.toSpec(this)}toString(t=lh.instance){return super.toString(t)}}class wu extends yu{get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=hs.fromString(t)),t&&!(t instanceof hs)&&!(t instanceof cn))throw new Is("Interval start is not a level 2 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=hs.fromString(t)),t&&!(t instanceof hs)&&!(t instanceof cn))throw new Is("Interval end is not a level 2 date or duration: "+t);this._end=t}static fromString(t,e=Ot.get(wu)){const{start:i,end:n}=e.parse(t);return new wu(i,n)}}class Uf extends Set{constructor(t,e){super(t),this.exclusive=e}has(t){const e=t.toString().replace("..","/");for(const i of this)if(i.toString()===e)return!0;return!1}static fromString(t,e=Ot.get(Uf)){const{exclusive:i,values:n}=e.parse(t);return new Uf(n,i)}}class Ua extends ka{constructor(t,e){super(t,e)}static read(t){return{value:t?parseInt(t,10):void 0}}parseGroups(t){return Ua.read(t[this.name])}parse(t){if(t.startsWith("-"))throw new Is(`${this.name} cannot be negative`);return super.parse(t)}}class k{static groupName(...t){return t.reduce((e,i)=>e?e+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(t,...e){return`(?<${t}>${e.join("")})`}static optional(t){return t+"?"}static nonCapturingGroup(...t){return`(?:${t.join("")})`}static optionalGroup(t,...e){return k.optional(k.group(t,...e))}static optionalNonCapturingGroup(...t){return k.optional(k.nonCapturingGroup(...t))}static numberGroup(t,e,i,n="\\d"){return k.group(t,`${i||""}[${n}]${e}`)}}const Lv="yearValue";class bu extends Ua{static format(t=""){return k.numberGroup(k.groupName(t,Lv),"{4}",void 0)}constructor(){super(Lv,bu.format())}}const kv="monthValue";class xu extends Ua{static format(t=""){return k.numberGroup(k.groupName(t,kv),"{1,2}",void 0)}constructor(){super(kv,xu.format())}}const Uv="dayValue";class Rh extends Ua{static format(t=""){return k.numberGroup(k.groupName(t,Uv),"{1,2}",void 0)}constructor(){super(Uv,Rh.format())}}const Fv="hourValue";class Ih extends Ua{static format(t=""){return k.numberGroup(k.groupName(t,Fv),"{1,2}",void 0)}constructor(){super(Fv,Ih.format())}}const zv="minuteValue";class Su extends Ua{static format(t=""){return k.numberGroup(k.groupName(t,zv),"{1,2}",void 0)}constructor(){super(zv,Su.format())}}const Bv="secondValue";class Eu extends Ua{static format(t=""){return k.numberGroup(k.groupName(t,Bv),"{1,2}",void 0)}constructor(){super(Bv,Eu.format())}}const Hv="timeshiftValue",Gv="shiftHour",Vv="shiftMinute";class jh extends ka{static format(t=""){return Nv.map(e=>e.name).join("|")+"|"+k.nonCapturingGroup(k.group(t+Gv,k.numberGroup(k.groupName(t,Hv),"{2}","[+-]")),k.optionalNonCapturingGroup(":?",k.numberGroup(k.groupName(t,Vv),"{2}",void 0)))}constructor(){super(Hv,jh.format())}parse(t,e){let i=0;const n=Nv.find(s=>s.name===t);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(e??{})}catch(s){throw new Is(`The time zone ${t} depends on the date: ${s.message}`)}t=n.timeshift}if(t!=="Z"){const s=this.regexGroups(t),r=s[Gv];r&&(i+=parseInt(r,10)*60);const a=s[Vv];a&&(i+=parseInt(a,10))}return i}}const Wv="year",Xv="month",$v="day",Yv="hour",Kv="minute",qv="second",Zv="millisecond",Jv="timeshift";class Zo extends ka{static format(t=""){return k.group(k.groupName(t,Wv),bu.format(t))+k.optionalNonCapturingGroup("-",k.group(k.groupName(t,Xv),xu.format(t)),k.optionalNonCapturingGroup("-",k.group(k.groupName(t,$v),Rh.format(t)),k.optionalNonCapturingGroup("[T ]",k.group(k.groupName(t,Yv),Ih.format(t)),":?",k.group(k.groupName(t,Kv),Su.format(t)),k.optionalNonCapturingGroup(":",k.group(k.groupName(t,qv),Eu.format(t)),k.optionalNonCapturingGroup("[.,]",k.group(k.groupName(t,Zv),"\\d+"))),"\\s*",k.optionalGroup(k.groupName(t,Jv),jh.format(t)))))}constructor(){super("date",Zo.format())}parse(t){const e=this.regexGroups(t),i=e[Wv],n=e[Xv],s=e[$v],r=e[Yv],a=e[Kv],c=e[qv],h=e[Zv],l=e[Jv],u=i?new $h(bu.read(i)):void 0,d=n?xu.read(n):void 0;return{year:u,month:d?new Yh(d,hh.create(d.value,u?.value)):void 0,day:s?new Kh(Rh.read(s)):void 0,hour:r?new qh(Ih.read(r)):void 0,minute:a?new Zh(Su.read(a)):void 0,second:c?new Jh(Eu.read(c)):void 0,millisecond:h?Oo.parseFraction(h):void 0,timeshift:l?Ro.fromString(l,new jh,{year:u?.value,month:d?.value,day:s?Rh.read(s).value:void 0,hour:r?Ih.read(r).value:void 0}):void 0}}}const jv="years",j0="months",BE="days",Qv="hours",tM="minutes",eM="seconds";class _1 extends ka{static format(t=""){return"P"+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,jv),"+",void 0,"\\d"),"Y")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,j0),"+",void 0,"\\d"),"MM")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,BE),"+",void 0,"\\d"),"D")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,Qv),"+",void 0,"\\d"),"H")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,tM),"+",void 0,"\\d"),"M")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,eM),"+",void 0,"\\d"),"S")}constructor(){super("duration",_1.format())}parseGroups(t){return{years:t[jv],months:t[j0],days:t[j0],hours:t[Qv],minutes:t[tM],seconds:t[eM]}}}const Q0="start",tp="end";class T1 extends ka{static format=k.group(Q0,Zo.format(Q0))+"/"+k.group(tp,Zo.format(tp));constructor(){super("interval",T1.format)}parse(t){const e=this.regexGroups(t),i=e[Q0],n=e[tp];return{start:i?En.fromString(i,new Zo):void 0,end:n?En.fromString(n,new Zo):void 0}}}class Ai extends Ua{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Ai.uncertainGroup+Ai.approximateGroup;constructor(t,e){super(t,e)}static qualifierFormat(t,e){return k.optionalGroup(t,`\\${e}`)}static formatSuffix(t){return this.qualifierFormat(k.groupName(Ai.uncertainGroup,t),"?")+this.qualifierFormat(k.groupName(Ai.approximateGroup,t),"~")+this.qualifierFormat(k.groupName(Ai.uncertainAndApproximateGroup,t),"%")}static numberFormat(t,e,i){return k.numberGroup(t,e,i,"\\dX")+this.formatSuffix(t)}getValueAndSign(t){let e=t[this.name],i;return e.charAt(0)==="-"?(i=-1,e=e.substring(1)):i=1,{valueStr:e,sign:i}}parseGroups(t){const{valueStr:e,sign:i}=this.getValueAndSign(t);let n=0,s;for(s=0;s<e.length;s++){const h=e[s];if(h==="X")break;n=n*10+parseInt(h,10)}if(s<e.length){let h=1;for(let d=0;d<e.length-s;d++)h*=10;const l=i*n*h,u=l+h-1;n={start:l,end:u}}else n*=i;const r=t[k.groupName(Ai.uncertainAndApproximateGroup,this.name)],a=t[k.groupName(Ai.approximateGroup,this.name)]||r,c=t[k.groupName(Ai.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:c?!!c:!1}}}const iM="yearValue";class Au extends Ai{constructor(){super(iM,Au.format())}static format(t=""){return"Y?"+Ai.numberFormat(k.groupName(t,iM),"+","[-]?")}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const nM="monthValue";class _u extends Ai{static format(t=""){return Ai.numberFormat(k.groupName(t,nM),"{1,2}",void 0)}constructor(){super(nM,_u.format())}}const sM="dayValue";class Tu extends Ai{static format(t=""){return Ai.numberFormat(k.groupName(t,sM),"{1,2}",void 0)}constructor(){super(sM,Tu.format())}}const rM="hourValue";class Ru extends Ai{static format(t=""){return Ai.numberFormat(k.groupName(t,rM),"{1,2}",void 0)}constructor(){super(rM,Ru.format())}}const aM="minuteValue";class Iu extends Ai{static format(t=""){return Ai.numberFormat(k.groupName(t,aM),"{1,2}",void 0)}constructor(){super(aM,Iu.format())}}const oM="secondValue";class Du extends Ai{static format(t=""){return Ai.numberFormat(k.groupName(t,oM),"{1,2}",void 0)}constructor(){super(oM,Du.format())}}class Cu extends jh{}class Oi extends ka{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(t=Oi.format()){super("date",t)}static format(t=""){return k.group(k.groupName(t,Oi.yearGroup),Au.format(t))+k.optionalNonCapturingGroup("-",k.group(k.groupName(t,Oi.monthGroup),_u.format(t)),k.optionalNonCapturingGroup("-",k.group(k.groupName(t,Oi.dayGroup),Tu.format(t)),k.optionalNonCapturingGroup("[T ]",k.group(k.groupName(t,Oi.hourGroup),Ru.format(t)),":",k.group(k.groupName(t,Oi.minuteGroup),Iu.format(t)),k.optionalNonCapturingGroup(":",k.group(k.groupName(t,Oi.secondGroup),Du.format(t)),k.optionalNonCapturingGroup("[.,]",k.group(k.groupName(t,Oi.millisecondGroup),"\\d+"))),k.optionalGroup(k.groupName(t,Oi.timeshiftGroup),Cu.format(t)))))}parseGroups(t){const e=t[Oi.millisecondGroup],i=e?Oo.parseFraction(e):void 0,n=t[Oi.secondGroup],s=n?Mo.fromString(n,new Du):void 0,r=t[Oi.minuteGroup];let a;r&&(a=vo.fromString(r,new Iu),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[Oi.hourGroup];let h;c&&(h=go.fromString(c,new Ru),h.uncertain=h.uncertain||a?.uncertain||!1,h.approximate=h.approximate||a?.approximate||!1);const l=t[Oi.dayGroup];let u;l&&(u=mo.fromString(l,new Tu),u.uncertain=u.uncertain||h?.uncertain||!1,u.approximate=u.approximate||h?.approximate||!1);const d=t[Oi.monthGroup];let f;d&&(f=po.fromString(d,new _u),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[Oi.yearGroup];let m;p&&(m=fo.fromString(p,void 0,new Au),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[Oi.timeshiftGroup],v=g?gc.fromString(g,new Cu,{year:m?.value,month:f?.value,day:u?.value,hour:h?.value}):void 0;return{year:m,month:f,day:u,hour:h,minute:a,second:s,millisecond:i,timeshift:v}}}const cM="years",hM="months",lM="days",uM="hours",dM="minutes",fM="seconds";class Jo extends Ai{static format(t=""){return"P"+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,cM),"+",void 0,"\\d"),"Y")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,hM),"+",void 0,"\\d"),"MM")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,lM),"+",void 0,"\\d"),"D")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,uM),"+",void 0,"\\d"),"H")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,dM),"+",void 0,"\\d"),"M")+k.optionalNonCapturingGroup(k.numberGroup(k.groupName(t,fM),"+",void 0,"\\d"),"S")+this.formatSuffix(t)}constructor(){super("duration",Jo.format())}parseGroups(t){return{years:t[cM],months:t[hM],days:t[lM],hours:t[uM],minutes:t[dM],seconds:t[fM],uncertain:!!t[Ai.uncertainGroup],approximate:!!t[Ai.approximateGroup]}}}const HE="dates",ep="start",ip="end",pM="durations",np="durationMin",sp="durationMax";class R1 extends ka{static format=k.group(HE,k.optionalGroup(ep,k.group("openStart","\\.\\.")+"|"+Oi.format(ep))+"/"+k.optionalGroup(ip,k.group("openEnd","\\.\\.")+"|"+Oi.format(ip)))+"|"+k.group(pM,k.group(np,Jo.format(np))+"/"+k.group(sp,Jo.format(sp)));constructor(t="interval",e=R1.format){super(t,e)}parseGroups(t){let e,i;if(t[pM]){const s=t[np];e=hn.fromString(s,new Jo);const r=t[sp];i=hn.fromString(r,new Jo)}else{const s=t[ep];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=Ss.fromString(s,new Oi)}const r=t[ip];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Ss.fromString(r,new Oi)}}return{start:e,end:i}}}class We extends Ai{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=We.uncertainGroup+We.approximateGroup;constructor(t,e){super(t,e)}static numberFormat(t,e,i){return this.qualifierFormat(k.groupName(We.uncertainGroup,t),"?")+this.qualifierFormat(k.groupName(We.approximateGroup,t),"~")+this.qualifierFormat(k.groupName(We.uncertainAndApproximateGroup,t),"%")+Ai.numberFormat(t,e,i)}parseGroups(t){const e=super.parseGroups(t),i=t[k.groupName(We.uncertainAndApproximateGroup,this.name)];return(t[k.groupName(We.uncertainGroup,this.name)]||i)&&(e.uncertainComponent=!0),(t[k.groupName(We.approximateGroup,this.name)]||i)&&(e.approximateComponent=!0),e}}const ml="yearValue",mM="exp",gM="signif";class Ou extends We{constructor(){super(ml,Ou.format())}static format(t=""){return"Y?"+k.nonCapturingGroup(k.group(k.groupName(t,mM),"[-]?\\d+E\\d+")+"|"+We.numberFormat(k.groupName(t,ml),"+","[-]?")+k.optionalGroup(k.groupName(t,gM),"S\\d+"))}parseGroups(t){const e=t[mM];if(e){const r=e.indexOf("E"),a=parseInt(e.substring(r+1),10),h=parseInt(e.substring(0,r),10)*Math.pow(10,a);t[ml]=h.toString()}const i=t[gM],n=t[ml];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:c}=this.getValueAndSign(t);let h="";for(let l=0;l<a.length;l++)h+=l<r?a.charAt(l):"X";t[ml]=(c<0?"-":"")+h}const s=super.parseGroups(t);return i&&(s.value.estimate=parseInt(n,10)),s}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const vM="monthValue";class Pu extends We{static format(t=""){return We.numberFormat(k.groupName(t,vM),"{1,2}",void 0)}constructor(){super(vM,Pu.format())}}const MM="dayValue";class Nu extends We{static format(t=""){return We.numberFormat(k.groupName(t,MM),"{1,2}",void 0)}constructor(){super(MM,Nu.format())}}const yM="hourValue";class Lu extends We{static format(t=""){return We.numberFormat(k.groupName(t,yM),"{1,2}",void 0)}constructor(){super(yM,Lu.format())}}const wM="secondValue";class ku extends We{static format(t=""){return We.numberFormat(k.groupName(t,wM),"{1,2}",void 0)}constructor(){super(wM,ku.format())}}const bM="minuteValue";class Uu extends We{static format(t=""){return We.numberFormat(k.groupName(t,bM),"{1,2}",void 0)}constructor(){super(bM,Uu.format())}}class GE extends Cu{}class Ye extends ka{static yearGroup=Oi.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",Ye.format())}static format(t=""){return k.group(k.groupName(t,Ye.yearGroup),Ou.format(t))+k.optionalNonCapturingGroup("-",k.group(k.groupName(t,Ye.monthGroup),Pu.format(t)),k.optionalNonCapturingGroup("-",k.group(k.groupName(t,Ye.dayGroup),Nu.format(t)),k.optionalNonCapturingGroup("[T ]",k.group(k.groupName(t,Ye.hourGroup),Lu.format(t)),":",k.group(k.groupName(t,Ye.minuteGroup),Uu.format(t)),k.optionalNonCapturingGroup(":",k.group(k.groupName(t,Ye.secondGroup),ku.format(t)),k.optionalNonCapturingGroup("[.,]",k.group(k.groupName(t,Ye.millisecondGroup),"\\d+"))),k.optionalGroup(k.groupName(t,Ye.timeshiftGroup),GE.format(t)))))}parseGroups(t){const e=t[Ye.millisecondGroup],i=e?Oo.parseFraction(e):void 0,n=t[Ye.secondGroup];let s;n&&(s=Ra.fromString(n,void 0,new ku),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=t[Ye.minuteGroup];let a;r&&(a=Ta.fromString(r,new Uu),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[Ye.hourGroup];let h;c&&(h=_a.fromString(c,new Lu),h.uncertain=h.uncertain||a?.uncertain||!1,h.approximate=h.approximate||a?.approximate||!1);const l=t[Ye.dayGroup];let u;l&&(u=Aa.fromString(l,new Nu),u.uncertain=u.uncertain||h?.uncertain||!1,u.approximate=u.approximate||h?.approximate||!1);const d=t[Ye.monthGroup];let f;d&&(f=Ea.fromString(d,new Pu),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[Ye.yearGroup];let m;p&&(m=Sa.fromString(p,void 0,new Ou),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[Ye.timeshiftGroup],v=g?cb.fromString(g,new Cu,{year:m?.value,month:f?.value,day:u?.value,hour:h?.value}):void 0;return{year:m,month:f,day:u,hour:h,minute:a,second:s,millisecond:i,timeshift:v}}}const xM="durationValue";class I1 extends We{static format(t=""){return"^"+We.numberFormat(k.groupName(t,xM),"+",void 0)}constructor(){super(xM,I1.format())}}class VE extends S1{millisecond=new pi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new pi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new pi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new pi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new pi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new pi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new pi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const Ic=new VE;class Qt extends We{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new I1;static componentFormat(t,e,i,n,s=""){const r=k.group(k.groupName(t,Qt.quantityGroup(e)),We.numberFormat(k.groupName(t,i),"+",void 0,"\\d"));return k.group(k.groupName(t,e),r,n,s)}static quantityGroup(t){return t+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",Qt.format())}static format(t=""){const e=k.groupName(t,Qt.durationGroup);return this.qualifierFormat(k.groupName(We.uncertainGroup,e),"?")+this.qualifierFormat(k.groupName(We.approximateGroup,e),"~")+this.qualifierFormat(k.groupName(We.uncertainAndApproximateGroup,e),"%")+"P"+k.optional(Qt.componentFormat(t,Qt.yearsGroup,Ye.yearGroup,"Y"))+k.optionalNonCapturingGroup(Qt.componentFormat(t,Qt.monthsGroup,Ye.monthGroup,"MM")+"|"+Qt.componentFormat(t,Qt.isoMonthsGroup,"isoMonth","M",Qt.isoMonthsLookahead))+k.optional(Qt.componentFormat(t,Qt.daysGroup,Ye.dayGroup,"D"))+"T?"+k.optional(Qt.componentFormat(t,Qt.hoursGroup,Ye.hourGroup,"H"))+k.optional(Qt.componentFormat(t,Qt.minutesGroup,Ye.minuteGroup,"M"))+k.optional(Qt.componentFormat(t,Qt.secondsGroup,Ye.secondGroup,"S"))+k.optionalGroup(k.groupName(t,Qt.suffixGroup),"[?~%]")}static parseComponent(t,e,i){const n=Qt.componentParser.parse(t);return new e(n,i)}parseGroups(t){const e=t[Qt.quantityGroup(Qt.secondsGroup)];let i;e&&(i=Qt.parseComponent(e,Ra,Ic.second),i.uncertain=!!t[k.groupName(We.uncertainGroup,Qt.secondsGroup)]||!1,i.approximate=!!t[k.groupName(We.approximateGroup,Qt.secondsGroup)]||!1);const n=t[Qt.quantityGroup(Qt.minutesGroup)];let s;n&&(s=Qt.parseComponent(n,Ta,Ic.minute),s.uncertain=s.uncertain||i?.uncertain||!1,s.approximate=s.approximate||i?.approximate||!1);const r=t[Qt.quantityGroup(Qt.hoursGroup)];let a;r&&(a=Qt.parseComponent(r,_a,Ic.hour),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[Qt.quantityGroup(Qt.daysGroup)];let h;c&&(h=Qt.parseComponent(c,Aa,Ic.day),h.uncertain=h.uncertain||a?.uncertain||!1,h.approximate=h.approximate||a?.approximate||!1);const l=t[Qt.quantityGroup(Qt.monthsGroup)]||t[Qt.quantityGroup(Qt.isoMonthsGroup)];let u;l&&(u=Qt.parseComponent(l,Ea,Ic.month),u.uncertain=u.uncertain||h?.uncertain||!1,u.approximate=u.approximate||h?.approximate||!1);const d=t[Qt.quantityGroup(Qt.yearsGroup)];let f;d&&(f=Qt.parseComponent(d,Sa,Ic.year),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[Qt.suffixGroup],m=!!t[k.groupName(We.uncertainAndApproximateGroup,Qt.durationGroup)]||p==="%",g=m||!!t[k.groupName(We.uncertainGroup,Qt.durationGroup)]||p==="?",v=m||!!t[k.groupName(We.approximateGroup,Qt.durationGroup)]||p==="~";return{years:f,months:u,days:h,hours:a,minutes:s,seconds:i,uncertain:g,approximate:v}}}const WE="dates",rp="start",ap="end",SM="durations",op="durationMin",cp="durationMax";class D0 extends ka{static format=k.group(WE,k.optionalGroup(rp,k.group("openStart","\\.\\.")+"|"+Ye.format(rp))+"/"+k.optionalGroup(ap,k.group("openEnd","\\.\\.")+"|"+Ye.format(ap)))+"|"+k.group(SM,k.group(op,Qt.format(op))+"/"+k.group(cp,Qt.format(cp)));constructor(t="interval",e=D0.format){super(t,e)}parseGroups(t){let e,i;if(t[SM]){const s=t[op];e=cn.fromString(s,new Qt);const r=t[cp];i=cn.fromString(r,new Qt)}else{const s=t[rp];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=hs.fromString(s,new Ye)}const r=t[ap];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=hs.fromString(r,new Ye)}}return{start:e,end:i}}}class XE{parse(t){t=t.trim();const e=t.startsWith("["),n=t.substring(1,t.length-1).split(","),s=[];for(const r of n){let a;r.includes("..")?a=wu.fromString(r.replace("..","/"),new D0):a=hs.fromString(r,new Ye),s.push(a)}return{values:s,exclusive:e}}}const lb=["spring","summer","autumn","winter"],Vm=21,$E=32,YE=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let KE;function qE(){return KE??=new Ye}function Dc(o){return typeof o?.value=="number"?o.value:void 0}function Dh(o){const t=o.trim();if(/^\d{1,2}:/.test(t)){const r=YE.exec(t)?.groups;return r?{year:void 0,month:void 0,day:void 0,hour:Number(r.hour),minute:Number(r.minute),second:r.second?Number(r.second):void 0,raw:t}:void 0}let e;try{e=hs.fromString(t,qE())}catch{return}const i=Dc(e.year),n=Dc(e.month),s=n!==void 0&&n>=Vm&&n<=$E;if(!(e.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(e.day||e.hour)))return{year:i,month:s?void 0:n,...s?{season:lb[(n-Vm)%4]}:{},day:Dc(e.day),hour:Dc(e.hour),minute:Dc(e.minute),second:Dc(e.second),raw:t}}function jo(o){if(o.raw!==void 0)return o.raw;if(o.year===void 0){if(o.hour===void 0)return"";let e=`${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`;return o.second!==void 0&&(e+=`:${String(o.second).padStart(2,"0")}`),e}let t=String(o.year).padStart(4,"0");return o.season!==void 0?`${t}-${Vm+lb.indexOf(o.season)}`:(o.month===void 0||(t+=`-${String(o.month).padStart(2,"0")}`,o.day===void 0)||(t+=`-${String(o.day).padStart(2,"0")}`,o.hour===void 0)||(t+=`T${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`,o.second!==void 0&&(t+=`:${String(o.second).padStart(2,"0")}`)),t)}function Wm(o){if(o.year!==void 0)return Date.UTC(o.year,(o.month??1)-1,o.day??1,o.hour??0,o.minute??0,o.second??0)}function EM(o){return(((o.day??0)*24+(o.hour??0))*60+(o.minute??0))*6e4+(o.second??0)*1e3}const ZE=["year","month","day","hour","minute"],JE=["day","hour","minute"];function AM(o,t){return t.filter(e=>o[e]!==void 0).join(",")}function ub(o){if(o.durationSeconds!==void 0)return o.durationSeconds*1e3;const t=o.durationText===void 0?void 0:Th.parse(o.durationText);if(t)return t.chosenSeconds*1e3;if(!o.time||!o.endTime)return;const e=o.time.year!==void 0&&o.endTime.year!==void 0,i=e?ZE:JE,n=AM(o.time,i);if(!(n===""||n!==AM(o.endTime,i)))return e?Wm(o.endTime)-Wm(o.time):EM(o.endTime)-EM(o.time)}class C0{constructor(t,e,i,n,s,r,a,c,h=[],l,u,d,f=[],p=[],m=[],g=[]){this.event=t,this.timeline=e,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=c,this.decor=h,this.weatherSource=l,this.instrumentId=u,this.exposureSeconds=d,this.milestones=f,this.references=p,this.roads=m,this.traces=g}provenance=os.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;frozen;sway;lightPollution;observerMap;iso;metering;lens;vehicle;events;eventsExpansion;sampleMs;get observerCount(){return 1+this.decor.filter(t=>t.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return ki.byId(this.instrumentId)}static create(t,e,i){return new C0({eventType:"sighting",time:t,place:e},new Qu,new mu,new gu,new vu,i)}}const jE=0,QE=0;function Le(o,t){const e=o.observerTrack.getInterpolatedPoseAt(t);if(e)return e;const i=o.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:jE,headingDeg:void 0,pitchDeg:QE,fovDeg:ki.fieldOfViewDeg(o.instrument)}}function rh(o,t){return o.weatherTrack.getInterpolatedWeatherAt(t)??o.weather??A0}function gl(o,t){return o.weatherTrack.getActualWeatherAt(t)??o.weather??A0}function db(o,t){return o.soundTrack.getInterpolatedSoundAt(t)??jS}class Wi{static toCurrent(t){const e=t.version,i=typeof e=="object"&&e!==null&&"value"in e?e.value:e;if(i!==void 0&&i!==1&&i!==2)return t;const n=i===2?t:Wi.fromVersion1(t);return Wi.fromVersion2(n)}static observerIdOf(t){return t.observer?.id??"observer"}static fromVersion2(t){const e={...t,version:3},i={...t.timeline??{keyframes:[]}},n=new Set,s=i.keyframes??[];for(const l of s)for(const u of l.shapes??[])n.add(u.sourceId);const r=[],a=l=>{let u=l;for(let d=r.length+1;u===void 0||n.has(u);d++)u=`group-${d}`;return n.add(u),u},c=Array.isArray(i.groups)?i.groups:[];for(const l of c)Array.isArray(l)?r.push({id:a(),members:[...l]}):typeof l=="object"&&l!==null&&r.push(l);const h=Array.isArray(t.events)?t.events.map(l=>({...l})):void 0;if(h){const l=Wi.observerIdOf(t),u=h.filter(v=>v.who==="phenomenon"),d=new Set(n);for(const v of u){const M=Wi.unwrapped(v.params?.parts);if(v.eventType==="appearance"&&Array.isArray(M))for(const w of M)w.sourceId&&d.add(w.sourceId)}for(const v of d)n.add(v);const f=v=>r.find(M=>M.members.includes(v)),p=v=>{const M=f(v);return M?p(M.id):v},m=[...new Set([...d].map(p))],g=m.length===1?m[0]:m.length>1?a("phenomenon"):"phenomenon";m.length>1&&r.push({id:g,members:m});for(const v of h)if(v.who===void 0||v.who==="observer")v.who=l;else if(v.who==="phenomenon"){v.who=g;const M=v.params;if(v.eventType!=="blink"||!M||!Array.isArray(M.parts))continue;const w=M.parts,{parts:y,...b}=M;v.params=b,v.who=Wi.groupFor(w,r,a)??g}e.events=h}return(r.length>0||c.length>0)&&(e.timeline={...i,groups:r}),e}static groupFor(t,e,i){if(t.length===1)return t[0];const n=h=>{const l=e.find(u=>u.id===h);return l?l.members.flatMap(n):[h]},s=e.find(h=>{const l=n(h.id);return l.length===t.length&&t.every(u=>l.includes(u))});if(s)return s.id;const r=new Set(t.map(h=>e.find(l=>l.members.includes(h))));if(r.size!==1)return;const[a]=r,c=i();if(a){const h=a.members.findIndex(l=>t.includes(l));a.members=a.members.filter(l=>!t.includes(l)),a.members.splice(h,0,c)}return e.push({id:c,members:[...t]}),c}static unwrapped(t){return Wi.isWrapped(t)?t.value:t}static fromVersion1(t){const e={...t,version:2};for(const i of["time","endTime"])t[i]!==void 0&&(e[i]=Wi.edtf(t[i]));if(Array.isArray(t.place)){const i=Wi.place(t.place);i===void 0?delete e.place:e.place=i}return e}static edtf(t){if(Wi.isWrapped(t)){const h=Wi.edtf(t.value);return h===void 0?void 0:{...t,value:h}}if(typeof t=="string")return t;const e=t,i=Object.values(e).find(h=>Wi.isWrapped(h)),n=Object.fromEntries(Object.entries(e).map(([h,l])=>[h,Wi.isWrapped(l)?l.value:l])),s=jo(n);if(s==="")return;if(!i)return s;const{basis:r,rationale:a,how:c}=i;return{value:s,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...c===void 0?{}:{how:c}}}static place(t){if(t.length===0)return;const e=t.map(h=>Wi.isWrapped(h)?h.value:h),i=e.find(h=>h.name)?.name,n={...i?{name:i}:{},locations:e.map(({lat:h,lng:l})=>({lat:h,lng:l}))},s=t.find(h=>Wi.isWrapped(h));if(!s)return n;const{basis:r,rationale:a,how:c}=s;return{value:n,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...c===void 0?{}:{how:c}}}static isWrapped(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}}class fb{static sync(t,e,i,n,s){if(t.querySelector(".param-description")?.remove(),e===void 0){t.removeAttribute("data-describing");return}const r=document.createElement("div");r.className="param-description";const a=document.createElement("div");a.className="param-description-head";const c=document.createElement("span");c.className="param-nest-label",c.textContent=i;const h=document.createElement("button");h.type="button",h.className="param-description-close",h.textContent="×",h.title=n,h.setAttribute("aria-label",n),h.addEventListener("click",s),a.append(c,h);const l=document.createElement("p");l.className="param-description-text",l.textContent=e,r.append(a,l),r.addEventListener("keydown",u=>{u.key==="Escape"&&s()}),t.setAttribute("data-describing",""),t.append(r),h.focus({preventScroll:!0})}static CSS=`
3
3
  .param-summary[data-describing] > :not(.param-description) {
4
4
  display: none;
@@ -664,7 +664,7 @@ ${fb.CSS}
664
664
  margin: 0.4em 0 0;
665
665
  padding-left: 1.2em;
666
666
  }
667
- `;class Xm{static NAMES=["weather","place","lightPollution","decor"];static KEYS={weather:["weatherTrack","weatherSource"],place:["place"],lightPollution:["lightPollution"],decor:["decor"]};static annexName(t,e){return`${t}.${e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}.json`}static fromFile(t,e){return t?.[e]!==void 0&&t[e].live!==!0}}class Ch{static NAMES=["relief","imagery","roads","water","railways","upperAir","map"];static TERRAIN=["relief","imagery","roads","water","railways"];static held(t,e){if(!t||t.live)return;const i=t[e];return i&&!i.live&&!i.refresh&&i.src!==void 0?i:void 0}static isLive(t,e){return t?.live===!0||t?.[e]?.live===!0}static annexName(t,e){const i=e==="relief"||e==="imagery"||e==="map"?"zip":"json",n=e.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);return`${t}.${n}.${i}`}static isEmpty(t){return!t||!t.live&&Ch.NAMES.every(e=>!t[e])&&Xm.NAMES.every(e=>!t[e])}}class Cc extends Error{constructor(t,e,i){super(`${t}: ${e}${i===void 0?"":` (HTTP ${i})`}`),this.kind=t,this.url=e,this.status=i,this.name="SightingFetchError"}}class Eo{static async recording(t){const e=await Eo.json(t);for(const i of Xm.NAMES){const n=e?.frozen?.[i];if(!(!n?.src||n.live))try{const s=Wi.toCurrent(await Eo.json(new URL(n.src,new URL(t,location.href)).href));for(const r of Xm.KEYS[i])s[r]!==void 0&&(e[r]=s[r])}catch{}}return e}static async json(t){const e=new URL(t,location.href);if(location.protocol==="https:"&&e.protocol==="http:")throw new Cc("mixed-content",t);let i;try{i=await fetch(t)}catch{throw await this.diagnose(t,e)}if(!i.ok)throw new Cc("status",t,i.status);try{return await i.json()}catch{throw new Cc("malformed",t)}}static async diagnose(t,e){if(e.origin===location.origin)return new Cc("unreachable",t);try{return await fetch(t,{mode:"no-cors"}),new Cc("cors",t)}catch{return new Cc("unreachable",t)}}}class iA extends Error{constructor(t,e,i){super(typeof e=="number"&&Number.isInteger(e)&&e>i?`This ${t} file is in version ${e} of its format; this UFO@home reads up to version ${i}. Read it with a newer UFO@home.`:`This ${t} file states ${JSON.stringify(e)} as its format version, which is not a version.`),this.format=t,this.found=e,this.supported=i,this.name="FormatVersionError"}said(t){return t.replace("{found}",typeof this.found=="number"?String(this.found):JSON.stringify(this.found)).replace("{supported}",String(this.supported))}}class Qo{static CURRENT={sighting:3,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(t,e=Qo.CURRENT[t]){return`${Qo.SCHEMA_BASE}/${e}/${t}.schema.json`}static of(t){if(typeof t!="object"||t===null)return 1;const e=t.version;return e===void 0?1:typeof e=="object"&&e!==null&&"value"in e?e.value:e}static check(t,e){const i=Qo.of(t),n=Qo.CURRENT[e];if(typeof i!="number"||!Number.isInteger(i)||i<1||i>n)throw new iA(e,i,n);return t}}class mn{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static INTERVIEW_EVENT="interview";static check(t){return Qo.check(t,"case")}static isCase(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Array.isArray(t.events)&&!("timeline"in t)}static sightingUrls(t,e){return(t.events??[]).filter(i=>i.eventType===mn.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,e).href)}static accountIds(t,e,i,n){const s=(t.events??[]).filter(r=>r.eventType===mn.SIGHTING_EVENT&&r.id!==void 0&&typeof r.url=="string"&&i!==void 0&&new URL(r.url,e).href===i).map(r=>r.id);return n!==void 0&&s.push(n),s}static interpretationEvents(t,e){const i=[e].flat().filter(n=>!!n);return i.length===0?[]:(t.events??[]).filter(n=>n.eventType===mn.INTERPRETATION_EVENT?n.sighting!==void 0&&i.includes(n.sighting):n.eventType!==mn.SIGHTING_EVENT||n.interpretationOf===void 0?!1:[n.interpretationOf].flat().some(s=>i.includes(s))).map(n=>n)}static problems(t,e){const i=t.events??[],n=new Set,s=new Set;for(const a of i)a.id!==void 0&&(n.has(a.id)&&s.add(a.id),n.add(a.id));const r=[];for(const a of i){const c=a.eventType===mn.SIGHTING_EVENT?a.interpretationOf:a.eventType===mn.INTERVIEW_EVENT?a.interviewOf:void 0;if(c!==void 0)for(const h of[c].flat())!n.has(h)&&!e.includes(h)&&r.push({reading:a.url??a.id??"",reference:h})}return{duplicateIds:[...s],unresolved:r}}static async interpretationOf(t,e,i){if(t.bodies)return mn.withModelsFrom(os.strip({title:t.title,bodies:t.bodies??[],smoke:t.smoke,flares:t.flares,lanterns:t.lanterns}).recording,e);if(!t.url)return{title:t.title,bodies:[]};const n=new URL(t.url,e).href,s=await i(n),r="timeline"in s&&s.interpretation?s.interpretation:s;return mn.withModelsFrom(os.strip({title:t.title??r.title,bodies:r.bodies??[],smoke:r.smoke,flares:r.flares,lanterns:r.lanterns}).recording,n)}static withModelsFrom(t,e){return{...t,bodies:t.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,e).href}}:i)}}}class Ps{constructor(t,e,i,n="en"){this.parts=t,this.messages=e,this.onChange=i,this.locale=n,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="";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:i}=this.parts;e.value=t?jo(t):"",i.type!=="date"&&(i.step=Ps.stepFor(t)),i.value=i.type==="date"?Ps.pickerDateOf(t):Ps.pickerValueOf(t),e.setCustomValidity(""),e.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...t){return t.every(e=>e===void 0||Ps.isPickable(e)&&Ps.qualifierOf(jo(e))==="")}static opensPreciseDate(...t){return t.every(e=>e===void 0||Ps.isFullDate(e)&&Ps.qualifierOf(jo(e))==="")}static isFullDate(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0}static pickerDateOf(t){if(!Ps.isFullDate(t))return"";const e=(i,n=2)=>String(i).padStart(n,"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(!Ps.isPickable(t))return"";const e=(n,s=2)=>String(n).padStart(s,"0"),i=t.second?`:${e(t.second)}`:"";return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}T${e(t.hour)}:${e(t.minute)}${i}`}static stepFor(t){return t?.second?"1":"60"}static qualifierOf(t){const e=/[?%]/.test(t),i=/[~%]/.test(t);return e&&i?"%":e?"?":i?"~":""}describe(t){return Ps.describeTime(t,this.messages,this.locale)}static describeTime(t,e,i){const n=jo(t),s=Ps.qualifierOf(n),r=l=>String(l).padStart(2,"0"),a=[];if(t.season!==void 0){const l={spring:e.timeSeasonSpring,summer:e.timeSeasonSummer,autumn:e.timeSeasonAutumn,winter:e.timeSeasonWinter}[t.season];a.push(t.year!==void 0?`${l} ${t.year}`:l)}else if(t.year!==void 0){const l=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"},u=new Date(Date.UTC(t.year,(t.month??1)-1,t.day??1));a.push(new Intl.DateTimeFormat(i,{...l,timeZone:"UTC"}).format(u))}t.hour!==void 0&&a.push(`${r(t.hour)}:${r(t.minute??0)}${t.second!==void 0?`:${r(t.second)}`:""}`);const c=a.join(", "),h=s==="~"?e.timeQualifierApproximate:s==="?"?e.timeQualifierUncertain:s==="%"?e.timeQualifierBoth:"";return h?`${c} — ${h.toLowerCase()}`:c}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 i=Dh(e);t.title=i?`→ ${this.describe(i)}`:this.messages.edtfInvalid}readText(){const t=this.parts.text.value.trim();if(t===""){this.clean(),this.onChange(void 0);return}const e=Dh(t);e&&(this.clean(),this.onChange(e))}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===""||Dh(e)||(t.setCustomValidity(this.messages.edtfInvalid),t.classList.add("invalid"))}}class Zr{static read(t,e){let i=t;for(const n of e.split(".")){if(i=Zr.bare(i),i===null||typeof i!="object")return;i=i[n]}return Zr.bare(i)}static write(t,e,i){const n=e.split("."),s=[];let r=t;for(let c=0;c<n.length-1;c++){let h=Zr.bare(r[n[c]]);if(h===null||typeof h!="object"||Array.isArray(h)){if(i===void 0)return;h={}}r[n[c]]=h,s.push({owner:r,part:n[c]}),r=h}const a=n[n.length-1];i===void 0?delete r[a]:r[a]=i;for(let c=s.length-1;c>=0;c--){const h=s[c].owner[s[c].part];if(Object.keys(h).length>0)break;delete s[c].owner[s[c].part]}}static stated(t,e){return Zr.read(t,e)!==void 0}static bare(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&"value"in t&&"basis"in t?t.value:t}}class vc{static MODES=["off","position","dipped","main","fog"];static DISPLAY_GAIN=.006;static TOE_IN_DEG=.6;static AUTO_BELOW_SUN_DEG=-1;static BEAMS={off:void 0,position:void 0,dipped:{candela:25e3,halfAngleDeg:24,pitchDeg:2.5,penumbra:1,color:"#fff2d8"},main:{candela:12e4,halfAngleDeg:14,pitchDeg:.4,penumbra:.85,color:"#fff6e6"},fog:{candela:9e3,halfAngleDeg:38,pitchDeg:5,penumbra:1,color:"#ffe9b0"}};static isMode(t){return typeof t=="string"&&vc.MODES.includes(t)}static at(t,e,i){if(!e||e.length===0)return t;let n=e[0];for(const s of e){if(s.t>i)break;n=s}return n.mode}static auto(t){return t<vc.AUTO_BELOW_SUN_DEG?"dipped":"off"}static lamps(t){return t!=="off"}}function nA(o){return o==="vehicle"?["front","behind","front-left","front-right","behind-left","behind-right"]:["front","behind","left","right"]}const sA=90,Ff=2;function pb(o){return o==="building"||o==="vehicle"}function rA(o,t){return o==="building"?!0:o==="vehicle"?t!=="front"&&t!=="behind":!1}function Qh(o){return o==="building"||o==="vehicle"}const mb={aircraft:{id:"poly-google-airliner"},tree:{id:"jungle-jim-tree-large-a"},observer:{id:"makehuman-farmer-40s"},entity:{id:"makehuman-farmer-40s"}},aA=["makehuman-farmer-40s","makehuman-man-overalls","makehuman-man-jacket","makehuman-old-man","makehuman-woman"];function _M(o,t){let e=0;for(const i of t)e=e*31+i.charCodeAt(0)>>>0;return{id:o[e%o.length]}}const oA=["jungle-jim-tree-large-a","jungle-jim-tree-medium-a","jungle-jim-tree-large-b","jungle-jim-tree-medium-b","jungle-jim-tree-large-c","jungle-jim-tree-medium-c","jagobo-tree-maple-a","jagobo-tree-maple-b","jagobo-tree-aspen-a","jagobo-tree-aspen-b","nicholas-3d-tree-a","nicholas-3d-tree-b","nicholas-3d-tree-c"];function zf(o){return o.model?o.model:o.kind==="tree"&&o.id!==void 0?_M(oA,o.id):(o.kind==="observer"||o.kind==="entity")&&o.id!==void 0?_M(aA,o.id):mb[o.kind]}function gb(o,t){const e=vc.at(o.headlights,o.headlightKeyframes,t);return e!==void 0?e:O0(o,t)?"dipped":"off"}const cA=-.5;function hA(o){return o.kind==="streetlight"&&o.origin!==void 0&&o.lit===void 0&&!o.litKeyframes?.length}function O0(o,t,e){if(e!==void 0&&hA(o))return e<cA;const i=o.litKeyframes;if(!i||i.length===0)return o.lit??!1;let n=i[0];for(const s of i){if(s.t>t)break;n=s}return n.lit}function TM(o,t){const e=o.observerKeyframes;if(!e||e.length===0)return{side:o.observerSide,facing:o.observerFacing};let i=e[0];for(const n of e){if(n.t>t)break;i=n}return{side:i.side,facing:i.facing}}function lA(o,t){const e=Oh(o,t);return e.intensity<=0?!1:e.pattern.kind==="steady"?!0:vb(o,t,t+1)>.5}function Oh(o,t){let e;for(const i of o.keyframes??[]){if(i.t>t)break;e=i}return{intensity:e?.intensity??o.intensity??1,pattern:e?.pattern??o.pattern}}function vb(o,t,e){const i=o.keyframes??[];if(i.length===0)return hp(o.pattern,t,e);const n=[t,...i.map(r=>r.t).filter(r=>r>t&&r<e),e];if(e<=t)return Oh(o,t).intensity>0?hp(Oh(o,t).pattern,t,e):0;let s=0;for(let r=0;r<n.length-1;r++){const a=Oh(o,n[r]);a.intensity>0&&(s+=hp(a.pattern,n[r],n[r+1])*(n[r+1]-n[r]))}return s/(e-t)}function hp(o,t,e){if(o.kind==="steady")return 1;const{perMinute:i,dutyCycle:n,phase:s=0}=o,r=Math.min(Math.max(n,0),1);if(r===0||i<=0)return 0;const a=6e4/i,c=t/a+s,h=e/a+s;if(h<=c)return Math.min(Math.max(c-Math.floor(c),0),r)<r?1:0;const l=u=>Math.floor(u)*r+Math.min(u-Math.floor(u),r);return(l(h)-l(c))/(h-c)}function vr(o,t){const e=o.track,i={eastM:o.eastM,northM:o.northM,altitudeM:0,headingDeg:o.headingDeg};if(!e||e.length===0)return i;if(e.length===1||t<=e[0].t)return RM(e[0],o);const n=e[e.length-1];if(t>=n.t)return RM(n,o);for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1];if(t<r.t||t>a.t)continue;const c=a.t-r.t,h=c===0?0:(t-r.t)/c;return{eastM:r.eastM+(a.eastM-r.eastM)*h,northM:r.northM+(a.northM-r.northM)*h,altitudeM:(r.altitudeM??0)+((a.altitudeM??0)-(r.altitudeM??0))*h,headingDeg:r.headingDeg??o.headingDeg}}return i}function uA(o,t){const e=(o.track??[]).filter(i=>i.gazeAzimuthDeg!==void 0);if(e.length!==0){if(t<=e[0].t)return e[0].gazeAzimuthDeg;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t>s.t)continue;const r=s.t-n.t,a=r===0?0:(t-n.t)/r,c=((s.gazeAzimuthDeg-n.gazeAzimuthDeg)%360+540)%360-180;return((n.gazeAzimuthDeg+c*a)%360+360)%360}return e[e.length-1].gazeAzimuthDeg}}function RM(o,t){return{eastM:o.eastM,northM:o.northM,altitudeM:o.altitudeM??0,headingDeg:o.headingDeg??t.headingDeg}}const IM="#ff2200",DM="#00ff44",ko="#ffffff",hd="#ffa500",Oc="#ff0000",dA="#2244ff",$m=[{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:IM,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:DM,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:ko,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:Oc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:Oc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:ko,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:ko,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:IM,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:DM,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:ko,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:Oc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:ko,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:ko,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:ko,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:Oc,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:Oc,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:hd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:hd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:hd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:hd,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:dA,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:Oc,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>ge.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>ge.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 Bf{static forKind(t){return $m.filter(e=>e.kinds.includes(t))}static byId(t){return $m.find(e=>e.id===t)}}class ge{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*ge.CYCLE_S/2,i=ge.VEHICLE_HEAD_Y_M,n=ge.LENS_SPACING_M;return[ge.lamp("red",ge.RED,i+n,e+ge.GREEN_S+ge.AMBER_S,ge.CYCLE_S-ge.GREEN_S-ge.AMBER_S,ge.VEHICLE_INTENSITY),ge.lamp("amber",ge.AMBER,i,e+ge.GREEN_S,ge.AMBER_S,ge.VEHICLE_INTENSITY),ge.lamp("green",ge.GREEN,i-n,e,ge.GREEN_S,ge.VEHICLE_INTENSITY)]}static pedestrianLights(t){const e=t*ge.CYCLE_S/2+ge.GREEN_S+ge.AMBER_S+ge.PEDESTRIAN_DELAY_S,i=ge.PEDESTRIAN_HEAD_Y_M,n=ge.LENS_SPACING_M/2;return[ge.lamp("ped-red",ge.RED,i+n,e+ge.PEDESTRIAN_GREEN_S,ge.CYCLE_S-ge.PEDESTRIAN_GREEN_S,ge.PEDESTRIAN_INTENSITY),ge.lamp("ped-green",ge.GREEN,i-n,e,ge.PEDESTRIAN_GREEN_S,ge.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,i,n,s,r){const a=ge.CYCLE_S,c=Math.round(((1-n/a)%1+1)%1*1e6)/1e6;return{id:t,color:e,intensity:r,radiusM:ge.LENS_RADIUS_M,beamDeg:ge.BEAM_DEG,offsetM:{x:0,y:i,z:-.13},pattern:{kind:"flash",perMinute:60/a,dutyCycle:Math.round(s/a*1e6)/1e6,...c?{phase:c}:{}}}}}class Kl{static of(t,e){const i=Kl.drawnAsModel(t);return{color:e?.color??!i,lit:e?.lit??Kl.litByDefault(t.kind,i),headlights:t.kind==="vehicle",lights:(e?.lights??!0)&&Kl.rigsFor(t.kind,e).length>0,windows:!i&&pb(t.kind),floors:!i&&t.kind==="building",observerSide:Qh(t.kind)}}static rigsFor(t,e){return Bf.forKind(t).filter(i=>e?.lightRigs===void 0||e.lightRigs.includes(i.id))}static drawnAsModel(t){return zf(t)!==void 0&&!(t.observerSide!==void 0&&Qh(t.kind))}static litByDefault(t,e){return t==="streetlight"||t==="vehicle"&&!e}}class vi{static sideLabel(t){return vi.SIDE_LABELS[t]}static SIDE_LABELS={front:{en:"Front",fr:"Avant",es:"Frente",it:"Fronte"},behind:{en:"Behind",fr:"Arrière",es:"Detrás",it:"Dietro"},left:{en:"Left",fr:"Gauche",es:"Izquierda",it:"Sinistra"},right:{en:"Right",fr:"Droite",es:"Derecha",it:"Destra"},"front-left":{en:"Front-left",fr:"Avant gauche",es:"Delantero izquierdo",it:"Anteriore sinistro"},"front-right":{en:"Front-right",fr:"Avant droit",es:"Delantero derecho",it:"Anteriore destro"},"behind-left":{en:"Behind-left",fr:"Arrière gauche",es:"Trasero izquierdo",it:"Posteriore sinistro"},"behind-right":{en:"Behind-right",fr:"Arrière droit",es:"Trasero derecho",it:"Posteriore destro"}};static WINDOWS={en:"Windows",fr:"Fenêtres",es:"Ventanas",it:"Finestre"};static BUILDING={en:"Building",fr:"Bâtiment",es:"Edificio",it:"Edificio"};static BRIDGE={en:"Bridge",fr:"Pont",es:"Puente",it:"Ponte"};static RAILING={en:"Railing",fr:"Garde-corps",es:"Barandilla",it:"Parapetto"};static WIRE={en:"Overhead line",fr:"Ligne aérienne",es:"Línea aérea",it:"Linea aerea"};static together(t,e){const i=["en","fr","es","it"],n=(s,r)=>typeof s=="string"?s:s[r]??s.en;return Object.fromEntries(i.map(s=>[s,`${n(t,s)} ${n(e,s)}`]))}static of(t,e){const i=[],n=Kl.drawnAsModel(t);if(!n&&t.kind==="building"&&i.push(...vi.floors(),...vi.walls(),...vi.roof()),!n&&pb(t.kind)&&i.push(...vi.windows(t.kind)),t.kind==="vehicle"&&i.push(...vi.engine()),t.kind==="observer"&&i.push(...vi.observerRecording()),t.kind==="aircraft"&&i.push(...vi.aircraftSound(e)),t.kind==="bridge"&&i.push(...vi.bridge()),t.kind==="wire"&&i.push(...vi.wire()),e?.parameters&&i.push(...e.parameters.map(s=>({...s,key:`modelParameters.${s.key}`}))),i.length!==0)return{kind:`decor-${t.kind}`,title:{en:"Properties",fr:"Propriétés",es:"Propiedades",it:"Proprietà"},parameters:i}}static floors(){const t=e=>Zr.read(e,"floors")??Ff;return[{type:"number",key:"floors",min:0,max:20,step:1,effective:()=>Ff,label:{en:"Floors",fr:"Étages",es:"Plantas",it:"Piani"},hint:{en:"Upper stories above the ground floor.",fr:"Étages au-dessus du rez-de-chaussée.",es:"Plantas sobre la planta baja.",it:"Piani sopra il pianterreno."},group:vi.BUILDING},{type:"number",key:"occupiedFloor",min:0,max:20,step:1,effective:()=>0,bounds:e=>({max:t(e)}),label:{en:"Occupied floor",fr:"Étage occupé",es:"Planta ocupada",it:"Piano occupato"},hint:{en:"The floor the observer is on, from 0 (ground floor).",fr:"L'étage où se tient l'observateur, à partir de 0 (rez-de-chaussée).",es:"La planta donde está el observador, desde 0 (planta baja).",it:"Il piano dove si trova l'osservatore, da 0 (pianterreno)."},group:vi.BUILDING}]}static walls(){const t={en:"Walls",fr:"Murs",es:"Muros",it:"Muri"};return[{type:"colour",key:"facade.color",group:t,fallback:"#d3cab8",label:{en:"Wall colour",fr:"Couleur des murs",es:"Color de los muros",it:"Colore dei muri"},hint:{en:"The colour of the walls, drawn with the facade of their kind where the width, the length and the height of the building are all stated. Empty: a pale plaster.",fr:"La couleur des murs, dessinés avec la façade de leur type là où la largeur, la longueur et la hauteur du bâtiment sont toutes énoncées. Vide : un enduit pâle.",es:"El color de los muros, dibujados con la fachada de su tipo donde el ancho, el largo y el alto del edificio están todos enunciados. Vacío: un enlucido pálido.",it:"Il colore dei muri, disegnati con la facciata del loro tipo dove larghezza, lunghezza e altezza dell'edificio sono tutte enunciate. Vuoto: un intonaco chiaro."}},{type:"choice",key:"facade.openings",group:t,label:{en:"Facade",fr:"Type de façade",es:"Tipo de fachada",it:"Tipo di facciata"},empty:{en:"A house's",fr:"D'une maison",es:"De una casa",it:"Di una casa"},hint:{en:"A house's: a window every three metres of every floor and a door, from a storey high (lower, a shed's bare wall). The tall windows of an old building, the tall narrow bays of a church, a bare wall (a warehouse, a shed, a monument), or none: the plain box.",fr:"D'une maison : une fenêtre tous les trois mètres de chaque étage et une porte, dès la hauteur d'un étage (plus bas, le mur nu d'un abri). Les hautes fenêtres d'un immeuble ancien, les hautes baies étroites d'une église, un mur nu (un entrepôt, un hangar, un monument), ou aucune : la simple boîte.",es:"De una casa: una ventana cada tres metros de cada planta y una puerta, desde la altura de una planta (más bajo, el muro liso de un cobertizo). Las ventanas altas de un edificio antiguo, los vanos altos y estrechos de una iglesia, un muro liso (un almacén, un cobertizo, un monumento), o ninguna: la caja lisa.",it:"Di una casa: una finestra ogni tre metri di ogni piano e una porta, dall'altezza di un piano (più basso, il muro liscio di un capanno). Le finestre alte di un edificio antico, le alte aperture strette di una chiesa, un muro liscio (un magazzino, un capannone, un monumento), o nessuna: la semplice scatola."},choices:[{value:"tall",label:{en:"Old building",fr:"Immeuble ancien",es:"Edificio antiguo",it:"Edificio antico"}},{value:"lancet",label:{en:"Church",fr:"Église",es:"Iglesia",it:"Chiesa"}},{value:"plain",label:{en:"Bare wall",fr:"Mur nu",es:"Muro liso",it:"Muro liscio"}},{value:"none",label:{en:"None",fr:"Aucune",es:"Ninguna",it:"Nessuna"}}]}]}static roof(){const t={en:"Roof",fr:"Toit",es:"Tejado",it:"Tetto"};return[{type:"choice",key:"roof.shape",group:t,label:{en:"Roof",fr:"Toit",es:"Tejado",it:"Tetto"},empty:{en:"Flat",fr:"Plat",es:"Plano",it:"Piano"},hint:{en:"Flat (the box), two slopes to a ridge, four slopes, or a dome.",fr:"Plat (la boîte), deux pentes jusqu'à un faîte, quatre pentes, ou une coupole.",es:"Plano (la caja), dos vertientes hasta una cumbrera, cuatro vertientes, o una cúpula.",it:"Piano (la scatola), due falde fino a un colmo, quattro falde, o una cupola."},choices:[{value:"flat",label:{en:"Flat",fr:"Plat",es:"Plano",it:"Piano"}},{value:"gable",label:{en:"Two slopes",fr:"Deux pentes",es:"Dos vertientes",it:"Due falde"}},{value:"hip",label:{en:"Four slopes",fr:"Quatre pentes",es:"Cuatro vertientes",it:"Quattro falde"}},{value:"dome",label:{en:"Dome",fr:"Coupole",es:"Cúpula",it:"Cupola"}}]},{type:"number",key:"roof.riseM",min:0,max:15,step:.1,unit:"m",group:t,effective:()=>3,label:{en:"Rise",fr:"Hauteur du toit",es:"Altura del tejado",it:"Altezza del tetto"},hint:{en:"How far the ridge stands above the eaves: the walls are the building's height less this.",fr:"De combien le faîte dépasse l'égout : les murs font la hauteur du bâtiment moins cela.",es:"Cuánto sube la cumbrera sobre el alero: los muros miden la altura del edificio menos esto.",it:"Quanto il colmo sta sopra la gronda: i muri sono l'altezza dell'edificio meno questo."},visibleWhen:i=>["gable","hip","dome"].includes(String(Zr.read(i,"roof.shape")))},{type:"choice",key:"roof.ridge",group:t,required:!1,label:{en:"Ridge along",fr:"Faîte le long de",es:"Cumbrera a lo largo de",it:"Colmo lungo"},empty:{en:"The width",fr:"La largeur",es:"El ancho",it:"La larghezza"},choices:[{value:"width",label:{en:"The width",fr:"La largeur",es:"El ancho",it:"La larghezza"}},{value:"depth",label:{en:"The depth",fr:"La profondeur",es:"El largo",it:"La profondità"}}],visibleWhen:i=>Zr.read(i,"roof.shape")==="gable"},{type:"colour",key:"roof.color",group:t,fallback:"#7a5a4a",label:{en:"Roof colour",fr:"Couleur du toit",es:"Color del tejado",it:"Colore del tetto"}}]}static windows(t){return nA(t).map(e=>({type:"number",key:`windows.${e}`,step:5,unit:"%",min:rA(t,e)?0:sA,max:100,label:vi.SIDE_LABELS[e],summary:vi.together(vi.WINDOWS,vi.SIDE_LABELS[e]),hint:{en:"Opacity of the window on this side: 0 is open, 100 shut. Empty: no window.",fr:"Opacité de la fenêtre de ce côté : 0 ouverte, 100 fermée. Vide : pas de fenêtre.",es:"Opacidad de la ventana de este lado: 0 abierta, 100 cerrada. Vacío: sin ventana.",it:"Opacità della finestra di questo lato: 0 aperta, 100 chiusa. Vuoto: nessuna finestra."},group:vi.WINDOWS}))}static engine(){const t={en:"Engine sound",fr:"Bruit du moteur",es:"Sonido del motor",it:"Suono del motore"};return[{type:"choice",key:"engine.kind",group:t,label:{en:"Engine",fr:"Moteur",es:"Motor",it:"Motore"},hint:{en:"Whether the vehicle is heard running, and what sort of engine: how many cylinders fire, how low they turn, how its gears are spaced.",fr:"Si le véhicule s'entend rouler, et de quel moteur : combien de cylindres tirent, à quel régime bas ils tournent, comment ses vitesses sont étagées.",es:"Si se oye el vehículo en marcha, y qué motor: cuántos cilindros disparan, cuán bajo giran, cómo se escalonan sus marchas.",it:"Se il veicolo si sente in marcia, e di che motore: quanti cilindri sparano, quanto in basso girano, come sono distanziate le marce."},empty:{en:"Silent (parked)",fr:"Silencieux (à l'arrêt)",es:"Silencioso (parado)",it:"Silenzioso (fermo)"},choices:[{value:"car",label:{en:"Car",fr:"Voiture",es:"Coche",it:"Auto"}},{value:"van",label:{en:"Van",fr:"Camionnette",es:"Furgoneta",it:"Furgone"}},{value:"truck",label:{en:"Truck",fr:"Camion",es:"Camión",it:"Camion"}},{value:"motorcycle",label:{en:"Motorcycle",fr:"Moto",es:"Moto",it:"Moto"}},{value:"generic",label:{en:"Unknown",fr:"Inconnu",es:"Desconocido",it:"Sconosciuto"}}]},{type:"number",key:"engine.noise",min:.1,max:3,step:.1,group:t,effective:()=>1,label:{en:"Loudness",fr:"Volume",es:"Volumen",it:"Volume"},hint:{en:"Against an ordinary one of its kind: 1 by default, 1.5 for a very noisy one.",fr:"Par rapport à un véhicule ordinaire de son genre : 1 par défaut, 1,5 pour un très bruyant.",es:"Frente a uno ordinario de su tipo: 1 por defecto, 1,5 para uno muy ruidoso.",it:"Rispetto a uno ordinario del suo tipo: 1 per impostazione predefinita, 1,5 per uno molto rumoroso."},visibleWhen:e=>Zr.read(e,"engine.kind")!==void 0||e.engine!==void 0}]}static observerRecording(){return[{type:"text",key:"sightingUrl",placeholder:"https://…/sighting.json",label:{en:"Their own recording URL",fr:"URL de son propre enregistrement",es:"URL de su propia grabación",it:"URL della sua registrazione"}}]}static aircraftSound(t){const e=(n,s,r,a,c)=>({value:n,label:{en:s,fr:r,es:a,it:c}}),i=t?.sound;return[{type:"choice",key:"aircraftSound",group:{en:"Sound",fr:"Bruit",es:"Sonido",it:"Suono"},label:{en:"Noise in flight",fr:"Bruit en vol",es:"Ruido en vuelo",it:"Rumore in volo"},hint:{en:"What it sounds like while it flies: nothing is heard of a machine that flies silent, and the stand-in of a phenomenon says so.",fr:"Ce qu'on entend quand il vole : rien d'une machine qui vole en silence, et la maquette d'un phénomène le dit.",es:"Cómo suena mientras vuela: nada se oye de una máquina que vuela en silencio, y la maqueta de un fenómeno lo dice.",it:"Come suona mentre vola: nulla si sente di una macchina che vola in silenzio, e il modello di un fenomeno lo dice."},empty:i==="silent"?{en:"Silent (as the model)",fr:"Silencieux (comme le modèle)",es:"Silencioso (como el modelo)",it:"Silenzioso (come il modello)"}:{en:"As the model",fr:"Selon le modèle",es:"Según el modelo",it:"Secondo il modello"},choices:[e("airliner-narrow","Narrow-body airliner","Avion de ligne monocouloir","Avión de pasillo único","Aereo di linea a fusoliera stretta"),e("airliner-wide","Wide-body airliner","Avion de ligne gros-porteur","Avión de fuselaje ancho","Aereo di linea a fusoliera larga"),e("regional-jet","Regional jet","Jet régional","Jet regional","Jet regionale"),e("regional-turboprop","Turboprop","Turbopropulseur","Turbohélice","Turboelica"),e("business-jet","Business jet","Jet d'affaires","Jet privado","Jet privato"),e("light-piston","Light piston aircraft","Avion léger à pistons","Avioneta de pistones","Aereo leggero a pistoni"),e("helicopter-light","Light helicopter","Hélicoptère léger","Helicóptero ligero","Elicottero leggero"),e("helicopter-medium","Medium helicopter","Hélicoptère moyen","Helicóptero medio","Elicottero medio"),e("helicopter-heavy","Heavy helicopter","Hélicoptère lourd","Helicóptero pesado","Elicottero pesante"),e("military-jet","Military jet","Avion de combat","Reactor militar","Jet militare"),e("ultralight","Ultralight","ULM","Ultraligero","Ultraleggero"),e("unmanned","Drone","Drone","Dron","Drone"),e("glider","Glider","Planeur","Planeador","Aliante"),e("silent","Silent","Silencieux","Silencioso","Silenzioso")]}]}static bridge(){const t=(e,i,n,s,r,a,c,h,l)=>({type:"number",key:e,label:i,min:n,max:s,step:r,unit:a,group:h,hint:l,effective:c===void 0?void 0:()=>c});return[t("bridge.spanM",{en:"Span",fr:"Portée",es:"Luz",it:"Luce"},.1,5e3,.1,"m",void 0,vi.BRIDGE,{en:"Metres of open span under the deck, centred. Empty: the whole length, no embankments.",fr:"Mètres de portée libre sous le tablier, centrés. Vide : toute la longueur, sans remblais.",es:"Metros de luz libre bajo el tablero, centrados. Vacío: toda la longitud, sin terraplenes.",it:"Metri di luce libera sotto l'impalcato, centrati. Vuoto: tutta la lunghezza, senza rilevati."}),t("bridge.deckThicknessM",{en:"Deck thickness",fr:"Épaisseur du tablier",es:"Espesor del tablero",it:"Spessore dell'impalcato"},.1,20,.1,"m",1.2,vi.BRIDGE),t("bridge.railing.heightM",{en:"Height",fr:"Hauteur",es:"Altura",it:"Altezza"},.1,5,.05,"m",1.05,vi.RAILING),t("bridge.railing.postSpacingM",{en:"Post spacing",fr:"Espacement des poteaux",es:"Separación de postes",it:"Distanza dei montanti"},.2,20,.1,"m",1.5,vi.RAILING),t("bridge.railing.rails",{en:"Rails",fr:"Lisses",es:"Barandas",it:"Correnti"},0,8,1,"",2,vi.RAILING)]}static wire(){return[{type:"choice",key:"wire.poles",group:vi.WIRE,label:{en:"Poles",fr:"Poteaux",es:"Postes",it:"Pali"},hint:{en:"Which ends stand on a pole: both, the one the heading points away from, the one it points towards, or none (a line anchored on buildings).",fr:"Quelles extrémités reposent sur un poteau : les deux, celle dont le cap s'éloigne, celle vers laquelle il pointe, ou aucune (une ligne ancrée sur des bâtiments).",es:"Qué extremos se apoyan en un poste: ambos, aquel del que se aleja el rumbo, aquel hacia el que apunta, o ninguno (una línea anclada en edificios).",it:"Quali estremità poggiano su un palo: entrambe, quella da cui si allontana la direzione, quella verso cui punta, o nessuna (una linea ancorata a edifici)."},choices:[{value:"both",label:{en:"Both",fr:"Les deux",es:"Ambos",it:"Entrambi"}},{value:"start",label:{en:"Start",fr:"Début",es:"Inicio",it:"Inizio"}},{value:"end",label:{en:"End",fr:"Fin",es:"Fin",it:"Fine"}},{value:"none",label:{en:"None",fr:"Aucun",es:"Ninguno",it:"Nessuno"}}],effective:()=>"both"},{type:"number",key:"wire.diameterM",min:.001,max:.2,step:.001,unit:"m",effective:()=>.008,group:vi.WIRE,label:{en:"Strand thickness",fr:"Épaisseur du brin",es:"Grosor del hilo",it:"Spessore del filo"}},{type:"number",key:"wire.poleHeightM",min:.5,max:100,step:.1,unit:"m",group:vi.WIRE,label:{en:"Pole height",fr:"Hauteur des poteaux",es:"Altura de los postes",it:"Altezza dei pali"},hint:{en:"Empty: half a metre over the highest strand.",fr:"Vide : un demi-mètre au-dessus du brin le plus haut.",es:"Vacío: medio metro sobre el hilo más alto.",it:"Vuoto: mezzo metro sopra il filo più alto."}}]}}class pr{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=[pr.NONE,pr.SOLAR_VISUAL,pr.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return pr.ALL.find(e=>e.id===t)??pr.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class bf{constructor(t){this.names=t}name(t){return this.names[t.toLowerCase()]??t}stored(t){const e=t.trim().toLowerCase();for(const[i,n]of Object.entries(this.names))if(n.toLowerCase()===e)return i;return t.trim()}}class ao{constructor(t,e,i,n=new bf({}),s){this.labels=t,this.naming=e,this.said=i,this.tags=n,this.timeWords=s}entriesFor(t,e,i={}){const n=[];return this.addSummary(n,t),this.addObservation(n,t),this.addObserver(n,t,e),this.addLocation(n,t,e,i.groundElevationM,i.roadGradeDeg??0),this.addDecor(n,t,e,i),i.phenomena===!0&&this.addPhenomena(n,t,e),this.addTemporal(n,t),this.addWeather(n,t,e),this.addSound(n,t,e),n}push(t,e,i,n,s,r="",a={}){s===void 0||s===""||t.push({group:e,field:i,label:n,value:String(s),unit:r,color:a.color,fromSource:a.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 i=this.said.read(e.event.description)?.trim();if(!i)return;const n=i.split(/\s+/),s=n.length>ao.DESCRIPTION_WORDS?`${n.slice(0,ao.DESCRIPTION_WORDS).join(" ")}…`:i;this.push(t,"summary","description",this.labels.summaryDescription,s),t[t.length-1].full=i}addObservation(t,e){const i=e.event.tags;this.push(t,"observation","tags",this.labels.tags,i&&i.length>0?i.map(n=>this.tags.name(n)).join(", "):void 0)}filterName(t){return t===pr.SOLAR_VISUAL?this.labels.filterSolarVisual:t===pr.SOLAR_PHOTO?this.labels.filterSolarPhoto:t.name}addObserver(t,e,i){const n=e.observer;this.push(t,"observer","observerId",this.labels.observerId,n?.id),this.push(t,"observer","observerTitle",this.labels.observerTitle,this.said.read(n?.title)),this.push(t,"observer","observerLastName",this.labels.observerLastName,n?.lastName);const s=n?.firstNames;this.push(t,"observer","observerFirstNames",this.labels.observerFirstNames,s&&s.length>0?s.join(", "):void 0);const r=e.instrument;this.push(t,"observer","instrument",this.labels.instrument,this.naming.instrument(r));const a=e.exposure;this.push(t,"observer","exposureSeconds",this.labels.exposure,a===void 0?void 0:a<1?`1/${Math.round(1/a)}`:this.rounded(a,2),"s");const c=Le(e,i);if(c){const h=ki.focalLengthMmFor(r,c.fovDeg);h===void 0?this.push(t,"observer","focalLength",this.labels.fieldOfView,this.rounded(c.fovDeg,1),"°"):this.push(t,"observer","focalLength",this.labels.focalLength,this.rounded(h,1),"mm"),this.push(t,"observer","fNumber",this.labels.aperture,this.rounded(c.fNumber??r.fNumber,1)),this.push(t,"observer","focusDistance",this.labels.focusDistance,this.rounded(c.focusDistanceM,1),"m"),this.push(t,"observer","roll",this.labels.roll,this.roundedShown(c.rollDeg),"°");const l=pr.byId(c.filter);l!==pr.NONE&&this.push(t,"observer","filter",this.labels.filter,this.filterName(l))}}degreesMinutesSeconds(t,e,i){if(t===void 0||!Number.isFinite(t))return;const n=Math.round(Math.abs(t)*3600),s=Math.floor(n/3600),r=Math.floor(n%3600/60),a=n%60;return`${s}°${String(r).padStart(2,"0")}′${String(a).padStart(2,"0")}″ ${this.naming.point(t<0?i:e)}`}static WALK_KMH=7;static SPEED_SPAN_MS=1e3;static speedKmhAt(t,e){const i=ao.SPEED_SPAN_MS/2,n=Math.max(0,e-i),s=Le(t,n),r=Le(t,n+2*i);if(s?.lat===void 0||s.lng===void 0||r?.lat===void 0||r.lng===void 0)return;const a=(r.lat-s.lat)*111320,c=(r.lng-s.lng)*111320*Math.cos(s.lat*Math.PI/180);return Math.hypot(a,c)/(2*i/1e3)*3.6}addLocation(t,e,i,n,s){const r=e.event.place?.[0];this.push(t,"location","placeName",this.labels.placeName,r?.name);const a=Le(e,i);if(!a)return;this.push(t,"location","lat",this.labels.latitude,this.degreesMinutesSeconds(a.lat,0,180)),this.push(t,"location","lng",this.labels.longitude,this.degreesMinutesSeconds(a.lng,90,270));const c=this.rounded(a.headingDeg);this.push(t,"location","heading",this.labels.heading,c,a.headingDeg===void 0?"°":`° (${this.naming.point(a.headingDeg)})`),this.push(t,"location","pitch",this.labels.pitch,a.pitchDeg===void 0?void 0:this.rounded(a.pitchDeg+s),"°");const h=ao.speedKmhAt(e,i);h!==void 0&&h>ao.WALK_KMH&&this.push(t,"location","speed",this.labels.speed,Math.round(h),"km/h"),n===void 0?this.push(t,"location","elevation",this.labels.heightAboveGround,this.roundedShown(a.elevationM),"m"):this.push(t,"location","elevation",this.labels.elevation,this.rounded(n+a.elevationM),"m")}addDecor(t,e,i,n){const s=e.decor.find(h=>h.id===n.decorId);if(!s){if(n.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(s.title));const r=vr(s,i);this.push(t,"decor","decorBase.eastM",this.labels.decorEast,this.rounded(r.eastM,1),"m"),this.push(t,"decor","decorBase.northM",this.labels.decorNorth,this.rounded(r.northM,1),"m"),this.push(t,"decor","decorBase.altitudeM",this.labels.decorAltitude,this.roundedShown(r.altitudeM),"m"),this.push(t,"decor","decorBase.headingDeg",this.labels.decorHeading,this.rounded(r.headingDeg),"°"),O0(s,i)&&this.push(t,"decor","decorState.lit",this.labels.decorLit,"✓");const a=s.lights?.map(h=>h.id).join()??"",c=a===""?void 0:$m.find(h=>h.create().map(l=>l.id).join()===a);this.push(t,"decor","decorState.lightRig",this.labels.decorLights,c?.name),this.push(t,"decor","decorState.observerSide",this.labels.decorObserverSide,this.decorSideName(s.observerSide));for(const h of vi.of(s)?.parameters??[]){const l=Zr.read(s,h.key);if(l==null)continue;const u=h.type==="choice"?this.said.read(h.choices.find(d=>d.value===l)?.label)??String(l):l;this.push(t,"decor",`decorParam.${h.key}`,this.said.read(h.summary??h.label)??h.key,typeof u=="boolean"?u?"✓":"":u,h.type==="number"?h.unit:void 0)}}timeText(t){return this.timeWords?Ps.describeTime(t,this.timeWords.messages,this.timeWords.locale):jo(t)}addTemporal(t,e){const i=e.event;this.push(t,"temporal","obs-time",this.labels.observationTime,i.time&&this.timeText(i.time)),this.push(t,"temporal","obs-end-time",this.labels.observationEndTime,i.endTime&&this.timeText(i.endTime));const n=ub(i);this.push(t,"temporal","durationSeconds",this.labels.duration,this.roundedShown(n&&n/1e3,1),"s"),this.push(t,"temporal","timeZone",this.labels.utcOffset,i.timeZone),this.push(t,"temporal","utcOffsetHours",this.labels.utcOffset,this.rounded(i.utcOffsetHours,1),"UTC±h")}addWeather(t,e,i){const n=rh(e,i),r={fromSource:e.weatherSource!==void 0},a=this.showsPercent(n.cloudCover)||this.showsPercent(n.lowerCloudCover)||this.showsPercent(n.highCloudCover);this.push(t,"weather","cloudCover",this.labels.cloudCover,this.percentShown(n.cloudCover),"",r),this.push(t,"weather","highCloudCover",this.labels.highCloudCover,this.percentShown(n.highCloudCover),"",r),this.push(t,"weather","iceCrystalAlignment",this.labels.iceCrystalAlignment,this.showsPercent(n.highCloudCover)?this.percent(n.iceCrystalAlignment):void 0),this.push(t,"weather","rareIceCrystals",this.labels.rareIceCrystals,this.showsPercent(n.highCloudCover)?this.percent(n.rareIceCrystals):void 0),this.push(t,"weather","cloudDarkness",this.labels.cloudDarkness,a?this.percent(n.cloudDarkness):void 0,"",r),this.push(t,"weather","cloudBase",this.labels.cloudBase,a?this.rounded(n.cloudBaseM):void 0,"m",r);const c=n.precipitationType!=="none"&&this.showsPercent(n.precipitationIntensity);this.push(t,"weather","precipitationType",this.labels.precipitationType,c?this.precipitationName(n.precipitationType):void 0,"",r),this.push(t,"weather","precipitationIntensity",this.labels.precipitationIntensity,c?this.percent(n.precipitationIntensity):void 0,"",r),this.push(t,"weather","windDirection",this.labels.windDirection,this.shows(n.windSpeed,2)?this.rounded(n.windDirectionDeg):void 0,"°",r),this.push(t,"weather","windSpeed",this.labels.windSpeed,this.roundedShown(n.windSpeed,2),"m/s",r),n.storm&&this.push(t,"weather","storm",this.labels.storm,"✓","",r)}addSound(t,e,i){const n=db(e,i);n.kind!=="none"&&(this.push(t,"sound","soundKind",this.labels.soundKind,this.soundKindName(n.kind)),this.push(t,"sound","soundVolume",this.labels.soundVolume,this.percentShown(n.volume)),this.push(t,"sound","soundPitch",this.labels.soundPitch,this.roundedShown(n.pitchHz),"Hz"),this.push(t,"sound","soundSrc",this.labels.soundSrc,n.src))}addPhenomena(t,e,i){for(const n of e.timeline.sourceIds){const s=e.timeline.getInterpolatedShapeAt(i,n),r=s?.angular,a=r?`${this.rounded(r.widthDeg,2)} × ${this.rounded(r.heightDeg,2)}°`:void 0;this.push(t,"phenomenon",`shape:${n}`,this.said.read(s?.title)??n,a)}for(const n of e.interpretation?.bodies??[]){const s=n.track.find(a=>a.sizeM?.widthM!==void 0)?.sizeM?.widthM,r=n.model.id??n.model.url?.replace(/^.*\//,"");this.push(t,"phenomenon",`body:${n.id}`,this.said.read(n.title)??n.id,[r,s!==void 0?`${this.rounded(s,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"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}}}Ot.register(En,()=>new Zo);Ot.register(Kh,()=>new Rh);Ot.register(gr,()=>new _1);Ot.register(qh,()=>new Ih);Ot.register(Mu,()=>new T1);Ot.register(Zh,()=>new Su);Ot.register(Yh,()=>new xu);Ot.register(Jh,()=>new Eu);Ot.register(Ro,()=>new jh);Ot.register($h,()=>new bu);Ot.register(Ss,()=>new Oi);Ot.register(mo,()=>new Tu);Ot.register(hn,()=>new Jo);Ot.register(go,()=>new Ru);Ot.register(yu,()=>new R1);Ot.register(vo,()=>new Iu);Ot.register(po,()=>new _u);Ot.register(Mo,()=>new Du);Ot.register(gc,()=>new Cu);Ot.register(fo,()=>new Au);Ot.register(hs,()=>new Ye);Ot.register(Aa,()=>new Nu);Ot.register(cn,()=>new Qt);Ot.register(_a,()=>new Lu);Ot.register(wu,()=>new D0);Ot.register(Ta,()=>new Uu);Ot.register(Ea,()=>new Pu);Ot.register(Ra,()=>new ku);Ot.register(Uf,()=>new XE);Ot.register(Sa,()=>new Ou);class Es{constructor(t){this.preferences=t}read(t){var e,i;if(t===void 0)return;if(typeof t=="string")return t===""?void 0:t;for(const s of this.preferences){const r=(e=t[s])!==null&&e!==void 0?e:t[Es.base(s)];if(r)return r}const n=new Set(this.preferences.map(s=>Es.base(s)));for(const[s,r]of Object.entries(t))if(r&&n.has(Es.base(s)))return r;return(i=Object.values(t).find(s=>s))!==null&&i!==void 0?i:void 0}write(t,e,i){var n,s;const r=e?.trim()?e.trim():void 0;if(t===void 0||typeof t=="string")return r;const a={...t},c=(s=(n=Object.keys(a).find(h=>h===i))!==null&&n!==void 0?n:Object.keys(a).find(h=>Es.base(h)===Es.base(i)))!==null&&s!==void 0?s:i;return r===void 0?delete a[c]:a[c]=r,Object.keys(a).length===0?void 0:a}static base(t){return t.toLowerCase().split("-")[0]}}Es.any=new Es([]);var CM;(function(o){o.abductee="abductee",o.actor="actor",o.artist="artist",o.anthropologist="anthropologist",o.archeologist="archeologist",o.astronaut="astronaut",o.astronomer="astronomer",o.astrologist="astrologist",o.astrophysicist="astrophysicist",o.banker="banker",o.barman="barman",o.biologist="biologist",o.biochemist="biochemist",o.biophysicist="biophysicist",o.bishop="bishop",o.businessman="businessman",o.botanist="botanist",o.cameraman="cameraman",o.chemist="chemist",o.contactee="contactee",o.cryptozoologist="cryptozoologist",o.dentist="dentist",o.director="director",o.diplomat="diplomat",o.diver="diver",o.electronics="electronics",o.engineer="engineer",o.ethnologist="ethnologist",o.exobiologist="exobiologist",o.farmer="farmer",o.firefighter="firefighter",o.flightAttendant="flightAttendant",o.geologist="geologist",o.geophysicist="geophysicist",o.geographer="geographer",o.historian="historian",o.houseWife="houseWife",o.hypnotherapist="hypnotherapist",o.illusionist="illusionist",o.journalist="journalist",o.judge="judge",o.lawyer="lawyer",o.leader="leader",o.librarian="librarian",o.logger="logger",o.mathematician="mathematician",o.mechanic="mechanic",o.meteorologist="meteorologist",o.military="military",o.musician="musician",o.neurologist="neurologist",o.neuroscientist="neuroscientist",o.neuropsychiatrist="neuropsychiatrist",o.nurse="nurse",o.oceanographer="oceanographer",o.painter="painter",o.parapsychologist="parapsychologist",o.philosopher="philosopher",o.photographer="photographer",o.physician="physician",o.physicist="physicist",o.pilot="pilot",o.politician="politician",o.policeman="policeman",o.priest="priest",o.producer="producer",o.prospector="prospector",o.psychologist="psychologist",o.psychiatrist="psychiatrist",o.radioastronomer="radioastronomer",o.radioamateur="radioamateur",o.salesman="salesman",o.sailor="sailor",o.sociologist="sociologist",o.softwareEngineer="softwareEngineer",o.stuntman="stuntman",o.taxiDriver="taxiDriver",o.teacher="teacher",o.telegrapher="telegrapher",o.truckDriver="truckDriver",o.ufologist="ufologist",o.ufoWitness="ufoWitness",o.ufoWitness2="ufoWitness2",o.worker="worker",o.writer="writer"})(CM||(CM={}));var OM;(function(o){o.neutral="neutral",o.male="male",o.female="female"})(OM||(OM={}));const fA="modulepreload",pA=function(o,t){return new URL(o,t).href},PM={},De=function(t,e,i){let n=Promise.resolve();if(e&&e.length>0){let r=function(l){return Promise.all(l.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const a=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),h=c?.nonce||c?.getAttribute("nonce");n=r(e.map(l=>{if(l=pA(l,i),l in PM)return;PM[l]=!0;const u=l.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!i)for(let m=a.length-1;m>=0;m--){const g=a[m];if(g.href===l&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":fA,u||(p.as="script"),p.crossOrigin="",p.href=l,h&&p.setAttribute("nonce",h),document.head.appendChild(p),u)return new Promise((m,g)=>{p.addEventListener("load",m),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return n.then(r=>{for(const a of r||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})};class mA extends Error{constructor(t,e){super(t),this.cause=e}}class D1 extends mA{constructor(t=D1.defaultMessage,e){super(t,e)}}D1.defaultMessage="Assertion failed";var NM;(function(o){o.country="country",o.region="region",o.department="department",o.city="city",o.company="company"})(NM||(NM={}));var LM;(function(o){o.at="at",o.au="au",o.ar="ar",o.be="be",o.br="br",o.ca="ca",o.ch="ch",o.cn="cn",o.cl="cl",o.co="co",o.cy="cy",o.de="de",o.dk="dk",o.do="do",o.dz="dz",o.gr="gr",o.ec="ec",o.eg="eg",o.es="es",o.fi="fi",o.fr="fr",o.ga="ga",o.ge="ge",o.hu="hu",o.in="in",o.ie="ie",o.ir="ir",o.il="il",o.it="it",o.jp="jp",o.kr="kr",o.ma="ma",o.mx="mx",o.my="my",o.mz="mz",o.nl="nl",o.no="no",o.nz="nz",o.pa="pa",o.pe="pe",o.ph="ph",o.pl="pl",o.pt="pt",o.ro="ro",o.ru="ru",o.sc="sc",o.tr="tr",o.ua="ua",o.uk="uk",o.us="us",o.sa="sa",o.se="se",o.su="su",o.tn="tn",o.tw="tw",o.ve="ve",o.za="za"})(LM||(LM={}));function C1(o,t){for(const e of o){const i=e.toLowerCase().split("-")[0];if(t.includes(i))return i}return"en"}class Ao{static preferencesFor(t){const e=navigator.languages??[],i=this.declaredFor(t);return i?[i,...e]:e}static declaredFor(t){for(let e=t;e;){const i=e.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=e.getRootNode();e=n instanceof ShadowRoot?n.host:void 0}}}const gA="Global Meteor Network",vA="https://globalmeteornetwork.org/data/",MA="“Thunder” by Jerimee",yA="https://creativecommons.org/licenses/by/3.0/",wA="CC BY 3.0";class In{static fill(t,e){t.innerHTML="";const i=d=>t.appendChild(d),n=e.currentTerrainAttribution;n&&i(In.text(n));const s=e.currentRoadAttribution;s&&i(In.text(s));const r=e.currentWaterAttribution;r&&i(In.text(r));const a=e.currentRailwayAttribution;a&&i(In.text(a));const c=e.ufoElement.observerMapCredit;c&&!n?.includes(c)&&i(In.text(c));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",p=document.createElement("li");d.sourceUrl?p.append(In.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):p.textContent=`${d.title}${f} (${d.license})`,i(p)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(In.link(d.creditUrl,d.credit)):f.textContent=d.credit,i(f)}if(e.ufoElement.sighting.traces.length>0){const d=new Es(Ao.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(p=>d.read(p.source)).filter(p=>!!p));for(const p of f)i(In.text(p))}const h=e.satelliteState;if(h.status==="ready"&&h.credit){const d=document.createElement("li");d.appendChild(In.link(h.creditUrl??"",h.credit)),i(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(In.link(vA,gA),document.createTextNode(" (CC BY 4.0)")),i(d)}const l=e.aircraftState;if(l.status==="ready"&&l.shown>0){const d=document.createElement("li");if(d.appendChild(In.link(l.creditUrl,l.credit)),i(d),l.trailCredit){const f=document.createElement("li");f.appendChild(In.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(f)}}const u=In.text(`${MA} (`);u.append(In.link(yA,wA),document.createTextNode(")")),i(u)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const i=document.createElement("a");return i.href=t,i.target="_blank",i.rel="noopener",i.textContent=e,i}}const bA=[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async o=>{const{CoverageAssessor:t}=await De(async()=>{const{CoverageAssessor:e}=await import("./CoverageAssessor-C7k3p3iN.js");return{CoverageAssessor:e}},[],import.meta.url);return new t().assess(o)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async o=>{const{HynekAssessor:t}=await De(async()=>{const{HynekAssessor:e}=await import("./HynekAssessor-DPsLpEGQ.js");return{HynekAssessor:e}},[],import.meta.url);return new t().assess(o)}})},{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 o=>{const{BallesterGuaspAssessor:t}=await De(async()=>{const{BallesterGuaspAssessor:e}=await import("./BallesterGuaspAssessor-E4mL2MjD.js");return{BallesterGuaspAssessor:e}},__vite__mapDeps([0,1]),import.meta.url);return new t().assess(o)}})}];class O1{constructor(t){this.labels=t}async read(t){const e=[],i=new Set;for(const n of bA){let s;try{s=await n.create().assess(t)}catch{continue}for(const a of s.criteria)a.basis===void 0&&!a.unsupported&&i.add(a.id);const r=s.score===void 0?s.verdict===void 0?"":this.verdictName(n.id,s.verdict):`${Math.round(s.score*100)}%`;r!==""&&e.push({group:"assessment",field:n.id,label:this.labels.assessmentNames[n.id]??n.name,value:r,unit:"",fromSource:!1,about:n.create().about,...s.factors?{detail:O1.factorsText(s.factors)}:{}})}return{entries:e,unanswered:i}}static factorsText(t){const e={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(t).map(([i,n])=>`${e[i]??i} ${n.toFixed(2)}`).join(" × ")}verdictName(t,e){return this.labels.assessmentVerdicts[`${t}.${e}`]??e.toUpperCase()}}const Mb=Math.PI/180,Hf=111320;function de(o,t,e,i){const n=Hf*Math.cos(e*Mb),s=(o-e)*Hf;return{x:(t-i)*n,z:-s}}function As(o,t,e,i){const n=Hf*Math.cos(e*Mb),s=-t,r=o;return{lat:e+s/Hf,lng:i+r/n}}class uh{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,i){const n=t.event.place?.[0],s=t.observerTrack;if(!n)return 0;const r=m=>{const g=s.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const v=de(g.lat,g.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:g.headingDeg}},a=r(e-uh.HALF_SPAN_MS),c=r(e+uh.HALF_SPAN_MS),h=r(e);if(!a||!c||!h)return 0;const l=Math.hypot(c.eastM-a.eastM,c.northM-a.northM),u=2*uh.HALF_SPAN_MS/1e3;if(l/u<uh.MIN_SPEED_MS)return 0;const d=i.heightAt(c.eastM,c.northM)-i.heightAt(a.eastM,a.northM),f=Math.atan2(d,l)*180/Math.PI;if(h.heading===void 0)return f;const p=Math.atan2(c.eastM-a.eastM,c.northM-a.northM)*180/Math.PI;return f*Math.max(0,Math.cos((h.heading-p)*Math.PI/180))}}class hc{static sessionDeclared=!1;static unlock(t){if(hc.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(!(hc.sessionDeclared||typeof navigator>"u")){hc.sessionDeclared=!0;try{const t=navigator.audioSession;t&&(t.type="playback")}catch{}}}}const xA=.08,kM=.15,UM=2,SA=2e3;class EA{context;noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}hc.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);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(n=>n.inside||n.distanceM<SA),i=new Set(e.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of e){const s=this.voices.get(n.id)??this.build(t,n.id);this.retarget(t,s,n)}}build(t,e){const i=t.createGain();i.gain.value=0;const n=t.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(t));const s=t.createOscillator();s.type="sawtooth";const r=t.createOscillator();r.type="sine";const a=t.createGain(),c=t.createBiquadFilter();c.type="lowpass",c.frequency.value=900,s.connect(c),r.connect(c),c.connect(a).connect(n);const h=()=>{const b=t.createBufferSource();return b.buffer=this.noise(t),b.loop=!0,b.loopStart=Math.random()*UM*.5,b},l=h(),u=t.createBiquadFilter();u.type="bandpass",u.Q.value=4;const d=t.createGain();l.connect(u).connect(d).connect(n);const f=h(),p=t.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const m=t.createGain();f.connect(p).connect(m).connect(n);const g=h(),v=t.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const M=t.createGain();g.connect(v).connect(M).connect(n);const w=[s,r,l,f,g];for(const b of w)b.start();const y={nodes:[i,n,a,c,u,d,p,m,v,M,...w],sources:w,firing:s,crank:r,knock:u,engineGain:a,knockGain:d,roadGain:m,windGain:M,cabin:n,output:i};return this.voices.set(e,y),y}retarget(t,e,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:c}){const h=t.currentTime,l=(M,w)=>M.setTargetAtTime(w,h,xA),u=n.rpm/60,d=u*i.cylinders/2,f=Math.min(1,n.rpm/i.shiftUpRpm),p=Math.min(1.5,n.speedMps/30);l(e.firing.frequency,d),l(e.crank.frequency,u),l(e.knock.frequency,d*3),l(e.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*f)*.3),l(e.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),l(e.roadGain.gain,i.roadGain*p**1.5*.8);const m=!r||a;l(e.windGain.gain,p**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+c/60);l(e.cabin.frequency,g);const v=r?.5:Math.min(1,8/Math.max(c,1));l(e.output.gain,v*s)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const i=this.context;i&&(e.output.gain.setTargetAtTime(0,i.currentTime,kM/3),setTimeout(()=>{for(const n of e.sources)try{n.stop()}catch{}for(const n of e.nodes)n.disconnect()},kM*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*UM,t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=e,e}}class Fu{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 Fu.BY_KIND[t??"generic"]??Fu.BY_KIND.generic}}class tc{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,i,n){const s=tc.SAMPLE_MS,r=[];for(let h=i;h<=n+s/2;h+=s){const l=e(h-s/2),u=e(h+s/2);if(!l||!u)return;r.push(Math.hypot(u.eastM-l.eastM,u.northM-l.northM)/(s/1e3))}const a=[];let c=1;for(let h=0;h<r.length;h++){const l=r[h],u=(r[Math.min(h+1,r.length-1)]-r[Math.max(h-1,0)])/(2*s/1e3);if(l<tc.STANDING_MPS){c=1,a.push({speedMps:l,rpm:t.idleRpm,load:.1,gear:0});continue}const d=l*3.6,f=v=>d/t.kmhPer1000Rpm[v-1]*1e3;for(;c<t.kmhPer1000Rpm.length&&f(c)>t.shiftUpRpm;)c++;for(;c>1&&f(c)<t.shiftDownRpm;)c--;const p=Math.max(f(c),t.idleRpm*(1+.3*Math.min(1,l/3))),m=.15+.5*Math.min(1,(l/35)**2),g=u>.15?Math.min(1,m+u/2.5):u<-.3?.05:m;a.push({speedMps:l,rpm:p,load:g,gear:c})}return new tc(a,i)}at(t){const e=(t-this.startMs)/tc.SAMPLE_MS,i=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(e-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class Gf{drives=new Map;at(t,e){const i=[],n=t.event.place?.[0],s=h=>{const l=t.observerTrack.getInterpolatedPoseAt(h),u=l?.lat??n?.lat,d=l?.lng??n?.lng;if(u===void 0||d===void 0||!n)return;const f=de(u,d,n.lat,n.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),a=t.vehicle;if(a){const h=Fu.of(a.kind),l=this.drive(`observer:${a.kind}`,Gf.trackKey(t),()=>tc.of(h,s,0,r));l&&i.push({id:"observer",profile:h,state:l.at(e),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const c=s(e);for(const h of t.decor){if(!h.engine||!c)continue;const l=Fu.of(h.engine.kind),u=m=>{const g=vr(h,m);return{eastM:g.eastM,northM:g.northM}},d=this.drive(`decor:${h.id}`,Gf.decorKey(h,r),()=>tc.of(l,u,0,r));if(!d)continue;const f=vr(h,e),p=Math.hypot(f.eastM-c.eastM,f.northM-c.northM,f.altitudeM);i.push({id:`decor:${h.id}`,profile:l,state:d.at(e),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return i}drive(t,e,i){const n=this.drives.get(t);if(n&&n.key===e)return n.drive;const s=i();return this.drives.set(t,{key:e,drive:s}),s}static trackKey(t){return t.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const FM=864e5,zM=4e4;function AA(o){const t=Math.floor(o.getTime()/FM);return{elapsedMs:o.getTime()-t*FM,shiftM:{x:BM.unit(t,2654435761)*zM,z:BM.unit(t,2246822507)*zM}}}class BM{static unit(t,e){let i=Math.imul(t|0,e)^e;return i=Math.imul(i^i>>>15,739982445),i=Math.imul(i^i>>>12,695872825),i^=i>>>15,(i>>>0)/4294967295*2-1}}function HM(o,t,e,i,n,s,r){const a=i?.lat!==void 0&&i.lng!==void 0&&n?.lat!==void 0&&n.lng!==void 0?de(n.lat,n.lng,i.lat,i.lng):{x:0,z:0};if(r){const l=t.getInterpolatedWeatherAt(0)??e,u=s===void 0?void 0:l.cloudLayers?.find(p=>p.id===s),d=(u?.windDirectionDeg??l.windDirectionDeg)*Math.PI/180,f=(u?.windSpeed??l.windSpeed)*r.elapsedMs/1e3;a.x+=r.shiftM.x-Math.sin(d)*f,a.z+=r.shiftM.z+Math.cos(d)*f}const c=Math.max(0,o),h=[0,...t.allKeyframes.map(l=>l.t).filter(l=>l>0&&l<c),c];for(let l=1;l<h.length;l++){const u=h[l-1],d=h[l]-u;if(d===0)continue;const f=32;for(let p=0;p<=f;p++){const m=t.getInterpolatedWeatherAt(u+d*p/f)??e,g=s===void 0?void 0:m.cloudLayers?.find(y=>y.id===s),v=(g?.windDirectionDeg??m.windDirectionDeg)*Math.PI/180,M=p===0||p===f?1:p%2===0?2:4,w=(g?.windSpeed??m.windSpeed)*d/1e3/f/3*M;a.x-=Math.sin(v)*w,a.z+=Math.cos(v)*w}}return a}const _A="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==",TA=`
667
+ `;class Xm{static NAMES=["weather","place","lightPollution","decor"];static KEYS={weather:["weatherTrack","weatherSource"],place:["place"],lightPollution:["lightPollution"],decor:["decor"]};static annexName(t,e){return`${t}.${e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}.json`}static fromFile(t,e){return t?.[e]!==void 0&&t[e].live!==!0}}class Ch{static NAMES=["relief","imagery","roads","water","railways","upperAir","map"];static TERRAIN=["relief","imagery","roads","water","railways"];static held(t,e){if(!t||t.live)return;const i=t[e];return i&&!i.live&&!i.refresh&&i.src!==void 0?i:void 0}static isLive(t,e){return t?.live===!0||t?.[e]?.live===!0}static annexName(t,e){const i=e==="relief"||e==="imagery"||e==="map"?"zip":"json",n=e.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);return`${t}.${n}.${i}`}static isEmpty(t){return!t||!t.live&&Ch.NAMES.every(e=>!t[e])&&Xm.NAMES.every(e=>!t[e])}}class Cc extends Error{constructor(t,e,i){super(`${t}: ${e}${i===void 0?"":` (HTTP ${i})`}`),this.kind=t,this.url=e,this.status=i,this.name="SightingFetchError"}}class Eo{static async recording(t){const e=await Eo.json(t);for(const i of Xm.NAMES){const n=e?.frozen?.[i];if(!(!n?.src||n.live))try{const s=Wi.toCurrent(await Eo.json(new URL(n.src,new URL(t,location.href)).href));for(const r of Xm.KEYS[i])s[r]!==void 0&&(e[r]=s[r])}catch{}}return e}static async json(t){const e=new URL(t,location.href);if(location.protocol==="https:"&&e.protocol==="http:")throw new Cc("mixed-content",t);let i;try{i=await fetch(t)}catch{throw await this.diagnose(t,e)}if(!i.ok)throw new Cc("status",t,i.status);try{return await i.json()}catch{throw new Cc("malformed",t)}}static async diagnose(t,e){if(e.origin===location.origin)return new Cc("unreachable",t);try{return await fetch(t,{mode:"no-cors"}),new Cc("cors",t)}catch{return new Cc("unreachable",t)}}}class iA extends Error{constructor(t,e,i){super(typeof e=="number"&&Number.isInteger(e)&&e>i?`This ${t} file is in version ${e} of its format; this UFO@home reads up to version ${i}. Read it with a newer UFO@home.`:`This ${t} file states ${JSON.stringify(e)} as its format version, which is not a version.`),this.format=t,this.found=e,this.supported=i,this.name="FormatVersionError"}said(t){return t.replace("{found}",typeof this.found=="number"?String(this.found):JSON.stringify(this.found)).replace("{supported}",String(this.supported))}}class Qo{static CURRENT={sighting:3,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(t,e=Qo.CURRENT[t]){return`${Qo.SCHEMA_BASE}/${e}/${t}.schema.json`}static of(t){if(typeof t!="object"||t===null)return 1;const e=t.version;return e===void 0?1:typeof e=="object"&&e!==null&&"value"in e?e.value:e}static check(t,e){const i=Qo.of(t),n=Qo.CURRENT[e];if(typeof i!="number"||!Number.isInteger(i)||i<1||i>n)throw new iA(e,i,n);return t}}class mn{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static INTERVIEW_EVENT="interview";static check(t){return Qo.check(t,"case")}static isCase(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Array.isArray(t.events)&&!("timeline"in t)}static sightingUrls(t,e){return(t.events??[]).filter(i=>i.eventType===mn.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,e).href)}static accountIds(t,e,i,n){const s=(t.events??[]).filter(r=>r.eventType===mn.SIGHTING_EVENT&&r.id!==void 0&&typeof r.url=="string"&&i!==void 0&&new URL(r.url,e).href===i).map(r=>r.id);return n!==void 0&&s.push(n),s}static interpretationEvents(t,e){const i=[e].flat().filter(n=>!!n);return i.length===0?[]:(t.events??[]).filter(n=>n.eventType===mn.INTERPRETATION_EVENT?n.sighting!==void 0&&i.includes(n.sighting):n.eventType!==mn.SIGHTING_EVENT||n.interpretationOf===void 0?!1:[n.interpretationOf].flat().some(s=>i.includes(s))).map(n=>n)}static problems(t,e){const i=t.events??[],n=new Set,s=new Set;for(const a of i)a.id!==void 0&&(n.has(a.id)&&s.add(a.id),n.add(a.id));const r=[];for(const a of i){const c=a.eventType===mn.SIGHTING_EVENT?a.interpretationOf:a.eventType===mn.INTERVIEW_EVENT?a.interviewOf:void 0;if(c!==void 0)for(const h of[c].flat())!n.has(h)&&!e.includes(h)&&r.push({reading:a.url??a.id??"",reference:h})}return{duplicateIds:[...s],unresolved:r}}static async interpretationOf(t,e,i){if(t.bodies)return mn.withModelsFrom(os.strip({title:t.title,bodies:t.bodies??[],smoke:t.smoke,flares:t.flares,lanterns:t.lanterns}).recording,e);if(!t.url)return{title:t.title,bodies:[]};const n=new URL(t.url,e).href,s=await i(n),r="timeline"in s&&s.interpretation?s.interpretation:s;return mn.withModelsFrom(os.strip({title:t.title??r.title,bodies:r.bodies??[],smoke:r.smoke,flares:r.flares,lanterns:r.lanterns}).recording,n)}static withModelsFrom(t,e){return{...t,bodies:t.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,e).href}}:i)}}}class Ps{constructor(t,e,i,n="en"){this.parts=t,this.messages=e,this.onChange=i,this.locale=n,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="";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:i}=this.parts;e.value=t?jo(t):"",i.type!=="date"&&(i.step=Ps.stepFor(t)),i.value=i.type==="date"?Ps.pickerDateOf(t):Ps.pickerValueOf(t),e.setCustomValidity(""),e.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...t){return t.every(e=>e===void 0||Ps.isPickable(e)&&Ps.qualifierOf(jo(e))==="")}static opensPreciseDate(...t){return t.every(e=>e===void 0||Ps.isFullDate(e)&&Ps.qualifierOf(jo(e))==="")}static isFullDate(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0}static pickerDateOf(t){if(!Ps.isFullDate(t))return"";const e=(i,n=2)=>String(i).padStart(n,"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(!Ps.isPickable(t))return"";const e=(n,s=2)=>String(n).padStart(s,"0"),i=t.second?`:${e(t.second)}`:"";return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}T${e(t.hour)}:${e(t.minute)}${i}`}static stepFor(t){return t?.second?"1":"60"}static qualifierOf(t){const e=/[?%]/.test(t),i=/[~%]/.test(t);return e&&i?"%":e?"?":i?"~":""}describe(t){return Ps.describeTime(t,this.messages,this.locale)}static describeTime(t,e,i){const n=jo(t),s=Ps.qualifierOf(n),r=l=>String(l).padStart(2,"0"),a=[];if(t.season!==void 0){const l={spring:e.timeSeasonSpring,summer:e.timeSeasonSummer,autumn:e.timeSeasonAutumn,winter:e.timeSeasonWinter}[t.season];a.push(t.year!==void 0?`${l} ${t.year}`:l)}else if(t.year!==void 0){const l=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"},u=new Date(Date.UTC(t.year,(t.month??1)-1,t.day??1));a.push(new Intl.DateTimeFormat(i,{...l,timeZone:"UTC"}).format(u))}t.hour!==void 0&&a.push(`${r(t.hour)}:${r(t.minute??0)}${t.second!==void 0?`:${r(t.second)}`:""}`);const c=a.join(", "),h=s==="~"?e.timeQualifierApproximate:s==="?"?e.timeQualifierUncertain:s==="%"?e.timeQualifierBoth:"";return h?`${c} — ${h.toLowerCase()}`:c}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 i=Dh(e);t.title=i?`→ ${this.describe(i)}`:this.messages.edtfInvalid}readText(){const t=this.parts.text.value.trim();if(t===""){this.clean(),this.onChange(void 0);return}const e=Dh(t);e&&(this.clean(),this.onChange(e))}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===""||Dh(e)||(t.setCustomValidity(this.messages.edtfInvalid),t.classList.add("invalid"))}}class Zr{static read(t,e){let i=t;for(const n of e.split(".")){if(i=Zr.bare(i),i===null||typeof i!="object")return;i=i[n]}return Zr.bare(i)}static write(t,e,i){const n=e.split("."),s=[];let r=t;for(let c=0;c<n.length-1;c++){let h=Zr.bare(r[n[c]]);if(h===null||typeof h!="object"||Array.isArray(h)){if(i===void 0)return;h={}}r[n[c]]=h,s.push({owner:r,part:n[c]}),r=h}const a=n[n.length-1];i===void 0?delete r[a]:r[a]=i;for(let c=s.length-1;c>=0;c--){const h=s[c].owner[s[c].part];if(Object.keys(h).length>0)break;delete s[c].owner[s[c].part]}}static stated(t,e){return Zr.read(t,e)!==void 0}static bare(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&"value"in t&&"basis"in t?t.value:t}}class vc{static MODES=["off","position","dipped","main","fog"];static DISPLAY_GAIN=.006;static TOE_IN_DEG=.6;static AUTO_BELOW_SUN_DEG=-1;static BEAMS={off:void 0,position:void 0,dipped:{candela:25e3,halfAngleDeg:24,pitchDeg:2.5,penumbra:1,color:"#fff2d8"},main:{candela:12e4,halfAngleDeg:14,pitchDeg:.4,penumbra:.85,color:"#fff6e6"},fog:{candela:9e3,halfAngleDeg:38,pitchDeg:5,penumbra:1,color:"#ffe9b0"}};static isMode(t){return typeof t=="string"&&vc.MODES.includes(t)}static at(t,e,i){if(!e||e.length===0)return t;let n=e[0];for(const s of e){if(s.t>i)break;n=s}return n.mode}static auto(t){return t<vc.AUTO_BELOW_SUN_DEG?"dipped":"off"}static lamps(t){return t!=="off"}}function nA(o){return o==="vehicle"?["front","behind","front-left","front-right","behind-left","behind-right"]:["front","behind","left","right"]}const sA=90,Ff=2;function pb(o){return o==="building"||o==="vehicle"}function rA(o,t){return o==="building"?!0:o==="vehicle"?t!=="front"&&t!=="behind":!1}function Qh(o){return o==="building"||o==="vehicle"}const mb={aircraft:{id:"poly-google-airliner"},tree:{id:"jungle-jim-tree-large-a"},observer:{id:"makehuman-farmer-40s"},entity:{id:"makehuman-farmer-40s"}},aA=["makehuman-farmer-40s","makehuman-man-overalls","makehuman-man-jacket","makehuman-old-man","makehuman-woman"];function _M(o,t){let e=0;for(const i of t)e=e*31+i.charCodeAt(0)>>>0;return{id:o[e%o.length]}}const oA=["jungle-jim-tree-large-a","jungle-jim-tree-medium-a","jungle-jim-tree-large-b","jungle-jim-tree-medium-b","jungle-jim-tree-large-c","jungle-jim-tree-medium-c","jagobo-tree-maple-a","jagobo-tree-maple-b","jagobo-tree-aspen-a","jagobo-tree-aspen-b","nicholas-3d-tree-a","nicholas-3d-tree-b","nicholas-3d-tree-c"];function zf(o){return o.model?o.model:o.kind==="tree"&&o.id!==void 0?_M(oA,o.id):(o.kind==="observer"||o.kind==="entity")&&o.id!==void 0?_M(aA,o.id):mb[o.kind]}function gb(o,t){const e=vc.at(o.headlights,o.headlightKeyframes,t);return e!==void 0?e:O0(o,t)?"dipped":"off"}const cA=-.5;function hA(o){return o.kind==="streetlight"&&o.origin!==void 0&&o.lit===void 0&&!o.litKeyframes?.length}function O0(o,t,e){if(e!==void 0&&hA(o))return e<cA;const i=o.litKeyframes;if(!i||i.length===0)return o.lit??!1;let n=i[0];for(const s of i){if(s.t>t)break;n=s}return n.lit}function TM(o,t){const e=o.observerKeyframes;if(!e||e.length===0)return{side:o.observerSide,facing:o.observerFacing};let i=e[0];for(const n of e){if(n.t>t)break;i=n}return{side:i.side,facing:i.facing}}function lA(o,t){const e=Oh(o,t);return e.intensity<=0?!1:e.pattern.kind==="steady"?!0:vb(o,t,t+1)>.5}function Oh(o,t){let e;for(const i of o.keyframes??[]){if(i.t>t)break;e=i}return{intensity:e?.intensity??o.intensity??1,pattern:e?.pattern??o.pattern}}function vb(o,t,e){const i=o.keyframes??[];if(i.length===0)return hp(o.pattern,t,e);const n=[t,...i.map(r=>r.t).filter(r=>r>t&&r<e),e];if(e<=t)return Oh(o,t).intensity>0?hp(Oh(o,t).pattern,t,e):0;let s=0;for(let r=0;r<n.length-1;r++){const a=Oh(o,n[r]);a.intensity>0&&(s+=hp(a.pattern,n[r],n[r+1])*(n[r+1]-n[r]))}return s/(e-t)}function hp(o,t,e){if(o.kind==="steady")return 1;const{perMinute:i,dutyCycle:n,phase:s=0}=o,r=Math.min(Math.max(n,0),1);if(r===0||i<=0)return 0;const a=6e4/i,c=t/a+s,h=e/a+s;if(h<=c)return Math.min(Math.max(c-Math.floor(c),0),r)<r?1:0;const l=u=>Math.floor(u)*r+Math.min(u-Math.floor(u),r);return(l(h)-l(c))/(h-c)}function vr(o,t){const e=o.track,i={eastM:o.eastM,northM:o.northM,altitudeM:0,headingDeg:o.headingDeg};if(!e||e.length===0)return i;if(e.length===1||t<=e[0].t)return RM(e[0],o);const n=e[e.length-1];if(t>=n.t)return RM(n,o);for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1];if(t<r.t||t>a.t)continue;const c=a.t-r.t,h=c===0?0:(t-r.t)/c;return{eastM:r.eastM+(a.eastM-r.eastM)*h,northM:r.northM+(a.northM-r.northM)*h,altitudeM:(r.altitudeM??0)+((a.altitudeM??0)-(r.altitudeM??0))*h,headingDeg:r.headingDeg??o.headingDeg}}return i}function uA(o,t){const e=(o.track??[]).filter(i=>i.gazeAzimuthDeg!==void 0);if(e.length!==0){if(t<=e[0].t)return e[0].gazeAzimuthDeg;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t>s.t)continue;const r=s.t-n.t,a=r===0?0:(t-n.t)/r,c=((s.gazeAzimuthDeg-n.gazeAzimuthDeg)%360+540)%360-180;return((n.gazeAzimuthDeg+c*a)%360+360)%360}return e[e.length-1].gazeAzimuthDeg}}function RM(o,t){return{eastM:o.eastM,northM:o.northM,altitudeM:o.altitudeM??0,headingDeg:o.headingDeg??t.headingDeg}}const IM="#ff2200",DM="#00ff44",ko="#ffffff",hd="#ffa500",Oc="#ff0000",dA="#2244ff",$m=[{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:IM,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:DM,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:ko,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:Oc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:Oc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:ko,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:ko,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:IM,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:DM,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:ko,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:Oc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:ko,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:ko,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:ko,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:Oc,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:Oc,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:hd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:hd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:hd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:hd,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:dA,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:Oc,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>ge.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>ge.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 Bf{static forKind(t){return $m.filter(e=>e.kinds.includes(t))}static byId(t){return $m.find(e=>e.id===t)}}class ge{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*ge.CYCLE_S/2,i=ge.VEHICLE_HEAD_Y_M,n=ge.LENS_SPACING_M;return[ge.lamp("red",ge.RED,i+n,e+ge.GREEN_S+ge.AMBER_S,ge.CYCLE_S-ge.GREEN_S-ge.AMBER_S,ge.VEHICLE_INTENSITY),ge.lamp("amber",ge.AMBER,i,e+ge.GREEN_S,ge.AMBER_S,ge.VEHICLE_INTENSITY),ge.lamp("green",ge.GREEN,i-n,e,ge.GREEN_S,ge.VEHICLE_INTENSITY)]}static pedestrianLights(t){const e=t*ge.CYCLE_S/2+ge.GREEN_S+ge.AMBER_S+ge.PEDESTRIAN_DELAY_S,i=ge.PEDESTRIAN_HEAD_Y_M,n=ge.LENS_SPACING_M/2;return[ge.lamp("ped-red",ge.RED,i+n,e+ge.PEDESTRIAN_GREEN_S,ge.CYCLE_S-ge.PEDESTRIAN_GREEN_S,ge.PEDESTRIAN_INTENSITY),ge.lamp("ped-green",ge.GREEN,i-n,e,ge.PEDESTRIAN_GREEN_S,ge.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,i,n,s,r){const a=ge.CYCLE_S,c=Math.round(((1-n/a)%1+1)%1*1e6)/1e6;return{id:t,color:e,intensity:r,radiusM:ge.LENS_RADIUS_M,beamDeg:ge.BEAM_DEG,offsetM:{x:0,y:i,z:-.13},pattern:{kind:"flash",perMinute:60/a,dutyCycle:Math.round(s/a*1e6)/1e6,...c?{phase:c}:{}}}}}class Kl{static of(t,e){const i=Kl.drawnAsModel(t);return{color:e?.color??!i,lit:e?.lit??Kl.litByDefault(t.kind,i),headlights:t.kind==="vehicle",lights:(e?.lights??!0)&&Kl.rigsFor(t.kind,e).length>0,windows:!i&&pb(t.kind),floors:!i&&t.kind==="building",observerSide:Qh(t.kind)}}static rigsFor(t,e){return Bf.forKind(t).filter(i=>e?.lightRigs===void 0||e.lightRigs.includes(i.id))}static drawnAsModel(t){return zf(t)!==void 0&&!(t.observerSide!==void 0&&Qh(t.kind))}static litByDefault(t,e){return t==="streetlight"||t==="vehicle"&&!e}}class vi{static sideLabel(t){return vi.SIDE_LABELS[t]}static SIDE_LABELS={front:{en:"Front",fr:"Avant",es:"Frente",it:"Fronte"},behind:{en:"Behind",fr:"Arrière",es:"Detrás",it:"Dietro"},left:{en:"Left",fr:"Gauche",es:"Izquierda",it:"Sinistra"},right:{en:"Right",fr:"Droite",es:"Derecha",it:"Destra"},"front-left":{en:"Front-left",fr:"Avant gauche",es:"Delantero izquierdo",it:"Anteriore sinistro"},"front-right":{en:"Front-right",fr:"Avant droit",es:"Delantero derecho",it:"Anteriore destro"},"behind-left":{en:"Behind-left",fr:"Arrière gauche",es:"Trasero izquierdo",it:"Posteriore sinistro"},"behind-right":{en:"Behind-right",fr:"Arrière droit",es:"Trasero derecho",it:"Posteriore destro"}};static WINDOWS={en:"Windows",fr:"Fenêtres",es:"Ventanas",it:"Finestre"};static BUILDING={en:"Building",fr:"Bâtiment",es:"Edificio",it:"Edificio"};static BRIDGE={en:"Bridge",fr:"Pont",es:"Puente",it:"Ponte"};static RAILING={en:"Railing",fr:"Garde-corps",es:"Barandilla",it:"Parapetto"};static WIRE={en:"Overhead line",fr:"Ligne aérienne",es:"Línea aérea",it:"Linea aerea"};static together(t,e){const i=["en","fr","es","it"],n=(s,r)=>typeof s=="string"?s:s[r]??s.en;return Object.fromEntries(i.map(s=>[s,`${n(t,s)} ${n(e,s)}`]))}static of(t,e){const i=[],n=Kl.drawnAsModel(t);if(!n&&t.kind==="building"&&i.push(...vi.floors(),...vi.walls(),...vi.roof()),!n&&pb(t.kind)&&i.push(...vi.windows(t.kind)),t.kind==="vehicle"&&i.push(...vi.engine()),t.kind==="observer"&&i.push(...vi.observerRecording()),t.kind==="aircraft"&&i.push(...vi.aircraftSound(e)),t.kind==="bridge"&&i.push(...vi.bridge()),t.kind==="wire"&&i.push(...vi.wire()),e?.parameters&&i.push(...e.parameters.map(s=>({...s,key:`modelParameters.${s.key}`}))),i.length!==0)return{kind:`decor-${t.kind}`,title:{en:"Properties",fr:"Propriétés",es:"Propiedades",it:"Proprietà"},parameters:i}}static floors(){const t=e=>Zr.read(e,"floors")??Ff;return[{type:"number",key:"floors",min:0,max:20,step:1,effective:()=>Ff,label:{en:"Floors",fr:"Étages",es:"Plantas",it:"Piani"},hint:{en:"Upper stories above the ground floor.",fr:"Étages au-dessus du rez-de-chaussée.",es:"Plantas sobre la planta baja.",it:"Piani sopra il pianterreno."},group:vi.BUILDING},{type:"number",key:"occupiedFloor",min:0,max:20,step:1,effective:()=>0,bounds:e=>({max:t(e)}),label:{en:"Occupied floor",fr:"Étage occupé",es:"Planta ocupada",it:"Piano occupato"},hint:{en:"The floor the observer is on, from 0 (ground floor).",fr:"L'étage où se tient l'observateur, à partir de 0 (rez-de-chaussée).",es:"La planta donde está el observador, desde 0 (planta baja).",it:"Il piano dove si trova l'osservatore, da 0 (pianterreno)."},group:vi.BUILDING}]}static walls(){const t={en:"Walls",fr:"Murs",es:"Muros",it:"Muri"};return[{type:"colour",key:"facade.color",group:t,fallback:"#d3cab8",label:{en:"Wall colour",fr:"Couleur des murs",es:"Color de los muros",it:"Colore dei muri"},hint:{en:"The colour of the walls, drawn with the facade of their kind where the width, the length and the height of the building are all stated. Empty: a pale plaster.",fr:"La couleur des murs, dessinés avec la façade de leur type là où la largeur, la longueur et la hauteur du bâtiment sont toutes énoncées. Vide : un enduit pâle.",es:"El color de los muros, dibujados con la fachada de su tipo donde el ancho, el largo y el alto del edificio están todos enunciados. Vacío: un enlucido pálido.",it:"Il colore dei muri, disegnati con la facciata del loro tipo dove larghezza, lunghezza e altezza dell'edificio sono tutte enunciate. Vuoto: un intonaco chiaro."}},{type:"choice",key:"facade.openings",group:t,label:{en:"Facade",fr:"Type de façade",es:"Tipo de fachada",it:"Tipo di facciata"},empty:{en:"A house's",fr:"D'une maison",es:"De una casa",it:"Di una casa"},hint:{en:"A house's: a window every three metres of every floor and a door, from a storey high (lower, a shed's bare wall). The tall windows of an old building, the tall narrow bays of a church, a bare wall (a warehouse, a shed, a monument), or none: the plain box.",fr:"D'une maison : une fenêtre tous les trois mètres de chaque étage et une porte, dès la hauteur d'un étage (plus bas, le mur nu d'un abri). Les hautes fenêtres d'un immeuble ancien, les hautes baies étroites d'une église, un mur nu (un entrepôt, un hangar, un monument), ou aucune : la simple boîte.",es:"De una casa: una ventana cada tres metros de cada planta y una puerta, desde la altura de una planta (más bajo, el muro liso de un cobertizo). Las ventanas altas de un edificio antiguo, los vanos altos y estrechos de una iglesia, un muro liso (un almacén, un cobertizo, un monumento), o ninguna: la caja lisa.",it:"Di una casa: una finestra ogni tre metri di ogni piano e una porta, dall'altezza di un piano (più basso, il muro liscio di un capanno). Le finestre alte di un edificio antico, le alte aperture strette di una chiesa, un muro liscio (un magazzino, un capannone, un monumento), o nessuna: la semplice scatola."},choices:[{value:"tall",label:{en:"Old building",fr:"Immeuble ancien",es:"Edificio antiguo",it:"Edificio antico"}},{value:"lancet",label:{en:"Church",fr:"Église",es:"Iglesia",it:"Chiesa"}},{value:"plain",label:{en:"Bare wall",fr:"Mur nu",es:"Muro liso",it:"Muro liscio"}},{value:"none",label:{en:"None",fr:"Aucune",es:"Ninguna",it:"Nessuna"}}]}]}static roof(){const t={en:"Roof",fr:"Toit",es:"Tejado",it:"Tetto"};return[{type:"choice",key:"roof.shape",group:t,label:{en:"Roof",fr:"Toit",es:"Tejado",it:"Tetto"},empty:{en:"Flat",fr:"Plat",es:"Plano",it:"Piano"},hint:{en:"Flat (the box), two slopes to a ridge, four slopes, or a dome.",fr:"Plat (la boîte), deux pentes jusqu'à un faîte, quatre pentes, ou une coupole.",es:"Plano (la caja), dos vertientes hasta una cumbrera, cuatro vertientes, o una cúpula.",it:"Piano (la scatola), due falde fino a un colmo, quattro falde, o una cupola."},choices:[{value:"flat",label:{en:"Flat",fr:"Plat",es:"Plano",it:"Piano"}},{value:"gable",label:{en:"Two slopes",fr:"Deux pentes",es:"Dos vertientes",it:"Due falde"}},{value:"hip",label:{en:"Four slopes",fr:"Quatre pentes",es:"Cuatro vertientes",it:"Quattro falde"}},{value:"dome",label:{en:"Dome",fr:"Coupole",es:"Cúpula",it:"Cupola"}}]},{type:"number",key:"roof.riseM",min:0,max:15,step:.1,unit:"m",group:t,effective:()=>3,label:{en:"Rise",fr:"Hauteur du toit",es:"Altura del tejado",it:"Altezza del tetto"},hint:{en:"How far the ridge stands above the eaves: the walls are the building's height less this.",fr:"De combien le faîte dépasse l'égout : les murs font la hauteur du bâtiment moins cela.",es:"Cuánto sube la cumbrera sobre el alero: los muros miden la altura del edificio menos esto.",it:"Quanto il colmo sta sopra la gronda: i muri sono l'altezza dell'edificio meno questo."},visibleWhen:i=>["gable","hip","dome"].includes(String(Zr.read(i,"roof.shape")))},{type:"choice",key:"roof.ridge",group:t,required:!1,label:{en:"Ridge along",fr:"Faîte le long de",es:"Cumbrera a lo largo de",it:"Colmo lungo"},empty:{en:"The width",fr:"La largeur",es:"El ancho",it:"La larghezza"},choices:[{value:"width",label:{en:"The width",fr:"La largeur",es:"El ancho",it:"La larghezza"}},{value:"depth",label:{en:"The depth",fr:"La profondeur",es:"El largo",it:"La profondità"}}],visibleWhen:i=>Zr.read(i,"roof.shape")==="gable"},{type:"colour",key:"roof.color",group:t,fallback:"#7a5a4a",label:{en:"Roof colour",fr:"Couleur du toit",es:"Color del tejado",it:"Colore del tetto"}}]}static windows(t){return nA(t).map(e=>({type:"number",key:`windows.${e}`,step:5,unit:"%",min:rA(t,e)?0:sA,max:100,label:vi.SIDE_LABELS[e],summary:vi.together(vi.WINDOWS,vi.SIDE_LABELS[e]),hint:{en:"Opacity of the window on this side: 0 is open, 100 shut. Empty: no window.",fr:"Opacité de la fenêtre de ce côté : 0 ouverte, 100 fermée. Vide : pas de fenêtre.",es:"Opacidad de la ventana de este lado: 0 abierta, 100 cerrada. Vacío: sin ventana.",it:"Opacità della finestra di questo lato: 0 aperta, 100 chiusa. Vuoto: nessuna finestra."},group:vi.WINDOWS}))}static engine(){const t={en:"Engine sound",fr:"Bruit du moteur",es:"Sonido del motor",it:"Suono del motore"};return[{type:"choice",key:"engine.kind",group:t,label:{en:"Engine",fr:"Moteur",es:"Motor",it:"Motore"},hint:{en:"Whether the vehicle is heard running, and what sort of engine: how many cylinders fire, how low they turn, how its gears are spaced.",fr:"Si le véhicule s'entend rouler, et de quel moteur : combien de cylindres tirent, à quel régime bas ils tournent, comment ses vitesses sont étagées.",es:"Si se oye el vehículo en marcha, y qué motor: cuántos cilindros disparan, cuán bajo giran, cómo se escalonan sus marchas.",it:"Se il veicolo si sente in marcia, e di che motore: quanti cilindri sparano, quanto in basso girano, come sono distanziate le marce."},empty:{en:"Silent (parked)",fr:"Silencieux (à l'arrêt)",es:"Silencioso (parado)",it:"Silenzioso (fermo)"},choices:[{value:"car",label:{en:"Car",fr:"Voiture",es:"Coche",it:"Auto"}},{value:"van",label:{en:"Van",fr:"Camionnette",es:"Furgoneta",it:"Furgone"}},{value:"truck",label:{en:"Truck",fr:"Camion",es:"Camión",it:"Camion"}},{value:"motorcycle",label:{en:"Motorcycle",fr:"Moto",es:"Moto",it:"Moto"}},{value:"generic",label:{en:"Unknown",fr:"Inconnu",es:"Desconocido",it:"Sconosciuto"}}]},{type:"number",key:"engine.noise",min:.1,max:3,step:.1,group:t,effective:()=>1,label:{en:"Loudness",fr:"Volume",es:"Volumen",it:"Volume"},hint:{en:"Against an ordinary one of its kind: 1 by default, 1.5 for a very noisy one.",fr:"Par rapport à un véhicule ordinaire de son genre : 1 par défaut, 1,5 pour un très bruyant.",es:"Frente a uno ordinario de su tipo: 1 por defecto, 1,5 para uno muy ruidoso.",it:"Rispetto a uno ordinario del suo tipo: 1 per impostazione predefinita, 1,5 per uno molto rumoroso."},visibleWhen:e=>Zr.read(e,"engine.kind")!==void 0||e.engine!==void 0}]}static observerRecording(){return[{type:"text",key:"sightingUrl",placeholder:"https://…/sighting.json",label:{en:"Their own recording URL",fr:"URL de son propre enregistrement",es:"URL de su propia grabación",it:"URL della sua registrazione"}}]}static aircraftSound(t){const e=(n,s,r,a,c)=>({value:n,label:{en:s,fr:r,es:a,it:c}}),i=t?.sound;return[{type:"choice",key:"aircraftSound",group:{en:"Sound",fr:"Bruit",es:"Sonido",it:"Suono"},label:{en:"Noise in flight",fr:"Bruit en vol",es:"Ruido en vuelo",it:"Rumore in volo"},hint:{en:"What it sounds like while it flies: nothing is heard of a machine that flies silent, and the stand-in of a phenomenon says so.",fr:"Ce qu'on entend quand il vole : rien d'une machine qui vole en silence, et la maquette d'un phénomène le dit.",es:"Cómo suena mientras vuela: nada se oye de una máquina que vuela en silencio, y la maqueta de un fenómeno lo dice.",it:"Come suona mentre vola: nulla si sente di una macchina che vola in silenzio, e il modello di un fenomeno lo dice."},empty:i==="silent"?{en:"Silent (as the model)",fr:"Silencieux (comme le modèle)",es:"Silencioso (como el modelo)",it:"Silenzioso (come il modello)"}:{en:"As the model",fr:"Selon le modèle",es:"Según el modelo",it:"Secondo il modello"},choices:[e("airliner-narrow","Narrow-body airliner","Avion de ligne monocouloir","Avión de pasillo único","Aereo di linea a fusoliera stretta"),e("airliner-wide","Wide-body airliner","Avion de ligne gros-porteur","Avión de fuselaje ancho","Aereo di linea a fusoliera larga"),e("regional-jet","Regional jet","Jet régional","Jet regional","Jet regionale"),e("regional-turboprop","Turboprop","Turbopropulseur","Turbohélice","Turboelica"),e("business-jet","Business jet","Jet d'affaires","Jet privado","Jet privato"),e("light-piston","Light piston aircraft","Avion léger à pistons","Avioneta de pistones","Aereo leggero a pistoni"),e("helicopter-light","Light helicopter","Hélicoptère léger","Helicóptero ligero","Elicottero leggero"),e("helicopter-medium","Medium helicopter","Hélicoptère moyen","Helicóptero medio","Elicottero medio"),e("helicopter-heavy","Heavy helicopter","Hélicoptère lourd","Helicóptero pesado","Elicottero pesante"),e("military-jet","Military jet","Avion de combat","Reactor militar","Jet militare"),e("ultralight","Ultralight","ULM","Ultraligero","Ultraleggero"),e("unmanned","Drone","Drone","Dron","Drone"),e("glider","Glider","Planeur","Planeador","Aliante"),e("silent","Silent","Silencieux","Silencioso","Silenzioso")]}]}static bridge(){const t=(e,i,n,s,r,a,c,h,l)=>({type:"number",key:e,label:i,min:n,max:s,step:r,unit:a,group:h,hint:l,effective:c===void 0?void 0:()=>c});return[t("bridge.spanM",{en:"Span",fr:"Portée",es:"Luz",it:"Luce"},.1,5e3,.1,"m",void 0,vi.BRIDGE,{en:"Metres of open span under the deck, centred. Empty: the whole length, no embankments.",fr:"Mètres de portée libre sous le tablier, centrés. Vide : toute la longueur, sans remblais.",es:"Metros de luz libre bajo el tablero, centrados. Vacío: toda la longitud, sin terraplenes.",it:"Metri di luce libera sotto l'impalcato, centrati. Vuoto: tutta la lunghezza, senza rilevati."}),t("bridge.deckThicknessM",{en:"Deck thickness",fr:"Épaisseur du tablier",es:"Espesor del tablero",it:"Spessore dell'impalcato"},.1,20,.1,"m",1.2,vi.BRIDGE),t("bridge.railing.heightM",{en:"Height",fr:"Hauteur",es:"Altura",it:"Altezza"},.1,5,.05,"m",1.05,vi.RAILING),t("bridge.railing.postSpacingM",{en:"Post spacing",fr:"Espacement des poteaux",es:"Separación de postes",it:"Distanza dei montanti"},.2,20,.1,"m",1.5,vi.RAILING),t("bridge.railing.rails",{en:"Rails",fr:"Lisses",es:"Barandas",it:"Correnti"},0,8,1,"",2,vi.RAILING)]}static wire(){return[{type:"choice",key:"wire.poles",group:vi.WIRE,label:{en:"Poles",fr:"Poteaux",es:"Postes",it:"Pali"},hint:{en:"Which ends stand on a pole: both, the one the heading points away from, the one it points towards, or none (a line anchored on buildings).",fr:"Quelles extrémités reposent sur un poteau : les deux, celle dont le cap s'éloigne, celle vers laquelle il pointe, ou aucune (une ligne ancrée sur des bâtiments).",es:"Qué extremos se apoyan en un poste: ambos, aquel del que se aleja el rumbo, aquel hacia el que apunta, o ninguno (una línea anclada en edificios).",it:"Quali estremità poggiano su un palo: entrambe, quella da cui si allontana la direzione, quella verso cui punta, o nessuna (una linea ancorata a edifici)."},choices:[{value:"both",label:{en:"Both",fr:"Les deux",es:"Ambos",it:"Entrambi"}},{value:"start",label:{en:"Start",fr:"Début",es:"Inicio",it:"Inizio"}},{value:"end",label:{en:"End",fr:"Fin",es:"Fin",it:"Fine"}},{value:"none",label:{en:"None",fr:"Aucun",es:"Ninguno",it:"Nessuno"}}],effective:()=>"both"},{type:"number",key:"wire.diameterM",min:.001,max:.2,step:.001,unit:"m",effective:()=>.008,group:vi.WIRE,label:{en:"Strand thickness",fr:"Épaisseur du brin",es:"Grosor del hilo",it:"Spessore del filo"}},{type:"number",key:"wire.poleHeightM",min:.5,max:100,step:.1,unit:"m",group:vi.WIRE,label:{en:"Pole height",fr:"Hauteur des poteaux",es:"Altura de los postes",it:"Altezza dei pali"},hint:{en:"Empty: half a metre over the highest strand.",fr:"Vide : un demi-mètre au-dessus du brin le plus haut.",es:"Vacío: medio metro sobre el hilo más alto.",it:"Vuoto: mezzo metro sopra il filo più alto."}}]}}class pr{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=[pr.NONE,pr.SOLAR_VISUAL,pr.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return pr.ALL.find(e=>e.id===t)??pr.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class bf{constructor(t){this.names=t}name(t){return this.names[t.toLowerCase()]??t}stored(t){const e=t.trim().toLowerCase();for(const[i,n]of Object.entries(this.names))if(n.toLowerCase()===e)return i;return t.trim()}}class ao{constructor(t,e,i,n=new bf({}),s){this.labels=t,this.naming=e,this.said=i,this.tags=n,this.timeWords=s}entriesFor(t,e,i={}){const n=[];return this.addSummary(n,t),this.addObservation(n,t),this.addObserver(n,t,e),this.addLocation(n,t,e,i.groundElevationM,i.roadGradeDeg??0),this.addDecor(n,t,e,i),i.phenomena===!0&&this.addPhenomena(n,t,e),this.addTemporal(n,t),this.addWeather(n,t,e),this.addSound(n,t,e),n}push(t,e,i,n,s,r="",a={}){s===void 0||s===""||t.push({group:e,field:i,label:n,value:String(s),unit:r,color:a.color,fromSource:a.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 i=this.said.read(e.event.description)?.trim();if(!i)return;const n=i.split(/\s+/),s=n.length>ao.DESCRIPTION_WORDS?`${n.slice(0,ao.DESCRIPTION_WORDS).join(" ")}…`:i;this.push(t,"summary","description",this.labels.summaryDescription,s),t[t.length-1].full=i}addObservation(t,e){const i=e.event.tags;this.push(t,"observation","tags",this.labels.tags,i&&i.length>0?i.map(n=>this.tags.name(n)).join(", "):void 0)}filterName(t){return t===pr.SOLAR_VISUAL?this.labels.filterSolarVisual:t===pr.SOLAR_PHOTO?this.labels.filterSolarPhoto:t.name}addObserver(t,e,i){const n=e.observer;this.push(t,"observer","observerId",this.labels.observerId,n?.id),this.push(t,"observer","observerTitle",this.labels.observerTitle,this.said.read(n?.title)),this.push(t,"observer","observerLastName",this.labels.observerLastName,n?.lastName);const s=n?.firstNames;this.push(t,"observer","observerFirstNames",this.labels.observerFirstNames,s&&s.length>0?s.join(", "):void 0);const r=e.instrument;this.push(t,"observer","instrument",this.labels.instrument,this.naming.instrument(r));const a=e.exposure;this.push(t,"observer","exposureSeconds",this.labels.exposure,a===void 0?void 0:a<1?`1/${Math.round(1/a)}`:this.rounded(a,2),"s");const c=Le(e,i);if(c){const h=ki.focalLengthMmFor(r,c.fovDeg);h===void 0?this.push(t,"observer","focalLength",this.labels.fieldOfView,this.rounded(c.fovDeg,1),"°"):this.push(t,"observer","focalLength",this.labels.focalLength,this.rounded(h,1),"mm"),this.push(t,"observer","fNumber",this.labels.aperture,this.rounded(c.fNumber??r.fNumber,1)),this.push(t,"observer","focusDistance",this.labels.focusDistance,this.rounded(c.focusDistanceM,1),"m"),this.push(t,"observer","roll",this.labels.roll,this.roundedShown(c.rollDeg),"°");const l=pr.byId(c.filter);l!==pr.NONE&&this.push(t,"observer","filter",this.labels.filter,this.filterName(l))}}degreesMinutesSeconds(t,e,i){if(t===void 0||!Number.isFinite(t))return;const n=Math.round(Math.abs(t)*3600),s=Math.floor(n/3600),r=Math.floor(n%3600/60),a=n%60;return`${s}°${String(r).padStart(2,"0")}′${String(a).padStart(2,"0")}″ ${this.naming.point(t<0?i:e)}`}static WALK_KMH=7;static SPEED_SPAN_MS=1e3;static speedKmhAt(t,e){const i=ao.SPEED_SPAN_MS/2,n=Math.max(0,e-i),s=Le(t,n),r=Le(t,n+2*i);if(s?.lat===void 0||s.lng===void 0||r?.lat===void 0||r.lng===void 0)return;const a=(r.lat-s.lat)*111320,c=(r.lng-s.lng)*111320*Math.cos(s.lat*Math.PI/180);return Math.hypot(a,c)/(2*i/1e3)*3.6}addLocation(t,e,i,n,s){const r=e.event.place?.[0];this.push(t,"location","placeName",this.labels.placeName,r?.name);const a=Le(e,i);if(!a)return;this.push(t,"location","lat",this.labels.latitude,this.degreesMinutesSeconds(a.lat,0,180)),this.push(t,"location","lng",this.labels.longitude,this.degreesMinutesSeconds(a.lng,90,270));const c=this.rounded(a.headingDeg);this.push(t,"location","heading",this.labels.heading,c,a.headingDeg===void 0?"°":`° (${this.naming.point(a.headingDeg)})`),this.push(t,"location","pitch",this.labels.pitch,a.pitchDeg===void 0?void 0:this.rounded(a.pitchDeg+s),"°");const h=ao.speedKmhAt(e,i);h!==void 0&&h>ao.WALK_KMH&&this.push(t,"location","speed",this.labels.speed,Math.round(h),"km/h"),n===void 0?this.push(t,"location","elevation",this.labels.heightAboveGround,this.roundedShown(a.elevationM),"m"):this.push(t,"location","elevation",this.labels.elevation,this.rounded(n+a.elevationM),"m")}addDecor(t,e,i,n){const s=e.decor.find(h=>h.id===n.decorId);if(!s){if(n.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(s.title));const r=vr(s,i);this.push(t,"decor","decorBase.eastM",this.labels.decorEast,this.rounded(r.eastM,1),"m"),this.push(t,"decor","decorBase.northM",this.labels.decorNorth,this.rounded(r.northM,1),"m"),this.push(t,"decor","decorBase.altitudeM",this.labels.decorAltitude,this.roundedShown(r.altitudeM),"m"),this.push(t,"decor","decorBase.headingDeg",this.labels.decorHeading,this.rounded(r.headingDeg),"°"),O0(s,i)&&this.push(t,"decor","decorState.lit",this.labels.decorLit,"✓");const a=s.lights?.map(h=>h.id).join()??"",c=a===""?void 0:$m.find(h=>h.create().map(l=>l.id).join()===a);this.push(t,"decor","decorState.lightRig",this.labels.decorLights,c?.name),this.push(t,"decor","decorState.observerSide",this.labels.decorObserverSide,this.decorSideName(s.observerSide));for(const h of vi.of(s)?.parameters??[]){const l=Zr.read(s,h.key);if(l==null)continue;const u=h.type==="choice"?this.said.read(h.choices.find(d=>d.value===l)?.label)??String(l):l;this.push(t,"decor",`decorParam.${h.key}`,this.said.read(h.summary??h.label)??h.key,typeof u=="boolean"?u?"✓":"":u,h.type==="number"?h.unit:void 0)}}timeText(t){return this.timeWords?Ps.describeTime(t,this.timeWords.messages,this.timeWords.locale):jo(t)}addTemporal(t,e){const i=e.event;this.push(t,"temporal","obs-time",this.labels.observationTime,i.time&&this.timeText(i.time)),this.push(t,"temporal","obs-end-time",this.labels.observationEndTime,i.endTime&&this.timeText(i.endTime));const n=ub(i);this.push(t,"temporal","durationSeconds",this.labels.duration,this.roundedShown(n&&n/1e3,1),"s"),this.push(t,"temporal","timeZone",this.labels.utcOffset,i.timeZone),this.push(t,"temporal","utcOffsetHours",this.labels.utcOffset,this.rounded(i.utcOffsetHours,1),"UTC±h")}addWeather(t,e,i){const n=rh(e,i),r={fromSource:e.weatherSource!==void 0},a=this.showsPercent(n.cloudCover)||this.showsPercent(n.lowerCloudCover)||this.showsPercent(n.highCloudCover);this.push(t,"weather","cloudCover",this.labels.cloudCover,this.percentShown(n.cloudCover),"",r),this.push(t,"weather","highCloudCover",this.labels.highCloudCover,this.percentShown(n.highCloudCover),"",r),this.push(t,"weather","iceCrystalAlignment",this.labels.iceCrystalAlignment,this.showsPercent(n.highCloudCover)?this.percent(n.iceCrystalAlignment):void 0),this.push(t,"weather","rareIceCrystals",this.labels.rareIceCrystals,this.showsPercent(n.highCloudCover)?this.percent(n.rareIceCrystals):void 0),this.push(t,"weather","cloudDarkness",this.labels.cloudDarkness,a?this.percent(n.cloudDarkness):void 0,"",r),this.push(t,"weather","cloudBase",this.labels.cloudBase,a?this.rounded(n.cloudBaseM):void 0,"m",r);const c=n.precipitationType!=="none"&&this.showsPercent(n.precipitationIntensity);this.push(t,"weather","precipitationType",this.labels.precipitationType,c?this.precipitationName(n.precipitationType):void 0,"",r),this.push(t,"weather","precipitationIntensity",this.labels.precipitationIntensity,c?this.percent(n.precipitationIntensity):void 0,"",r),this.push(t,"weather","windDirection",this.labels.windDirection,this.shows(n.windSpeed,2)?this.rounded(n.windDirectionDeg):void 0,"°",r),this.push(t,"weather","windSpeed",this.labels.windSpeed,this.roundedShown(n.windSpeed,2),"m/s",r),n.storm&&this.push(t,"weather","storm",this.labels.storm,"✓","",r)}addSound(t,e,i){const n=db(e,i);n.kind!=="none"&&(this.push(t,"sound","soundKind",this.labels.soundKind,this.soundKindName(n.kind)),this.push(t,"sound","soundVolume",this.labels.soundVolume,this.percentShown(n.volume)),this.push(t,"sound","soundPitch",this.labels.soundPitch,this.roundedShown(n.pitchHz),"Hz"),this.push(t,"sound","soundSrc",this.labels.soundSrc,n.src))}addPhenomena(t,e,i){for(const n of e.timeline.sourceIds){const s=e.timeline.getInterpolatedShapeAt(i,n),r=s?.angular,a=r?`${this.rounded(r.widthDeg,2)} × ${this.rounded(r.heightDeg,2)}°`:void 0;this.push(t,"phenomenon",`shape:${n}`,this.said.read(s?.title)??n,a)}for(const n of e.interpretation?.bodies??[]){const s=n.track.find(a=>a.sizeM?.widthM!==void 0)?.sizeM?.widthM,r=n.model.id??n.model.url?.replace(/^.*\//,"");this.push(t,"phenomenon",`body:${n.id}`,this.said.read(n.title)??n.id,[r,s!==void 0?`${this.rounded(s,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"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}}}Ot.register(En,()=>new Zo);Ot.register(Kh,()=>new Rh);Ot.register(gr,()=>new _1);Ot.register(qh,()=>new Ih);Ot.register(Mu,()=>new T1);Ot.register(Zh,()=>new Su);Ot.register(Yh,()=>new xu);Ot.register(Jh,()=>new Eu);Ot.register(Ro,()=>new jh);Ot.register($h,()=>new bu);Ot.register(Ss,()=>new Oi);Ot.register(mo,()=>new Tu);Ot.register(hn,()=>new Jo);Ot.register(go,()=>new Ru);Ot.register(yu,()=>new R1);Ot.register(vo,()=>new Iu);Ot.register(po,()=>new _u);Ot.register(Mo,()=>new Du);Ot.register(gc,()=>new Cu);Ot.register(fo,()=>new Au);Ot.register(hs,()=>new Ye);Ot.register(Aa,()=>new Nu);Ot.register(cn,()=>new Qt);Ot.register(_a,()=>new Lu);Ot.register(wu,()=>new D0);Ot.register(Ta,()=>new Uu);Ot.register(Ea,()=>new Pu);Ot.register(Ra,()=>new ku);Ot.register(Uf,()=>new XE);Ot.register(Sa,()=>new Ou);class Es{constructor(t){this.preferences=t}read(t){var e,i;if(t===void 0)return;if(typeof t=="string")return t===""?void 0:t;for(const s of this.preferences){const r=(e=t[s])!==null&&e!==void 0?e:t[Es.base(s)];if(r)return r}const n=new Set(this.preferences.map(s=>Es.base(s)));for(const[s,r]of Object.entries(t))if(r&&n.has(Es.base(s)))return r;return(i=Object.values(t).find(s=>s))!==null&&i!==void 0?i:void 0}write(t,e,i){var n,s;const r=e?.trim()?e.trim():void 0;if(t===void 0||typeof t=="string")return r;const a={...t},c=(s=(n=Object.keys(a).find(h=>h===i))!==null&&n!==void 0?n:Object.keys(a).find(h=>Es.base(h)===Es.base(i)))!==null&&s!==void 0?s:i;return r===void 0?delete a[c]:a[c]=r,Object.keys(a).length===0?void 0:a}static base(t){return t.toLowerCase().split("-")[0]}}Es.any=new Es([]);var CM;(function(o){o.abductee="abductee",o.actor="actor",o.artist="artist",o.anthropologist="anthropologist",o.archeologist="archeologist",o.astronaut="astronaut",o.astronomer="astronomer",o.astrologist="astrologist",o.astrophysicist="astrophysicist",o.banker="banker",o.barman="barman",o.biologist="biologist",o.biochemist="biochemist",o.biophysicist="biophysicist",o.bishop="bishop",o.businessman="businessman",o.botanist="botanist",o.cameraman="cameraman",o.chemist="chemist",o.contactee="contactee",o.cryptozoologist="cryptozoologist",o.dentist="dentist",o.director="director",o.diplomat="diplomat",o.diver="diver",o.electronics="electronics",o.engineer="engineer",o.ethnologist="ethnologist",o.exobiologist="exobiologist",o.farmer="farmer",o.firefighter="firefighter",o.flightAttendant="flightAttendant",o.geologist="geologist",o.geophysicist="geophysicist",o.geographer="geographer",o.historian="historian",o.houseWife="houseWife",o.hypnotherapist="hypnotherapist",o.illusionist="illusionist",o.journalist="journalist",o.judge="judge",o.lawyer="lawyer",o.leader="leader",o.librarian="librarian",o.logger="logger",o.mathematician="mathematician",o.mechanic="mechanic",o.meteorologist="meteorologist",o.military="military",o.musician="musician",o.neurologist="neurologist",o.neuroscientist="neuroscientist",o.neuropsychiatrist="neuropsychiatrist",o.nurse="nurse",o.oceanographer="oceanographer",o.painter="painter",o.parapsychologist="parapsychologist",o.philosopher="philosopher",o.photographer="photographer",o.physician="physician",o.physicist="physicist",o.pilot="pilot",o.politician="politician",o.policeman="policeman",o.priest="priest",o.producer="producer",o.prospector="prospector",o.psychologist="psychologist",o.psychiatrist="psychiatrist",o.radioastronomer="radioastronomer",o.radioamateur="radioamateur",o.salesman="salesman",o.sailor="sailor",o.sociologist="sociologist",o.softwareEngineer="softwareEngineer",o.stuntman="stuntman",o.taxiDriver="taxiDriver",o.teacher="teacher",o.telegrapher="telegrapher",o.truckDriver="truckDriver",o.ufologist="ufologist",o.ufoWitness="ufoWitness",o.ufoWitness2="ufoWitness2",o.worker="worker",o.writer="writer"})(CM||(CM={}));var OM;(function(o){o.neutral="neutral",o.male="male",o.female="female"})(OM||(OM={}));const fA="modulepreload",pA=function(o,t){return new URL(o,t).href},PM={},Ie=function(t,e,i){let n=Promise.resolve();if(e&&e.length>0){let r=function(l){return Promise.all(l.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const a=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),h=c?.nonce||c?.getAttribute("nonce");n=r(e.map(l=>{if(l=pA(l,i),l in PM)return;PM[l]=!0;const u=l.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!i)for(let m=a.length-1;m>=0;m--){const g=a[m];if(g.href===l&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":fA,u||(p.as="script"),p.crossOrigin="",p.href=l,h&&p.setAttribute("nonce",h),document.head.appendChild(p),u)return new Promise((m,g)=>{p.addEventListener("load",m),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return n.then(r=>{for(const a of r||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})};class mA extends Error{constructor(t,e){super(t),this.cause=e}}class D1 extends mA{constructor(t=D1.defaultMessage,e){super(t,e)}}D1.defaultMessage="Assertion failed";var NM;(function(o){o.country="country",o.region="region",o.department="department",o.city="city",o.company="company"})(NM||(NM={}));var LM;(function(o){o.at="at",o.au="au",o.ar="ar",o.be="be",o.br="br",o.ca="ca",o.ch="ch",o.cn="cn",o.cl="cl",o.co="co",o.cy="cy",o.de="de",o.dk="dk",o.do="do",o.dz="dz",o.gr="gr",o.ec="ec",o.eg="eg",o.es="es",o.fi="fi",o.fr="fr",o.ga="ga",o.ge="ge",o.hu="hu",o.in="in",o.ie="ie",o.ir="ir",o.il="il",o.it="it",o.jp="jp",o.kr="kr",o.ma="ma",o.mx="mx",o.my="my",o.mz="mz",o.nl="nl",o.no="no",o.nz="nz",o.pa="pa",o.pe="pe",o.ph="ph",o.pl="pl",o.pt="pt",o.ro="ro",o.ru="ru",o.sc="sc",o.tr="tr",o.ua="ua",o.uk="uk",o.us="us",o.sa="sa",o.se="se",o.su="su",o.tn="tn",o.tw="tw",o.ve="ve",o.za="za"})(LM||(LM={}));function C1(o,t){for(const e of o){const i=e.toLowerCase().split("-")[0];if(t.includes(i))return i}return"en"}class Ao{static preferencesFor(t){const e=navigator.languages??[],i=this.declaredFor(t);return i?[i,...e]:e}static declaredFor(t){for(let e=t;e;){const i=e.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=e.getRootNode();e=n instanceof ShadowRoot?n.host:void 0}}}const gA="Global Meteor Network",vA="https://globalmeteornetwork.org/data/",MA="“Thunder” by Jerimee",yA="https://creativecommons.org/licenses/by/3.0/",wA="CC BY 3.0";class In{static fill(t,e){t.innerHTML="";const i=d=>t.appendChild(d),n=e.currentTerrainAttribution;n&&i(In.text(n));const s=e.currentRoadAttribution;s&&i(In.text(s));const r=e.currentWaterAttribution;r&&i(In.text(r));const a=e.currentRailwayAttribution;a&&i(In.text(a));const c=e.ufoElement.observerMapCredit;c&&!n?.includes(c)&&i(In.text(c));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",p=document.createElement("li");d.sourceUrl?p.append(In.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):p.textContent=`${d.title}${f} (${d.license})`,i(p)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(In.link(d.creditUrl,d.credit)):f.textContent=d.credit,i(f)}if(e.ufoElement.sighting.traces.length>0){const d=new Es(Ao.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(p=>d.read(p.source)).filter(p=>!!p));for(const p of f)i(In.text(p))}const h=e.satelliteState;if(h.status==="ready"&&h.credit){const d=document.createElement("li");d.appendChild(In.link(h.creditUrl??"",h.credit)),i(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(In.link(vA,gA),document.createTextNode(" (CC BY 4.0)")),i(d)}const l=e.aircraftState;if(l.status==="ready"&&l.shown>0){const d=document.createElement("li");if(d.appendChild(In.link(l.creditUrl,l.credit)),i(d),l.trailCredit){const f=document.createElement("li");f.appendChild(In.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(f)}}const u=In.text(`${MA} (`);u.append(In.link(yA,wA),document.createTextNode(")")),i(u)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const i=document.createElement("a");return i.href=t,i.target="_blank",i.rel="noopener",i.textContent=e,i}}const bA=[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async o=>{const{CoverageAssessor:t}=await Ie(async()=>{const{CoverageAssessor:e}=await import("./CoverageAssessor-C7k3p3iN.js");return{CoverageAssessor:e}},[],import.meta.url);return new t().assess(o)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async o=>{const{HynekAssessor:t}=await Ie(async()=>{const{HynekAssessor:e}=await import("./HynekAssessor-B8Iw0Cbz.js");return{HynekAssessor:e}},__vite__mapDeps([0,1]),import.meta.url);return new t().assess(o)}})},{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 o=>{const{BallesterGuaspAssessor:t}=await Ie(async()=>{const{BallesterGuaspAssessor:e}=await import("./BallesterGuaspAssessor-CCjRjJck.js");return{BallesterGuaspAssessor:e}},__vite__mapDeps([2,1,3]),import.meta.url);return new t().assess(o)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async o=>{const{PoherAssessor:t}=await Ie(async()=>{const{PoherAssessor:e}=await import("./PoherAssessor-CwQN9pB1.js");return{PoherAssessor:e}},[],import.meta.url);return new t().assess(o)}})}];class O1{constructor(t){this.labels=t}async read(t){const e=[],i=new Set;for(const n of bA){let s;try{s=await n.create().assess(t)}catch{continue}for(const a of s.criteria)a.basis===void 0&&!a.unsupported&&i.add(a.id);const r=s.score===void 0?s.verdict===void 0?"":this.verdictName(n.id,s.verdict):`${Math.round(s.score*100)}%`;r!==""&&e.push({group:"assessment",field:n.id,label:this.labels.assessmentNames[n.id]??n.name,value:r,unit:"",fromSource:!1,about:n.create().about,...s.factors?{detail:O1.factorsText(s.factors)}:{}})}return{entries:e,unanswered:i}}static factorsText(t){const e={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(t).map(([i,n])=>`${e[i]??i} ${n.toFixed(2)}`).join(" × ")}verdictName(t,e){return this.labels.assessmentVerdicts[`${t}.${e}`]??e.toUpperCase()}}const Mb=Math.PI/180,Hf=111320;function de(o,t,e,i){const n=Hf*Math.cos(e*Mb),s=(o-e)*Hf;return{x:(t-i)*n,z:-s}}function As(o,t,e,i){const n=Hf*Math.cos(e*Mb),s=-t,r=o;return{lat:e+s/Hf,lng:i+r/n}}class uh{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,i){const n=t.event.place?.[0],s=t.observerTrack;if(!n)return 0;const r=m=>{const g=s.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const v=de(g.lat,g.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:g.headingDeg}},a=r(e-uh.HALF_SPAN_MS),c=r(e+uh.HALF_SPAN_MS),h=r(e);if(!a||!c||!h)return 0;const l=Math.hypot(c.eastM-a.eastM,c.northM-a.northM),u=2*uh.HALF_SPAN_MS/1e3;if(l/u<uh.MIN_SPEED_MS)return 0;const d=i.heightAt(c.eastM,c.northM)-i.heightAt(a.eastM,a.northM),f=Math.atan2(d,l)*180/Math.PI;if(h.heading===void 0)return f;const p=Math.atan2(c.eastM-a.eastM,c.northM-a.northM)*180/Math.PI;return f*Math.max(0,Math.cos((h.heading-p)*Math.PI/180))}}class hc{static sessionDeclared=!1;static unlock(t){if(hc.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(!(hc.sessionDeclared||typeof navigator>"u")){hc.sessionDeclared=!0;try{const t=navigator.audioSession;t&&(t.type="playback")}catch{}}}}const xA=.08,kM=.15,UM=2,SA=2e3;class EA{context;noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}hc.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);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(n=>n.inside||n.distanceM<SA),i=new Set(e.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of e){const s=this.voices.get(n.id)??this.build(t,n.id);this.retarget(t,s,n)}}build(t,e){const i=t.createGain();i.gain.value=0;const n=t.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(t));const s=t.createOscillator();s.type="sawtooth";const r=t.createOscillator();r.type="sine";const a=t.createGain(),c=t.createBiquadFilter();c.type="lowpass",c.frequency.value=900,s.connect(c),r.connect(c),c.connect(a).connect(n);const h=()=>{const b=t.createBufferSource();return b.buffer=this.noise(t),b.loop=!0,b.loopStart=Math.random()*UM*.5,b},l=h(),u=t.createBiquadFilter();u.type="bandpass",u.Q.value=4;const d=t.createGain();l.connect(u).connect(d).connect(n);const f=h(),p=t.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const m=t.createGain();f.connect(p).connect(m).connect(n);const g=h(),v=t.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const M=t.createGain();g.connect(v).connect(M).connect(n);const w=[s,r,l,f,g];for(const b of w)b.start();const y={nodes:[i,n,a,c,u,d,p,m,v,M,...w],sources:w,firing:s,crank:r,knock:u,engineGain:a,knockGain:d,roadGain:m,windGain:M,cabin:n,output:i};return this.voices.set(e,y),y}retarget(t,e,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:c}){const h=t.currentTime,l=(M,w)=>M.setTargetAtTime(w,h,xA),u=n.rpm/60,d=u*i.cylinders/2,f=Math.min(1,n.rpm/i.shiftUpRpm),p=Math.min(1.5,n.speedMps/30);l(e.firing.frequency,d),l(e.crank.frequency,u),l(e.knock.frequency,d*3),l(e.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*f)*.3),l(e.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),l(e.roadGain.gain,i.roadGain*p**1.5*.8);const m=!r||a;l(e.windGain.gain,p**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+c/60);l(e.cabin.frequency,g);const v=r?.5:Math.min(1,8/Math.max(c,1));l(e.output.gain,v*s)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const i=this.context;i&&(e.output.gain.setTargetAtTime(0,i.currentTime,kM/3),setTimeout(()=>{for(const n of e.sources)try{n.stop()}catch{}for(const n of e.nodes)n.disconnect()},kM*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*UM,t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=e,e}}class Fu{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 Fu.BY_KIND[t??"generic"]??Fu.BY_KIND.generic}}class tc{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,i,n){const s=tc.SAMPLE_MS,r=[];for(let h=i;h<=n+s/2;h+=s){const l=e(h-s/2),u=e(h+s/2);if(!l||!u)return;r.push(Math.hypot(u.eastM-l.eastM,u.northM-l.northM)/(s/1e3))}const a=[];let c=1;for(let h=0;h<r.length;h++){const l=r[h],u=(r[Math.min(h+1,r.length-1)]-r[Math.max(h-1,0)])/(2*s/1e3);if(l<tc.STANDING_MPS){c=1,a.push({speedMps:l,rpm:t.idleRpm,load:.1,gear:0});continue}const d=l*3.6,f=v=>d/t.kmhPer1000Rpm[v-1]*1e3;for(;c<t.kmhPer1000Rpm.length&&f(c)>t.shiftUpRpm;)c++;for(;c>1&&f(c)<t.shiftDownRpm;)c--;const p=Math.max(f(c),t.idleRpm*(1+.3*Math.min(1,l/3))),m=.15+.5*Math.min(1,(l/35)**2),g=u>.15?Math.min(1,m+u/2.5):u<-.3?.05:m;a.push({speedMps:l,rpm:p,load:g,gear:c})}return new tc(a,i)}at(t){const e=(t-this.startMs)/tc.SAMPLE_MS,i=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(e-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class Gf{drives=new Map;at(t,e){const i=[],n=t.event.place?.[0],s=h=>{const l=t.observerTrack.getInterpolatedPoseAt(h),u=l?.lat??n?.lat,d=l?.lng??n?.lng;if(u===void 0||d===void 0||!n)return;const f=de(u,d,n.lat,n.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),a=t.vehicle;if(a){const h=Fu.of(a.kind),l=this.drive(`observer:${a.kind}`,Gf.trackKey(t),()=>tc.of(h,s,0,r));l&&i.push({id:"observer",profile:h,state:l.at(e),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const c=s(e);for(const h of t.decor){if(!h.engine||!c)continue;const l=Fu.of(h.engine.kind),u=m=>{const g=vr(h,m);return{eastM:g.eastM,northM:g.northM}},d=this.drive(`decor:${h.id}`,Gf.decorKey(h,r),()=>tc.of(l,u,0,r));if(!d)continue;const f=vr(h,e),p=Math.hypot(f.eastM-c.eastM,f.northM-c.northM,f.altitudeM);i.push({id:`decor:${h.id}`,profile:l,state:d.at(e),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return i}drive(t,e,i){const n=this.drives.get(t);if(n&&n.key===e)return n.drive;const s=i();return this.drives.set(t,{key:e,drive:s}),s}static trackKey(t){return t.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const FM=864e5,zM=4e4;function AA(o){const t=Math.floor(o.getTime()/FM);return{elapsedMs:o.getTime()-t*FM,shiftM:{x:BM.unit(t,2654435761)*zM,z:BM.unit(t,2246822507)*zM}}}class BM{static unit(t,e){let i=Math.imul(t|0,e)^e;return i=Math.imul(i^i>>>15,739982445),i=Math.imul(i^i>>>12,695872825),i^=i>>>15,(i>>>0)/4294967295*2-1}}function HM(o,t,e,i,n,s,r){const a=i?.lat!==void 0&&i.lng!==void 0&&n?.lat!==void 0&&n.lng!==void 0?de(n.lat,n.lng,i.lat,i.lng):{x:0,z:0};if(r){const l=t.getInterpolatedWeatherAt(0)??e,u=s===void 0?void 0:l.cloudLayers?.find(p=>p.id===s),d=(u?.windDirectionDeg??l.windDirectionDeg)*Math.PI/180,f=(u?.windSpeed??l.windSpeed)*r.elapsedMs/1e3;a.x+=r.shiftM.x-Math.sin(d)*f,a.z+=r.shiftM.z+Math.cos(d)*f}const c=Math.max(0,o),h=[0,...t.allKeyframes.map(l=>l.t).filter(l=>l>0&&l<c),c];for(let l=1;l<h.length;l++){const u=h[l-1],d=h[l]-u;if(d===0)continue;const f=32;for(let p=0;p<=f;p++){const m=t.getInterpolatedWeatherAt(u+d*p/f)??e,g=s===void 0?void 0:m.cloudLayers?.find(y=>y.id===s),v=(g?.windDirectionDeg??m.windDirectionDeg)*Math.PI/180,M=p===0||p===f?1:p%2===0?2:4,w=(g?.windSpeed??m.windSpeed)*d/1e3/f/3*M;a.x-=Math.sin(v)*w,a.z+=Math.cos(v)*w}}return a}const _A="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==",TA=`
668
668
  <div class="stage" id="stage">
669
669
  <div class="frame" id="frame">
670
670
  <canvas id="scene-canvas"></canvas>
@@ -2400,10 +2400,10 @@ canvas[data-cursor="rotate"] {
2400
2400
  }
2401
2401
  `;class Ph{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const i of t.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||e.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(e.length===0){const i=t.event.place?.[0];if(!i)return;e.push({t:0,lat:i.lat,lng:i.lng})}return new Ph(e)}static TRAVEL_M=50;get travels(){return this.spanM>Ph.TRAVEL_M}get moved(){return this.spanM>Ph.STATIONARY_M}get spanM(){const t=this.box,e=(t.south+t.north)/2,i=(t.west+t.east)/2;return Math.max(Math.abs(de(e,t.east,e,t.west).x),Math.abs(de(t.north,i,t.south,i).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:i,lng:n}=this.center,s=Math.max(this.spanM*(1+e),t)/2;return{north:As(0,-s,i,n).lat,south:As(0,s,i,n).lat,east:As(s,0,i,n).lng,west:As(-s,0,i,n).lng}}get box(){const t=this.points.map(i=>i.lat),e=this.points.map(i=>i.lng);return{south:Math.min(...t),north:Math.max(...t),west:Math.min(...e),east:Math.max(...e)}}}class $s{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){if(t.instrument.mounted)return;const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>$s.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new $s(Math.max(1-(t.instrument.stabilization??0),$s.GAZE_DRIFT_SHARE),i)}offsetAt(t){const e=t/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*e+d),[s,r,a,c,h,l]=$s.HZ;return{eastM:i*$s.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*$s.SWAY_M*(.6*n(a,2.2)+.4*n(h,.8)),upM:i*$s.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*$s.DRIFT_YAW_DEG*(.6*n(l,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*$s.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*$s.DRIFT_ROLL_DEG*n(s,2.9)}}}class ni{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){const e=Ph.of(t);if(!e||e.points.length<2)return;const i=[];let n=0;for(let s=1;s<e.points.length;s++){const r=e.points[s-1],a=e.points[s],c=(a.t-r.t)/1e3;if(c<=0)continue;const h=de(a.lat,a.lng,r.lat,r.lng),l=h.x,u=-h.z,d=Math.hypot(l,u),f=d/c,p=ni.stepHzFor(f);i.push({startMs:r.t,endMs:a.t,speedMPerS:f,eastUnit:d>0?l/d:0,northUnit:d>0?u/d:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*c}for(let s=0;s<i.length;s++){const r=i[s-1],a=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=a===void 0||a.stepHz===0}if(i.some(s=>s.stepHz>0))return new ni(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=ni.of(t)?.offsetAt(e)??ni.STILL;return i?n:ni.add(n,$s.of(t)?.offsetAt(e))}static stepHzFor(t){return t<ni.SLOWEST_WALK_M_PER_S||t>ni.FASTEST_WALK_M_PER_S?0:ni.REFERENCE_STEP_HZ*Math.pow(t/ni.REFERENCE_SPEED_M_PER_S,ni.CADENCE_EXPONENT)}offsetAt(t){return ni.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/ni.REFERENCE_SPEED_M_PER_S,n=(a,c,h,l)=>{if(a<0||a>ni.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/ni.JOLT_DECAY_S)*Math.sin(2*Math.PI*ni.JOLT_HZ*u),f=l*c*i*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-l*h*i*d*this.rotationPassed,yawDeg:0}},s=e.rampsOut?n(t-e.endMs,ni.STOP_LURCH_M,ni.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,ni.START_LURCH_M,ni.START_PITCH_DEG,-1):void 0;if(r)return r}}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(c=>t>=c.startMs&&t<=c.endMs);if(!e||e.stepHz===0)return ni.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=ni.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/ni.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:ni.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:ni.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:ni.HEAD_YAW_DEG*a*Math.cos(n/2)}}amplitudeAt(t,e){const i=1e3/t.stepHz,n=Math.min(i,(t.endMs-t.startMs)/2);if(n<=0)return 1;const s=e-t.startMs,r=t.endMs-e,a=Math.min(t.rampsIn?s/n:1,t.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class CA{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 i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}this.onFrame(t,e)}}const yb=["nw","n","ne","e","se","s","sw","w"],OA=24,ld=8,PA=3,NA=8;function ud(o,t,e){const i=o.x-t.x,n=o.y-t.y,s=Math.cos(e),r=Math.sin(e);return{x:t.x+i*s-n*r,y:t.y+i*r+n*s}}function vl(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const LA={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 Us{static handlePointsFor(t){const{x:e,y:i,width:n,height:s}=t.bounds,r={nw:{x:e,y:i},n:{x:e+n/2,y:i},ne:{x:e+n,y:i},e:{x:e+n,y:i+s/2},se:{x:e+n,y:i+s},s:{x:e+n/2,y:i+s},sw:{x:e,y:i+s},w:{x:e,y:i+s/2},rotate:{x:e+n/2,y:i-OA}},a=vl(t.bounds),c={};for(const h of Object.keys(r))c[h]=ud(r[h],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...yb,"rotate"]){const s=Us.handlePointsFor(t);for(const r of n)if(Math.hypot(e.x-s[r].x,e.y-s[r].y)<=i)return r}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 n=((Us.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(t,e,i,n){const s=vl(t),r=ud(n,s,-e),{x:a,y:c,width:h,height:l}=t,u=LA[i];let d=a,f=c,p=a+h,m=c+l;return u.left&&(d=Math.min(r.x,p-ld)),u.right&&(p=Math.max(r.x,d+ld)),u.top&&(f=Math.min(r.y,m-ld)),u.bottom&&(m=Math.max(r.y,f+ld)),{x:d,y:f,width:p-d,height:m-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=t.bounds,r=Us.resizeBounds(t.bounds,t.angle,e,i);if(t.kind==="oval")return{...t,bounds:r};const a=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...t,bounds:r,points:t.points.map(h=>({x:h.x*a,y:h.y*c}))}}static rotateShape(t,e){const i=vl(t.bounds),n=Math.atan2(e.y-i.y,e.x-i.x)+Math.PI/2;return{...t,angle:n}}static groupBoundsFor(t){const e=Math.min(...t.map(r=>r.x)),i=Math.min(...t.map(r=>r.y)),n=Math.max(...t.map(r=>r.x+r.width)),s=Math.max(...t.map(r=>r.y+r.height));return{x:e,y:i,width:n-e,height:s-i}}static vertexPointsFor(t){const e=vl(t.bounds);return t.points.map(i=>ud({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=NA){const n=Us.vertexPointsFor(t);let s,r=i;return n.forEach((a,c)=>{const h=Math.hypot(e.x-a.x,e.y-a.y);h<=r&&(r=h,s=c)}),s}static toLocalPoint(t,e){const i=vl(t.bounds),n=ud(e,i,-t.angle);return{x:n.x-t.bounds.x,y:n.y-t.bounds.y}}static moveVertex(t,e,i){const n=t.points.map((u,d)=>d===e?Us.toLocalPoint(t,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),a=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),h={x:t.bounds.x+s,y:t.bounds.y+r,width:a-s,height:c-r},l=n.map(u=>({x:u.x-s,y:u.y-r}));return{...t,bounds:h,points:l}}static insertVertexNear(t,e){const i=Us.toLocalPoint(t,e),{points:n}=t;let s=n.length-1,r=1/0;for(let c=0;c<n.length;c++){const h=n[c],l=n[(c+1)%n.length],u=Us.distanceToSegment(i,h,l);u<r&&(r=u,s=c)}const a=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...t,points:a}}static distanceToSegment(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((t.x-e.x)*n+(t.y-e.y)*s)/r)),c=e.x+a*n,h=e.y+a*s;return Math.hypot(t.x-c,t.y-h)}static deleteVertex(t,e){return t.points.length<=PA?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const Ym=6,dd=Ym/2,GM=20,VM=24,WM=9,XM=6,$M=7,YM=6,Er=4;class tl{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:i,width:n,height:s}=t.bounds,r=e+n/2,a=i+s/2,c=t.angle%(2*Math.PI)!==0,h=Math.hypot(n,s)/2,l=c?h:n/2,u=c?h:s/2,d=Math.max(n,s)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+WM*f),YM*f)-d:0,m=f>0?d*(1+$M*f)-d:0,g=3*VM*(t.blur??0)+1.5*GM*t.haloScale,v=Math.max(p,m,0)+g+2;return{x:r-l-v,y:a-u-v,width:2*(l+v),height:2*(u+v)}}paintInto(t,e,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-e.x,-e.y);const s=t.selected?{...t,selected:!1}:t;n?this.paintGhost(s,1.5):this.paintShape(s),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(${(VM*e).toFixed(2)}px)`);const i=t.brightness??0;i>0&&this.paintDazzle(t,i),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:i,y:n,width:s,height:r}=t.bounds,a=i+s/2,c=n+r/2,h=Math.max(s,r)/2,l=Math.max(h*(1+WM*e),YM*e);if(l<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(a,c,0,a,c,l);for(let d=0;d<=XM;d++){const f=d/XM,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(t.color,p*e*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(a,c,l,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=h*(1+$M*e);this.ctx.lineWidth=Math.max(1,h*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const p=f/this.starPoints*Math.PI*2+this.roll,m=a+Math.cos(p)*d,g=c+Math.sin(p)*d,v=this.ctx.createLinearGradient(a,c,m,g);v.addColorStop(0,this.withAlpha(t.color,e*.55)),v.addColorStop(.35,this.withAlpha(t.color,e*.22)),v.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=v,this.ctx.beginPath(),this.ctx.moveTo(a,c),this.ctx.lineTo(m,g),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const i=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!i)return t.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*e);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),n=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!n)return t;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.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:i,width:n,height:s}=t.bounds,r=n/2,a=s/2;this.ctx.ellipse(e+r,i+a,r,a,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:n,height:s}=t.bounds;this.ctx.save(),this.ctx.translate(e+n/2,i+s/2),this.ctx.rotate(t.angle),this.ctx.translate(-n/2,-s/2),t.points.forEach((r,a)=>{a===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=GM*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(Us.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of Us.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Er,Er,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(Us.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,i){const n=this.ctx;if(n.save(),t&&t.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(t[0].x,t[0].y);for(const s of t.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of e){const r=tl.landmarkColour(s.residualDeg),a=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=a+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Er+2,Er+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,Er,Er,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Er+2,Er+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Er+5,s.picture.y-Er-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}paintGhosts(t,e,i){const n=this.ctx;n.save();const s=(c,h,l,u=[])=>{n.setLineDash(u),n.lineWidth=l+2,n.strokeStyle="rgba(0, 0, 0, 0.6)",c(),n.lineWidth=l,n.strokeStyle=h,c(),n.setLineDash([])},r=(c,h)=>()=>{n.beginPath(),n.arc(c.x,c.y,h,0,2*Math.PI),n.stroke()},a=(c,h,l)=>()=>{const[u,d]=l?[h,h]:[h,0];n.beginPath(),n.moveTo(c.x-u,c.y-d),n.lineTo(c.x+u,c.y+d),n.moveTo(c.x+d,c.y-u),n.lineTo(c.x-d,c.y+u),n.stroke()};for(const c of t)s(()=>{n.beginPath(),n.moveTo(c.ghost.x,c.ghost.y),n.lineTo(c.light.x,c.light.y),n.stroke()},"rgba(255, 255, 255, 0.85)",1,[4,4]),s(r(c.light,7),"#ffffff",1.5),s(r(c.ghost,Math.max(9,c.ghostRadius)),"#ffd23f",2);e&&s(a(e,8,!1),"#ffd23f",2),i&&s(a(i,5,!0),"rgba(255, 255, 255, 0.7)",1),n.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const a=r.measureText(t).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(e-3,i-2,a+6,s+4),r.fillStyle=n,r.fillText(t,e,i),r.restore()}paintGroupHandles(t){this.paintHandleFrame(Us.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 i of yb){const n=t[i];this.ctx.fillRect(n.x-dd,n.y-dd,Ym,Ym)}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,dd+1,dd+1,0,0,2*Math.PI),this.ctx.fill())}}const KM=.05,qM=.08,ZM=2,JM=3,kA=14,UA=.02;class FA{context;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}}hc.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 i=++this.voiceToken;e.startsWith("src:")?this.buildRecordedVoice(t.src,e,i):this.voice=this.buildSynthesizedVoice(t,e)}this.applyTo(this.voice,t)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const i=this.context;if(!t||!i)return;const n=i.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,n,KM);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,KM)}buildSynthesizedVoice(t,e){const i=this.context;if(i)switch(t.kind){case"hum":return this.buildHum(i,e);case"whistle":return this.buildWhistle(i,e);case"rumble":return this.buildRumble(i,e);case"crackle":return this.buildCrackle(i,e);default:return}}buildHum(t,e){const i=t.createOscillator();i.type="sawtooth";const n=t.createOscillator();n.type="sawtooth";const s=t.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=t.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:n.frequency,ratio:1.006},{param:s.frequency,ratio:6}]}}buildWhistle(t,e){const i=t.createOscillator();i.type="sine";const n=t.createOscillator();n.type="sine",n.frequency.value=5;const s=t.createGain(),r=t.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(t,e){const i=t.createBufferSource();i.buffer=this.brownNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=t.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(t)),i.start(),{key:e,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(t,e){const i=t.createBufferSource();i.buffer=this.whiteNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=t.createGain();s.gain.value=0;const r=t.createBufferSource();r.buffer=this.crackleEnvelope(t),r.loop=!0;const a=t.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(t)),i.start(),r.start(),{key:e,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(t,e,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(t)}catch(c){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",c);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();a.gain.value=0,r.connect(a).connect(this.output(n)),r.start(),this.voice={key:e,nodes:[a],sources:[r],volumeParam:a.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 i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*ZM),t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*ZM),t.sampleRate),i=e.getChannelData(0);let n=0,s=0;for(let r=0;r<i.length;r++)n=(n+.02*(Math.random()*2-1))/1.02,i[r]=n,s=Math.max(s,Math.abs(n));if(s>0)for(let r=0;r<i.length;r++)i[r]/=s;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*JM),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(UA*t.sampleRate)),s=Math.round(JM*kA);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let h=0;h<n&&a+h<i.length;h++)i[a+h]=Math.max(i[a+h],c*(1-h/n))}this.crackleBuffer=e}return this.crackleBuffer}stopVoice(){const t=this.voice,e=this.context;if(this.voice=void 0,!t||!e)return;const i=e.currentTime;t.volumeParam.cancelScheduledValues(i),t.volumeParam.setTargetAtTime(0,i,qM/3);const n=i+qM;for(const s of t.sources){s.onended=()=>{s.disconnect();for(const r of t.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of t.nodes)r.disconnect()}}}}class Pr{static KINDS=["beams","launches","reentries"];static isEmpty(t){return!t||Pr.KINDS.every(e=>!t[e]?.length)}static written(t){if(Pr.isEmpty(t))return;const e={};for(const i of Pr.KINDS)t[i]?.length&&(e[i]=t[i]);return e}static read(t,e){const i=e,n={};for(const r of Pr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&Pr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...h}=i;s=Pr.isReading(h)?h:void 0}return{skyEvents:Pr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function ql(o){return[...o].sort((t,e)=>t.t-e.t)}function lp(o,t){let e;for(const i of ql(o)){if(i.t>t)break;e=i}return e}const up=Math.PI/180,fd=180/Math.PI;class $r{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*up/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new $r(t.projection,e,i)}degToPx(t){const e=t*up;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*fd:2*Math.atan(t/(2*this.focalPx))*fd}angleDegToRadiusPx(t){const e=t*up;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*fd:Math.atan(t/this.focalPx)*fd}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(ci.angularWidthDeg(t))}}class ln{static fovOf(t,e){return Le(t,e)?.fovDeg??ki.fieldOfViewDeg(t.instrument)}static toAngular(t){this.eachKeyframe(t,(e,i)=>{const n=i.ofBounds(e.bounds);return e.angular?.widthDeg===n.widthDeg&&e.angular.heightDeg===n.heightDeg?e:{...e,angular:n}})}static toBounds(t){this.eachKeyframe(t,(e,i)=>this.sizedFromAngle(e,i))}static sizedFromAngle(t,e){if(!t.angular)return t;const{width:i,height:n}=e.toBoundsSize(t.angular),s={x:t.bounds.x+(t.bounds.width-i)/2,y:t.bounds.y+(t.bounds.height-n)/2,width:i,height:n};if(t.kind!=="polygon")return{...t,bounds:s};const r=t.bounds.width===0?1:i/t.bounds.width,a=t.bounds.height===0?1:n/t.bounds.height;return{...t,bounds:s,points:t.points.map(c=>({x:c.x*r,y:c.y*a}))}}static toAim(t){this.eachKeyframe(t,(e,i,n)=>{const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);if(s&&Math.abs(s.x-e.bounds.x)<ln.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<ln.UNMOVED_PX)return e;const r=this.aimFrom(t,i,n,e.bounds);return r?{...e,aim:r}:e})}static UNMOVED_PX=.01;static aimOf(t,e,i){const n=$r.of(t.instrument,ci.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,Le(t,e),i)}static aimFrom(t,e,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(t),r=e.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=e.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(t){this.eachKeyframe(t,(e,i,n)=>this.placedByAim(t,e,i,n))}static placedByAim(t,e,i,n){const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);return s?{...e,bounds:{...e.bounds,...s}}:e}static derivable(t){const e=new Set,i=new Map,n=new Map;return t.timeline.allKeyframes.forEach((s,r)=>{const a=Le(t,s.t),c=$r.of(t.instrument,ci.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:h,shape:l}of s.shapes){const u=n.get(h),d=i.get(h);if(n.set(h,l),!u||!d){i.set(h,l);continue}const f=Object.fromEntries(Object.entries(l).filter(([g,v])=>g!=="bounds"&&g!=="points"&&JSON.stringify(v)!==JSON.stringify(u[g]))),p={...d,...f},m=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);ln.near(m,l)?(e.add(`${r}:${h}`),i.set(h,p)):i.set(h,l)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=ln.SAME_PX*Math.max(1,Math.abs(a)),n=t.bounds,s=e.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:e.kind!=="polygon"||t.kind!=="polygon"?!0:t.points.length===e.points.length&&t.points.every((r,a)=>i(r.x,e.points[a].x)&&i(r.y,e.points[a].y))}static positionOf(t,e,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(t),a=this.shortestArc(e.azimuthDeg-s.headingDeg),c=e.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(t){return{x:ki.frameWidthPx(t.instrument,ci.CANVAS_HEIGHT_PX)/2,y:ci.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=ln.OFF_CANVAS_DEG?Math.sign(e)*ln.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=ki.frameWidthPx(e,ci.CANVAS_HEIGHT_PX)/2,s=ki.frameWidthPx(t.instrument,ci.CANVAS_HEIGHT_PX)/2,r=ci.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),h=i?.get(a.t)??c,l=$r.of(e,ci.CANVAS_HEIGHT_PX,h),u=$r.of(t.instrument,ci.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,m=f.y+f.height/2-r,g=Math.hypot(p,m),v=g===0?1:u.angleDegToRadiusPx(l.radiusPxToAngleDeg(g))/g,M={...f,x:s+p*v-f.width/2,y:r+m*v-f.height/2};return{...d,shape:{...d.shape,bounds:M}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=Le(t,n.t),r=this.fovOf(t,n.t),a=$r.of(t.instrument,ci.CANVAS_HEIGHT_PX,r);let c=!1;const h=n.shapes.map(l=>{const u=e(l.shape,a,s);return u===l.shape?l:(c=!0,{...l,shape:u})});c&&i.addKeyframe(n.t,h)}}}class ns{static isRelative(t){return t!==void 0&&typeof t.eastM=="number"&&typeof t.northM=="number"}static isAbsolute(t){return t!==void 0&&typeof t.lat=="number"&&typeof t.lng=="number"}static referenceOf(t,e){return e.references.find(i=>(i.id??void 0)===(t.relativeTo??void 0))}static resolve(t,e){if(ns.isRelative(t)){const i=ns.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return ns.isAbsolute(t)&&e.origin?ns.toLocal(t,e.origin):void 0}static restated(t,e,i){if(ns.isRelative(t)){const s=ns.referenceOf(t,i);return s?ns.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=ns.toGeo(e,i.origin);return{lat:ns.degrees(n.lat),lng:ns.degrees(n.lng)}}static relative(t,e,i){const n={eastM:ns.metres(t),northM:ns.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=de(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return As(t.eastM,-t.northM,e.lat,e.lng)}static metres(t){return Math.round(t*100)/100}static degrees(t){return Math.round(t*1e7)/1e7}}class Wn{static restatedDecor(t){const e=Wn.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=Wn.restated(i.saidPosition,i,Wn.frameAt(t,0,e,i.id));JSON.stringify(s)!==JSON.stringify(i.saidPosition)&&(n={...i,saidPosition:s},s||delete n.saidPosition)}if(i.track?.some(s=>s.saidPosition)){const s=i.track.map(r=>{if(!r.saidPosition)return r;const a=Wn.restated(r.saidPosition,r,Wn.frameAt(t,r.t,e,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const c={...r,saidPosition:a};return a||delete c.saidPosition,c});n={...n,track:s}}return n})}static restatedObserverTrack(t){const e=t.observerTrack.toJSON(),i=Wn.originOf(t);return!i||!e.keyframes.some(n=>n.pose.saidPosition)?e:{...e,keyframes:e.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=ns.toLocal({lat:s.lat,lng:s.lng},i),a=Wn.restated(s.saidPosition,r,Wn.frameAt(t,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const c={...s,saidPosition:a};return a||delete c.saidPosition,{...n,pose:c}})}}static restatedInterpretation(t){const e=t.interpretation;if(!e?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return e;const i=Wn.originOf(t);return{...e,bodies:e.bodies.map(n=>n.track.some(s=>s.saidPosition)?{...n,track:n.track.map(s=>{if(!s.saidPosition)return s;const r=s.eastM!==void 0&&s.northM!==void 0?Wn.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},Wn.frameAt(t,s.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(s.saidPosition))return s;const a={...s,saidPosition:r};return r||delete a.saidPosition,a})}:n)}}static originOf(t){const e=t.observerTrack.getInterpolatedPoseAt(0),i=t.event.place?.[0],n=e?.lat??i?.lat,s=e?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(t,e,i,n){const s=[{label:"",eastM:0,northM:0},...t.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:c}=vr(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return ns.restated(t,{eastM:e.eastM,northM:e.northM},i)}}class si{constructor(t,e,i){this.params=t,this.from=e,this.origin=t.path[0],this.cos0=Math.cos(t.path[0].lat*Math.PI/180),this.points=t.path.map(r=>this.local(r)),this.cumulative=[0];for(let r=1;r<this.points.length;r++){const a=this.points[r-1],c=this.points[r];this.cumulative.push(this.cumulative[r-1]+Math.hypot(c.e-a.e,c.n-a.n))}this.distances=[];let n=0;for(let r=e;r<=i+si.BEYOND_MS;r+=si.STEP_MS)this.distances.push(n),n+=this.speedAt(r)*si.STEP_MS/1e3;this.shift=this.project(this.local(t.through))-this.distanceAt(t.through.t);const s=[];for(let r=e;r<=i;r+=si.SAMPLE_MS)s.push({t:r,place:this.placeAt(r)});this.sampleOrigin=s[0].place,this.sampleCos=Math.cos(this.sampleOrigin.lat*Math.PI/180),this.samples=s.map(({t:r,place:a})=>({t:r,e:(a.lng-this.sampleOrigin.lng)*Math.PI/180*si.R*this.sampleCos,n:(a.lat-this.sampleOrigin.lat)*Math.PI/180*si.R}))}static R=63710088e-1;static STEP_MS=100;static SAMPLE_MS=2e3;static BEYOND_MS=8e4;origin;cos0;points;cumulative;distances;shift;samples;sampleOrigin;sampleCos;get start(){return this.sampleOrigin}stateAt(t){const e=this.samples,i=e.length-2;let n=0;for(;n<i&&e[n+1].t<t;)n++;const s=e[n],r=e[n+1],a=(t-s.t)/(r.t-s.t),c=p=>[n>0?p[n-1]:2*p[n]-p[n+1],p[n],p[n+1],n+2<p.length?p[n+2]:2*p[n+1]-p[n]],h=e.map(p=>p.e),l=e.map(p=>p.n),u=si.catmull(c(h),a),d=si.catmull(c(l),a),f=(Math.atan2(si.slope(c(h),a),si.slope(c(l),a))*180/Math.PI%360+360)%360;return{eastM:u,northM:d,roadDeg:f,lat:this.sampleOrigin.lat+d/si.R*180/Math.PI,lng:this.sampleOrigin.lng+u/(si.R*this.sampleCos)*180/Math.PI}}bearingAt(t,e){const i=this.local(this.placeAt(t)),n=this.local(e);return(Math.atan2(n.e-i.e,n.n-i.n)*180/Math.PI%360+360)%360}get sampleTimes(){return this.samples.map(t=>t.t)}placeAt(t){const e=this.along(this.distanceAt(t)+this.shift);return{lat:this.origin.lat+e.n/si.R*180/Math.PI,lng:this.origin.lng+e.e/(si.R*this.cos0)*180/Math.PI}}distanceAt(t){const e=Math.max(0,Math.min(this.distances.length-1,Math.round((t-this.from)/si.STEP_MS)));return this.distances[e]}speedAt(t){const e=this.params.speedDivisors?si.linear(this.params.speedDivisors.map(({t:i,divisor:n,step:s})=>({t:i,value:n,step:s})),t):1;return si.linear(this.params.speeds.map(({t:i,kmh:n,step:s})=>({t:i,value:n,step:s})),t)/3.6/e}local(t){return{e:(t.lng-this.origin.lng)*Math.PI/180*si.R*this.cos0,n:(t.lat-this.origin.lat)*Math.PI/180*si.R}}along(t){const e=this.points;let i=0;for(;i<e.length-2&&this.cumulative[i+1]<t;)i++;const n=e[i],s=e[i+1],r=(t-this.cumulative[i])/(this.cumulative[i+1]-this.cumulative[i]);return{e:n.e+(s.e-n.e)*r,n:n.n+(s.n-n.n)*r}}project(t){let e=1/0,i=0;for(let n=0;n<this.points.length-1;n++){const s=this.points[n],r=this.points[n+1],a=r.e-s.e,c=r.n-s.n,h=Math.max(0,Math.min(1,((t.e-s.e)*a+(t.n-s.n)*c)/(a*a+c*c))),l=Math.hypot(s.e+a*h-t.e,s.n+c*h-t.n);l<e&&(e=l,i=this.cumulative[n]+h*Math.hypot(a,c))}return i}static linear(t,e){if(e<=t[0].t)return t[0].value;for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];if(s.step&&e<s.t)return n.value;if(e<=s.t)return n.value+(s.value-n.value)*(e-n.t)/(s.t-n.t)}return t[t.length-1].value}static catmull([t,e,i,n],s){return .5*(2*e+(i-t)*s+(2*t-5*e+4*i-n)*s*s+(3*e-t-3*i+n)*s**3)}static slope([t,e,i,n],s){return .5*(i-t+2*(2*t-5*e+4*i-n)*s+3*(3*e-t-3*i+n)*s*s)}}class Ze{constructor(t,e,i,n,s,r){this.drive=t,this.eye=e,this.lookAhead=i,this.lean=n,this.watch=s,this.times=t.sampleTimes;const a=i.pitchShare??1;this.aimed=[];for(const c of this.times){const h=t.bearingAt(c,i.target),l=this.aimed[this.aimed.length-1];this.aimed.push(l===void 0?h:l+Ze.signed(h-l))}this.pitched=this.times.map(c=>r(c)*a)}static STEP_MS=250;static DENSE_MS=50;static SETTLED_MS=700;static TURN_S=.4;static TURN_S_PER_DEG=.5/150;static ROAD_PITCH_DEG=-1;static SHOULDER={x:-.08,y:0,z:-.07};static TWIST_FROM_DEG=60;aimed;pitched;times;poses(t,e){const i=[];for(let u=t;u<e;u+=Ze.STEP_MS)i.push(u);i.push(e);const n=new Map(i.map(u=>{const d=this.sample(u);return[u,Ze.signed(d.headingDeg-d.roadDeg)]})),s=u=>n.get(i.reduce((d,f)=>Math.abs(f-u)<Math.abs(d-u)?f:d)),r=this.schedule(s,e),a=this.watch?.t,c=r.map(([u,d],f)=>{if(f===0)return 0;if(u===a&&this.lean)return this.lean.params.turnS;const p=this.sample(u);return Ze.turnS(this.target(r[f-1][1],p),this.target(d,p))}),h=new Set(i),l=r.map(([u],d)=>[u,c[d]]);this.lean&&l.push([this.lean.t,this.lean.params.turnS],[this.lean.t+this.lean.params.holdS*1e3,this.lean.params.turnS]);for(const[u,d]of l){const f=Math.round(u+d*1e3+Ze.SETTLED_MS)+Ze.DENSE_MS;for(let p=Math.round(u);p<f;p+=Ze.DENSE_MS)p>=t&&p<=e&&h.add(p)}return[...h].sort((u,d)=>u-d).map(u=>{const d=this.sample(u),[f,p]=this.gaze(r,c,d),m=this.drive.stateAt(u);return{t:u,headingDeg:f,pitchDeg:p,eye:this.eyeAt(u,Ze.signed(f-d.roadDeg)),roadDeg:m.roadDeg,lat:m.lat,lng:m.lng}})}schedule(t,e){const i=[],n=this.lookAhead,s=this.watch?.t??e;let r=0;for(;r<s;){if(Math.abs(t(r))<=n.glanceBeyondDeg){(i.length===0||i[i.length-1][1]!=="watch")&&i.push([r,"watch"]),r+=Ze.STEP_MS;continue}if(i.push([r,"glance"]),r+=n.glanceS*1e3,r>=s)break;i.push([r,"road"]),r+=n.roadS*1e3}if(!this.watch)return i;const a=this.watch.params;r=s,i.push([r,"mirror"]),r+=a.firstS*1e3;let c=0;for(;r<e;){const h=r<a.glancesUntil&&c%2===0?"glance":"road";i.push([r,h]),r+=(h==="glance"?a.glanceS:a.roadS)*1e3,i.push([r,"mirror"]),r+=a.mirrorS*1e3,c++}return i}sample(t){const e=this.times,i=e.length-2;let n=0;for(;n<i&&e[n+1]<t;)n++;const s=(t-e[n])/(e[n+1]-e[n]),r=a=>[n>0?a[n-1]:2*a[n]-a[n+1],a[n],a[n+1],n+2<a.length?a[n+2]:2*a[n+1]-a[n]];return{t,roadDeg:this.drive.stateAt(t).roadDeg,headingDeg:(si.catmull(r(this.aimed),s)%360+360)%360,pitchDeg:si.catmull(r(this.pitched),s),eye:this.eyeAt(t,0)}}target(t,e){const{roadDeg:i,headingDeg:n,pitchDeg:s,eye:r}=e;if(t==="glance")return[n,s];if(t==="watch"){const u=Ze.signed(n-i),d=this.lookAhead.keepDeg,f=u-d*Math.tanh(u/d),p=u?f/u:0;return[Ze.normalized(i+f),Ze.ROAD_PITCH_DEG+(s-Ze.ROAD_PITCH_DEG)*p]}if(t==="road"||!this.watch)return[i,Ze.ROAD_PITCH_DEG];const a=this.watch.params.mirror,c={x:a.x-r.x,y:a.y-r.y,z:a.z-r.z},h=Math.atan2(-c.x,-c.z)*180/Math.PI,l=Math.atan2(c.y,Math.hypot(c.x,c.z))*180/Math.PI;return[Ze.normalized(i-h),l]}gaze(t,e,i,n){const s=i.t;let r=n??0;if(n===void 0&&s>=t[0][0])for(let g=0;g<t.length;g++)t[g][0]<=s&&(r=g);const[a,c]=this.target(t[r][1],i);if(r===0)return[a,c];const h=e[r]*1e3,l=s-t[r][0];if(l>h+Ze.SETTLED_MS)return[a,c];const[u,d]=this.gaze(t,e,i,r-1);if(l<h){const g=l/h,v=-2*g**3+3*g*g+(g**3-g*g)*pn.ARRIVAL;return[Ze.normalized(u+Ze.signed(a-u)*v),d+(c-d)*v]}const f=Ze.signed(a-u),p=l-h,m=pn.ARRIVAL/h*p*Math.exp(-p/Math.min(pn.SETTLE_MS,.4*h));return[Ze.normalized(a+f*m),c+(c-d)*m]}leanAt(t){if(!this.lean)return 0;const{holdS:e,turnS:i}=this.lean.params,n=(t-this.lean.t)/1e3;return n<0||n>e+i?0:Ze.smooth(Math.min(1,n/i,(e+i-n)/i))}eyeAt(t,e){const i=this.leanAt(t),n=this.lean?.params.offsetM??{x:0,y:0,z:0},s=Ze.smooth((Math.abs(e)-Ze.TWIST_FROM_DEG)/(180-Ze.TWIST_FROM_DEG)),r=Ze.SHOULDER;return{x:this.eye.x+n.x*i+r.x*s,y:this.eye.y+n.y*i+r.y*s,z:this.eye.z+n.z*i+r.z*s}}static turnS(t,e){return Ze.TURN_S+Ze.TURN_S_PER_DEG*Math.hypot(Ze.signed(e[0]-t[0]),e[1]-t[1])}static smooth(t){const e=Math.min(1,Math.max(0,t));return e*e*e*(10-15*e+6*e*e)}static signed(t){return((t+540)%360+360)%360-180}static normalized(t){return(t%360+360)%360}}const dp=Math.PI/180;class zt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)zt.collect(this.motionKeys,s.t,s.motions),zt.collect(this.turnKeys,s.t,s.turns),zt.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;turnKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return zt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?zt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],h=r[Math.min(a+1,r.length-1)],l=h===c||h.t===c.t?0:Math.min(1,(e-c.t)/(h.t-c.t));n[s]=zt.lerp(c.value,h.value,l)}return n}static eyeOf(t,e,i){const n=Le(t,0),s=Le(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?de(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,h=a?-a.z:0;return{eastM:c,northM:h,upM:i.heightAt(c,h)+zt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=zt.directionOf(e,i),r=h=>t.upM+s.upM*h-n.heightAt(t.eastM+s.eastM*h,t.northM+s.northM*h);let a=0,c=0;for(;c<zt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let h=0;h<30;h++){const l=(a+c)/2;r(l)<=0?c=l:a=l}return c}a=c}}static directionOf(t,e){const i=t*dp,n=e*dp;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const m=i+n+1>>1;e[m].t>t?n=m-1:i=m}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),h=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,l=h?h.eastM+zt.lerp(r.carried.eastM,a.carried.eastM,c):zt.lerp(r.eastM,a.eastM,c),u=h?h.northM+zt.lerp(r.carried.northM,a.carried.northM,c):zt.lerp(r.northM,a.northM,c),d={widthM:zt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:zt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:zt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:zt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:zt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:zt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(h)p=h.upM+zt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=zt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(l,u,d,f.headingDeg)+m+d.heightM/2}else p=zt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,modelParameters:this.body.modelParameters,flicker:this.body.flicker,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:l,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:zt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:zt.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:zt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:zt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:zt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:zt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),...this.turnKeys.size>0?{turns:zt.channelsAt(this.turnKeys,t,0)}:{},lights:this.lightsAt(t),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:zt.lerp(n.lengthM,s.lengthM,i),widthM:zt.lerp(n.widthM,s.widthM,i),luminanceCdM2:zt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){if(!("upM"in t.vertical))return this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2;const e=t.vertical.fromGround;if(!e)return t.vertical.upM;const i=t.vertical.upM+this.ground.heightAt(e.eastM,e.northM);return Math.max(i,this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.sizeM.heightM/2)}groundUnderFootprint(t,e,i,n){const s=n*dp,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[h,l]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=h*i.widthM/2,d=l*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??zt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??zt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??zt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??zt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??zt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??zt.DEFAULT_APPEARANCE.haloScale},h=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!h)continue;const l=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...h,sizeM:r,attitude:a,appearance:c,flame:l,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=zt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?zt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=zt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=zt.rgbOf(t),s=zt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(zt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class ys{static ANONYMOUS_OBSERVER="observer";static observerId(t){return t.observer?.id??ys.ANONYMOUS_OBSERVER}static shapeIds(t){const e=new Set(t.timeline.sourceIds);for(const i of t.events??[])if(i.eventType==="appearance")for(const n of i.params?.parts??[])e.add(n.sourceId);return[...e]}static ids(t){const e=new Map,i=(n,s)=>{n!==void 0&&e.set(n,[...e.get(n)??[],s])};i(ys.observerId(t),"observer");for(const n of ys.shapeIds(t))i(n,"shape");for(const n of t.timeline.allGroups)i(n.id,"group");for(const n of t.interpretation?.bodies??[])i(n.id,"body");for(const n of t.decor)i(n.id,"decor");return e}static kindOf(t,e){if(e===void 0)return;const i=ys.ids(t).get(e);return i?.length===1?i[0]:void 0}static partOf(t){const e=t?.indexOf("/")??-1;if(!(t===void 0||e<=0||e===t.length-1))return{element:t.slice(0,e),part:t.slice(e+1)}}static hasPart(t,e,i){if(e==="body")return!0;if(e!=="decor")return!1;const n=t.decor.find(s=>s.id===i.element);return!!(n?.lights?.some(s=>s.id===i.part)||n?.groups?.some(s=>s.id===i.part))}static isObserver(t,e){return e.who===ys.observerId(t)}static isPhenomenon(t,e){return e.who===void 0?!1:t.timeline.groupOf(e.who)!==void 0||ys.shapeIds(t).includes(e.who)}static within(t,e){const i=new Set([e]),n=s=>{for(const r of t.timeline.groupOf(s)?.members??[])i.has(r)||(i.add(r),n(r))};return n(e),i}static renamed(t,e,i){if(e!==i)for(const n of t.events??[])n.who===e&&(n.who=i)}static issues(t){const e=[],i=ys.ids(t);for(const[n,s]of i)s.length>1&&e.push({kind:"duplicate-id",id:n,path:s.join(", ")});return(t.events??[]).forEach((n,s)=>{const r=ys.partOf(n.who);r&&i.get(r.element)?.length===1&&ys.hasPart(t,i.get(r.element)[0],r)||(n.who===void 0||!i.has(n.who))&&e.push({kind:"unknown-who",id:n.who??"",path:`events.${s}.who`})}),e}}class we{constructor(t,e,i){this.travel=t;const n=t.params,s=t.until??i;let r=we.unit(n.from),a=we.towards(r,we.unit(n.towards));const c=e.map(l=>{const u=l.params,d=u.side==="left"?1:-1;return{from:l.t,to:l.until??l.t,radians:u.byDeg*Math.PI/180*(u.seenFrom==="craft"?-d:d)}}),h=we.STEP_MS;for(let l=t.t;l<=s;l+=h){this.directions.push(we.direction(r));for(const f of c){const p=f.to-f.from;if(p<=0)continue;const m=f.radians*(we.smooth((l+h-f.from)/p)-we.smooth((l-f.from)/p));m&&(a=we.add(we.scale(a,Math.cos(m)),we.scale(we.cross(a,r),Math.sin(m))))}const u=we.speedAt(n.speeds,l)*h/1e3*Math.PI/180,d=we.add(we.scale(r,Math.cos(u)),we.scale(a,Math.sin(u)));a=we.add(we.scale(a,Math.cos(u)),we.scale(r,-Math.sin(u))),r=d}}static STEP_MS=5;directions=[];at(t){const e=Math.round((t-this.travel.t)/we.STEP_MS);return this.directions[Math.max(0,Math.min(this.directions.length-1,e))]}sizeAt(t){const e=this.travel.params;return e.sizeBy!=="altitude"?e.sizeDeg:e.sizeDeg*Math.max(.1,Math.sin(Math.max(this.at(t).altitudeDeg,1)*Math.PI/180))}static speedAt(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].degPerS;for(let i=1;i<t.length;i++){const n=t[i-1],s=t[i];if(s.step&&e<s.t)return n.degPerS;if(e<s.t)return n.degPerS+(s.degPerS-n.degPerS)*we.smooth((e-n.t)/(s.t-n.t))}return t[t.length-1].degPerS}static smooth(t){const e=Math.max(0,Math.min(1,t));return e*e*(3-2*e)}static unit(t){const e=t.azimuthDeg*Math.PI/180,i=t.altitudeDeg*Math.PI/180;return[Math.cos(i)*Math.sin(e),Math.cos(i)*Math.cos(e),Math.sin(i)]}static direction(t){return{azimuthDeg:(Math.atan2(t[0],t[1])*180/Math.PI%360+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,t[2])))*180/Math.PI}}static towards(t,e){const i=we.add(e,we.scale(t,-we.dot(t,e))),n=Math.hypot(...i)||1;return we.scale(i,1/n)}static toScreen(t,e,i){const[n,s,r]=we.basis(e,i),a=we.unit(t),c=we.dot(a,n);return[we.dot(a,s)/c,we.dot(a,r)/c]}static fromScreen(t,e,i,n){const[s,r,a]=we.basis(i,n),c=[s[0]+t*r[0]+e*a[0],s[1]+t*r[1]+e*a[1],s[2]+t*r[2]+e*a[2]],h=Math.hypot(...c);return we.direction([c[0]/h,c[1]/h,c[2]/h])}static basis(t,e){const i=t*Math.PI/180,n=e*Math.PI/180;return[[Math.cos(n)*Math.sin(i),Math.cos(n)*Math.cos(i),Math.sin(n)],[Math.cos(i),-Math.sin(i),0],[-Math.sin(n)*Math.sin(i),-Math.sin(n)*Math.cos(i),Math.cos(n)]]}static dot(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}static cross(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}static add(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}static scale(t,e){return[t[0]*e,t[1]*e,t[2]*e]}}class eo{constructor(t,e){this.sighting=t,this.events=e}static FOV_DEG=60;keyframes(){const t=this.events.filter(c=>c.eventType==="look").sort((c,h)=>c.t-h.t),e=this.events.filter(c=>c.eventType==="walk").sort((c,h)=>c.t-h.t),i=this.events.filter(c=>c.eventType==="follow").sort((c,h)=>c.t-h.t);if(t.length===0&&e.length===0)return[];const n=new Set([0]);for(const c of[...t,...e,...i])n.add(c.t),c.until!==void 0&&n.add(c.until);const s=c=>{let h;for(const l of e){const u=l.params;if(c<=l.t)return h??u.from;if(l.until===void 0||c>=l.until)h=u.to;else return}return h??this.sighting.event.place?.[0]},r=c=>([...t].reverse().find(l=>l.t<=c)??t[0])?.params??{headingDeg:0,pitchDeg:0},a=[...n].sort((c,h)=>c-h).flatMap(c=>{const h=s(c);if(!h)return[];const l=r(c);return[{t:c,pose:eo.pose(h,l.headingDeg,l.pitchDeg,l.fovDeg)}]});for(const c of a)this.sighting.observerTrack.addKeyframe(c.t,c.pose);for(const c of i)this.follow(c,r(c.t));return[...this.sighting.observerTrack.allKeyframes]}follow(t,e){const i=t.params;if(this.followSky(t,e))return;const n=this.sighting.interpretation?.bodies.find(l=>l.id===i.target);if(!n)return;const s={heightAt:()=>0},r=l=>zt.eyeOf(this.sighting,l,s),a=new zt(n,s,r),c=t.until??1/0;let h=e;for(const l of n.track){if(l.t<=t.t||l.t>=c)continue;const u=a.at(l.t),d=r(l.t),f=this.sighting.observerTrack.getInterpolatedPoseAt(l.t);if(!u||!d||!f)continue;const p=u.eastM-d.eastM,m=u.northM-d.northM,g=u.upM-d.upM;h={headingDeg:(Math.atan2(p,m)*180/Math.PI%360+360)%360,pitchDeg:Math.atan2(g,Math.hypot(p,m))*180/Math.PI},this.sighting.observerTrack.addKeyframe(l.t,{...f,headingDeg:h.headingDeg,pitchDeg:h.pitchDeg})}if(Number.isFinite(c)){const l=this.sighting.observerTrack.getInterpolatedPoseAt(c);l&&this.sighting.observerTrack.addKeyframe(c,{...l,headingDeg:h.headingDeg,pitchDeg:h.pitchDeg})}}static FOLLOW_SKY_MS=25;static CATCH_UP_MS=900;static OVERHEAD_DEG=78;static HIGHEST_PITCH_DEG=88;followSky(t,e){const i=t.params,n=ys.within(this.sighting,i.target),s=this.sighting.events??[],r=s.find(v=>v.eventType==="travel"&&v.who!==void 0&&n.has(v.who));if(!r)return!1;const a=this.sighting.event.durationSeconds!==void 0?this.sighting.event.durationSeconds*1e3:r.until??t.t,c=new we(r,s.filter(v=>v.eventType==="turn"&&v.who!==void 0&&n.has(v.who)),a),h=t.until??a,l=(i.lagS??0)*1e3,u=(i.reactionS??0)*1e3,d=[],f=this.sighting.sampleMs??eo.FOLLOW_SKY_MS;for(let v=t.t;v<=h;v+=f)d.push(v);const p=d.map(v=>c.at(Math.max(r.t,v-l))),m=p.map(v=>v.azimuthDeg),g=p.flatMap((v,M)=>v.altitudeDeg>eo.OVERHEAD_DEG?[M]:[]);if(g.length>0){const v=Math.max(0,g[0]-1),M=Math.min(d.length-1,g[g.length-1]+1),w=m[v],y=(m[M]-w+540)%360-180;for(let b=v;b<=M;b++)m[b]=((w+y*we.smooth((b-v)/(M-v)))%360+360)%360}return d.forEach((v,M)=>{const w=we.smooth((v-t.t-u)/eo.CATCH_UP_MS),y=(m[M]-e.headingDeg+540)%360-180,b=Math.min(p[M].altitudeDeg,eo.HIGHEST_PITCH_DEG),S=this.sighting.observerTrack.getInterpolatedPoseAt(v)??this.sighting.observerTrack.getLatestPoseAt(v);if(!S)return;const _=x=>Math.round(x*100)/100;this.sighting.observerTrack.addKeyframe(v,{...S,headingDeg:_(((e.headingDeg+y*w)%360+360)%360),pitchDeg:_(e.pitchDeg+(b-e.pitchDeg)*w)})}),!0}static pose(t,e,i,n=eo.FOV_DEG){return{lat:t.lat,lng:t.lng,elevationM:0,headingDeg:e,pitchDeg:i,fovDeg:n}}}class yo{constructor(t,e,i,n){this.body=t,this.events=e,this.endMs=i,this.sampleMs=n}static SAMPLE_MS=250;track(){const t=new Map,e=h=>{const l=t.get(h.t);t.set(h.t,l?{...l,...h,motions:{...l.motions,...h.motions},...l.turns||h.turns?{turns:{...l.turns,...h.turns}}:{},...l.lights||h.lights?{lights:{...l.lights,...h.lights}}:{}}:h)};for(const h of this.body.track)e({...h});const i=[...this.events].sort((h,l)=>h.t-l.t),n=new Map,s=new Map,r=new Map;let a=0;for(const h of this.body.track){for(const[l,u]of Object.entries(h.motions??{}))n.set(l,u);for(const[l,u]of Object.entries(h.turns??{}))s.set(l,u);for(const[l,u]of Object.entries(h.lights??{}))r.set(l,u);h.attitude?.headingDeg!==void 0&&(a=h.attitude.headingDeg)}let c=this.startPlace();for(const h of i){const l=yo.partOf(h.who,this.body.id);if(l!==void 0&&(h.eventType==="light"||h.eventType==="blink")){for(const u of this.leavesOf(l))this.switchLight(u,h,r,e,d=>t.get(d)?.lights?.[u]);continue}if(l!==void 0){if(h.eventType!=="spin"&&h.eventType!=="turn")continue;const u=s.get(l)??0,d=h.until??h.t,f=h.eventType==="spin"?u+360*h.params.turnsPerS*(d-h.t)/1e3:h.params.headingDeg;e({t:h.t,turns:{[l]:u}}),e({t:d,turns:{[l]:f}}),s.set(l,f);continue}if((h.eventType==="motion"||h.eventType==="spin")&&h.params?.motion){const u=h.params,d=u.motion,f=n.get(d)??0,p=h.until??h.t,m=h.eventType==="motion"?u.to:f+u.turnsPerS*(p-h.t)/1e3;e({t:h.t,motions:{[d]:f}}),e({t:p,motions:{[d]:m}}),n.set(d,m)}else if(h.eventType==="rise"&&c){const u=h.params,d=h.until??h.t,f=u.angleDeg*Math.PI/180,p=(u.headingDeg??0)*Math.PI/180,m=c,g=v=>{const M=u.stops===!1?v*v:v*v*v*(10-15*v+6*v*v),w=u.distanceM*M;return{eastM:m.eastM+w*Math.sin(f)*Math.sin(p),northM:m.northM+w*Math.sin(f)*Math.cos(p),aboveGroundM:m.aboveGroundM+w*Math.cos(f)}};for(let v=h.t;v<d;v+=this.sampleMs??yo.SAMPLE_MS)e(yo.key(v,g((v-h.t)/(d-h.t))));c=g(1),e(yo.key(d,c))}else if(h.eventType==="turn"){const u=h.params;e({t:h.t,attitude:{headingDeg:a}}),e({t:h.until??h.t,attitude:{headingDeg:u.headingDeg}}),a=u.headingDeg}else h.eventType==="vanish"&&e({t:h.t,present:!1})}return[...t.values()].sort((h,l)=>h.t-l.t)}static ride(t,e,i){const n=e.params,s=e.until??1/0,r=new Map(t.track.map(a=>[a.t,{...a}]));for(const a of i.track){if(a.t<e.t||a.t>s||(a.present===!1&&r.set(a.t,{...r.get(a.t),t:a.t,present:!1}),a.eastM===void 0||a.northM===void 0))continue;const c=(a.onGround?0:a.altitudeAboveGroundM??0)+n.aboveM;r.set(a.t,{...r.get(a.t),t:a.t,eastM:a.eastM,northM:a.northM,altitudeAboveGroundM:c})}return[...r.values()].sort((a,c)=>a.t-c.t)}switchLight(t,e,i,n,s){const r=i.get(t)??0,a=e.eventType==="light"?e.until:e.until??this.endMs,c=(h,l)=>n({t:h,lights:{[t]:l}});if(e.t>0&&s(e.t-1)===void 0&&c(e.t-1,r),e.eventType==="light"){const h=e.params.cdM2;if(c(e.t,h),a===void 0){i.set(t,h);return}c(a-1,h)}else{const h=e.params;if(a===void 0)return;const l=h.cdM2??r;let u=e.t,d=!0;for(;u<a;){const f=Math.min(Math.round(u+1e3*(d?h.onS:h.offS)),a);if(f<=u)break;c(u,d?l:0),c(f-1,d?l:0),u=f,d=!d}}c(a,r),i.set(t,r)}leavesOf(t,e=new Set){const i=this.body.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}startPlace(){const t=this.body.track.find(e=>e.eastM!==void 0&&e.northM!==void 0);return t&&{eastM:t.eastM,northM:t.northM,aboveGroundM:t.onGround?0:t.altitudeAboveGroundM??0}}static key(t,e){return e.aboveGroundM<=0?{t,eastM:e.eastM,northM:e.northM,onGround:!0}:{t,eastM:e.eastM,northM:e.northM,altitudeAboveGroundM:e.aboveGroundM}}}class zu{constructor(t,e,i){this.object=t,this.events=e,this.endMs=i}lights(){const t=new Map,e=[...this.events].sort((i,n)=>i.t-n.t);for(const i of e){const n=zu.partOf(i.who,this.object.id);if(!(n===void 0||i.eventType!=="light"&&i.eventType!=="blink"))for(const s of this.leavesOf(n)){const r=this.object.lights?.find(a=>a.id===s);r&&t.set(s,this.switched(r,t.get(s)??[],i))}}return(this.object.lights??[]).map(i=>t.has(i.id)?{...i,keyframes:t.get(i.id)}:i)}switched(t,e,i){const n=zu.stateAt(t,e,i.t),s=i.eventType==="light"?i.until:i.until??this.endMs,r=[];if(i.eventType==="light")r.push({t:i.t,intensity:i.params.intensity,pattern:n.pattern});else{const c=i.params,h=c.onS+c.offS;if(s===void 0||h<=0)return e;const l=h*1e3,u=(-i.t/l%1+1)%1,d={kind:"flash",perMinute:60/h,dutyCycle:c.onS/h,...u?{phase:u}:{}},f=c.intensity??(n.intensity>0?n.intensity:t.intensity??1);r.push({t:i.t,intensity:f,pattern:d})}s!==void 0&&r.push({t:s,intensity:n.intensity,pattern:n.pattern});const a=new Set(r.map(c=>c.t));return[...e.filter(c=>!a.has(c.t)),...r].sort((c,h)=>c.t-h.t)}static stateAt(t,e,i){const n=e.filter(s=>s.t<=i).at(-1);return{intensity:n?.intensity??t.intensity??1,pattern:n?.pattern??t.pattern}}leavesOf(t,e=new Set){const i=this.object.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}}class Nh{static observer(t){const e=t.allKeyframes,i=e.map(s=>Nh.said(s.pose)),n=e.filter((s,r)=>r>0&&r<e.length-1&&i[r]===i[r-1]&&i[r]===i[r+1]);for(const s of n)t.removeKeyframeAt(s.t)}static said(t){return JSON.stringify(t,(e,i)=>typeof i=="number"?Math.round(i*1e10)/1e10:i)}static timeline(t){const e=new Map;for(const i of t.allKeyframes)for(const n of i.shapes){const s=e.get(n.sourceId)??[];s.push({t:i.t,said:Nh.said(n.shape)}),e.set(n.sourceId,s)}for(const[i,n]of e){const s=n.filter((r,a)=>a>0&&a<n.length-1&&r.said===n[a-1].said&&r.said===n[a+1].said);for(const r of s)t.removeShapeAt(r.t,i)}}}class Vf{constructor(t,e){this.end=e;const i=[...t].sort((n,s)=>n.t-s.t);this.rolls=i.filter(n=>n.eventType==="roll"),this.vibrations=i.filter(n=>n.eventType==="vibrate"),this.spirals=i.filter(n=>n.eventType==="spiral")}static SPIRAL_OPENS=4;static THINNEST=.08;rolls;vibrations;spirals;rollAt(t){let e=0,i=0;for(const n of this.rolls){if(t<n.t)break;const s=n.params,r=this.progress(n,t);i=e+(s.toDeg-e)*(s.andBack?Math.sin(Math.PI*we.smooth(r)):we.smooth(r)),s.andBack||(e=s.toDeg)}for(const n of this.spirals){if(t<n.t)break;const s=n.params;i=e+(s.clockwise?1:-1)*s.rollDeg*this.progress(n,t)}return i}acrossShareAt(t){return Math.max(Vf.THINNEST,Math.abs(Math.cos(this.rollAt(t)*Math.PI/180)))}sidewaysAt(t,e){let i=0;for(const n of this.vibrations){const s=n.until??this.end;if(t<n.t||t>=s)continue;const r=n.params,a=we.smooth((t-n.t)/(r.riseS*1e3))*Math.max(0,1-(t-n.t)/(s-n.t));i+=r.amplitudeShare*e*a*Math.sin(2*Math.PI*r.hz*(t-n.t)/1e3)}return i}spiralAt(t){const e=[...this.spirals].reverse().find(a=>a.t<=t);if(!e)return;const i=e.params,n=this.progress(e,t),s=Math.tan(i.radiusDeg*Math.PI/180)*we.smooth(n*Vf.SPIRAL_OPENS)*(1-i.shrink*we.smooth(n)),r=-(i.clockwise?1:-1)*2*Math.PI*i.turns*n;return[s*(Math.cos(r)-1),s*Math.sin(r)]}progress(t,e){const i=t.until??this.end;return i<=t.t?1:Math.max(0,Math.min(1,(e-t.t)/(i-t.t)))}}class vs{constructor(t,e,i,n){this.sighting=t,this.stand=e;const s=i.filter(a=>a.eventType==="appearance").sort((a,c)=>a.t-c.t);this.vanishAt=i.find(a=>a.eventType==="vanish")?.t;const r=this.vanishAt??n;this.path=e.eventType==="travel"?new we(e,i.filter(a=>a.eventType==="turn"),n):void 0,this.motion=this.path?new Vf(i,e.until??n):void 0,this.looks=s.map((a,c)=>({t:a.t,until:a.until??s[c+1]?.t??r,parts:a.params.parts})),this.blinks=i.filter(a=>a.eventType==="blink").map(a=>({t:a.t,until:a.until??r,parts:a.who===void 0?[]:t.timeline.leavesOf(a.who),params:a.params}))}static SAMPLE_MS=2e3;static TRAVEL_SAMPLE_MS=25;static MOTION_MS=40;static SPIRAL_AHEAD_MS=20;static R=63710088e-1;looks;blinks;vanishAt;path;motion;timeline(){const t=new Map,e=(r,a)=>{const c=this.state(a,r);c&&(t.has(r)||t.set(r,new Map),t.get(r).set(a,c))},i=[...new Set(this.looks.flatMap(r=>r.parts.map(a=>a.sourceId)))];this.looks.forEach((r,a)=>{const c=this.looks[a+1];for(const h of i){if(!r.parts.some(d=>d.sourceId===h)){e(r.t,h),c?.parts.some(d=>d.sourceId===h)&&e(c.t-1,h);continue}const u=this.sighting.sampleMs??(this.path?vs.TRAVEL_SAMPLE_MS:vs.SAMPLE_MS);for(let d=r.t;d<r.until;d+=u)e(d,h);e(r.until-1,h)}});for(const r of this.blinks)for(const[a,c]of this.phases(r))for(const h of r.parts)e(a,h),e(c-1,h);if(this.vanishAt!==void 0)for(const r of i)e(this.vanishAt,r);const n=[...t.keys()].sort((r,a)=>r-a).map(r=>({t:r,shapes:[...t.get(r).values()]})),s=new Map;for(const r of n)for(const a of r.shapes){const c=a.shape.angle,h=s.get(a.sourceId);if(c===void 0)continue;const l=h===void 0?c:c+2*Math.PI*Math.round((h-c)/(2*Math.PI));a.shape.angle=Math.round(l*1e4)/1e4,s.set(a.sourceId,l)}return{keyframes:n,order:i,groups:[]}}phases(t){const e=[];let i=!0;for(let n=t.t;n<t.until;){const s=Math.min(n+(i?t.params.onS:t.params.offS)*1e3,t.until);e.push([n,s]),n=s,i=!i}return e}off(t,e){for(const i of this.blinks){if(e<i.t||e>=i.until||!i.parts.includes(t))continue;if(this.phases(i).findIndex(([s,r])=>e>=s&&e<r)%2===1)return i.params.off}}state(t,e){const i=[...this.looks].reverse().find(h=>h.t<=e)??this.looks[0],n=i?.parts.find(h=>h.sourceId===t),r=(n?i:this.looks.find(h=>h.t>e&&h.parts.some(l=>l.sourceId===t))??[...this.looks].reverse().find(h=>h.parts.some(l=>l.sourceId===t)))?.parts.find(h=>h.sourceId===t);if(!r)return;const a=!n||this.vanishAt!==void 0&&e>=this.vanishAt,c=a?void 0:this.off(t,e);return this.path?{sourceId:t,shape:this.onPath(r,e,c,a)}:{sourceId:t,shape:vs.shape(r,this.geometry(e),c,a)}}onPath(t,e,i,n){const s=this.path,r=this.sighting.observerTrack.getInterpolatedPoseAt(e)??this.sighting.observerTrack.getLatestPoseAt(e),a=r?.headingDeg??0,c=r?.pitchDeg??0,h=this.motion,l=x=>we.toScreen(s.at(x),a,c),u=(x,A)=>{const I=Math.hypot(A[0]-x[0],A[1]-x[1])||1;return[(A[0]-x[0])/I,(A[1]-x[1])/I]};let d=l(e),[f,p]=u(l(e-vs.MOTION_MS),l(e+vs.MOTION_MS));const m=s.sizeAt(e),g=Math.tan(h.sidewaysAt(e,m)*Math.PI/180);d=[d[0]-g*p,d[1]+g*f];const v=h.spiralAt(e);if(v){const x=h.spiralAt(e+vs.SPIRAL_AHEAD_MS),A=l(e),I=l(e+vs.SPIRAL_AHEAD_MS);d=[d[0]+v[0],d[1]+v[1]],[f,p]=u([A[0]+v[0],A[1]+v[1]],[I[0]+x[0],I[1]+x[1]])}const M=h.acrossShareAt(e),w={...t,heightShare:(t.heightShare??t.widthShare)*M,...t.upShare===void 0?{}:{upShare:t.upShare*M}},y=Math.tan(m*(w.alongShare??0)*Math.PI/180),b=Math.tan(m*(w.upShare??0)*Math.PI/180),S=we.fromScreen(d[0]+y*f-b*p,d[1]+y*p+b*f,a,c),_=vs.shape(w,{...S,sizeDeg:m},i,n,!0);return _.angle=Math.atan2(-p,f),_}geometry(t){const e=this.stand.params,i=this.sighting.observerTrack.getInterpolatedPoseAt(t)??this.sighting.observerTrack.getLatestPoseAt(t),n=i?.lat!==void 0&&i.lng!==void 0?{lat:i.lat,lng:i.lng}:this.sighting.event.place?.[0]??e.place;return vs.seenFrom(e,n,t)}static seenFrom(t,e,i){const n=(t.place.lng-e.lng)*Math.PI/180*vs.R*Math.cos(e.lat*Math.PI/180),s=(t.place.lat-e.lat)*Math.PI/180*vs.R,r=Math.hypot(n,s),a=si.linear(t.metres.map(({t:h,widthM:l,step:u})=>({t:h,value:l,step:u})),i),c=si.linear(t.metres.map(({t:h,heightM:l,step:u})=>({t:h,value:l,step:u})),i);return{azimuthDeg:(Math.atan2(n,s)*180/Math.PI%360+360)%360,altitudeDeg:Math.atan2(c,r)*180/Math.PI,sizeDeg:2*Math.atan(a/(2*r))*180/Math.PI}}static shape(t,e,i,n,s=!1){const r=e.sizeDeg,a=Math.max(t.minWidthDeg??0,r*t.widthShare),c=t.kind==="oval"&&t.heightShare===void 0?a:Math.max(t.minHeightDeg??0,r*(t.heightShare??t.widthShare)),h=s?e.altitudeDeg:e.altitudeDeg+r*(t.upShare??0),l=s?e.azimuthDeg:e.azimuthDeg+r*(t.alongShare??0)/Math.cos(h*Math.PI/180),u=(p,m)=>Math.round(p*10**m)/10**m,d=t.kind==="polygon"?{kind:"polygon",bounds:{x:300,y:170,width:100,height:100*c/a},points:(t.points??[]).map(p=>({x:u(p.x*100,2),y:u(p.y*100*c/a,2)}))}:{kind:"oval",bounds:{x:320,y:180,width:2,height:2}};Object.assign(d,{color:i?.color??t.color,angle:0,transparency:n?1:i?.transparency??t.transparency??0,haloScale:t.halo??0,selected:!1,...t.blur===void 0?{}:{blur:t.blur},...t.title===void 0?{}:{title:t.title},angular:{widthDeg:u(a,4),heightDeg:u(c,4)},aim:{azimuthDeg:u((l%360+360)%360,3),altitudeDeg:u(h,3)}});const f=i&&"brightness"in i?i.brightness:t.brightness;return f!=null&&(d.brightness=n?0:f),d}}class Oe{static STANDING_EYE_M=1.6;static METERS_PER_DEGREE=111320;static expand(t){Oe.expandBodies(t),Oe.expandObserver(t),Oe.expandFlights(t),Oe.expandDecorLights(t),Oe.expandPhenomenon(t)}static expandDecorLights(t){for(const e of t.decor){if(!e.lights?.length||e.lights.some(s=>s.keyframes?.length))continue;const i=(t.events??[]).filter(s=>zu.partOf(s.who,e.id)!==void 0);if(i.length===0)continue;const n=JSON.stringify(e.lights);e.lights=new zu(e,i,Oe.endOf(t)).lights(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorLights={...t.eventsExpansion.decorLights,[e.id]:{stated:n,expanded:JSON.stringify(e.lights)}}}}static writtenLights(t,e,i){const n=t.eventsExpansion?.decorLights?.[e];return n&&JSON.stringify(i)===n.expanded?JSON.parse(n.stated):i}static expandPhenomenon(t){if(t.timeline.allKeyframes.length>0)return;const e=Oe.stands(t);for(const i of e){const n=ys.within(t,i.who),s=(t.events??[]).filter(a=>a.who!==void 0&&n.has(a.who)),r=new vs(t,i,s,i.until??Oe.endOf(t)).timeline();for(const a of Qu.fromJSON(r).allKeyframes)t.timeline.addKeyframe(a.t,a.shapes)}e.length!==0&&(Nh.timeline(t.timeline),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.timelinePending=!0)}static stands(t){return(t.events??[]).filter(e=>(e.eventType==="stand"||e.eventType==="travel")&&ys.isPhenomenon(t,e))}static shapesOf(t){const{groups:e,...i}=t.timeline.toJSON();return JSON.stringify(i)}static timelineWithoutShapes(t){const e=t.timeline.toJSON().groups??[];return e.length>0?{keyframes:[],groups:e}:{keyframes:[]}}static settle(t){t.eventsExpansion?.timelinePending&&(ln.toAngular(t),ln.toAim(t),t.eventsExpansion.timeline=Oe.shapesOf(t),t.eventsExpansion.timelinePending=!1)}static timelineIsExpanded(t){return t.eventsExpansion?.timeline!==void 0&&t.eventsExpansion.timeline===Oe.shapesOf(t)}static expandFlights(t){const e=t.observerTrack.allKeyframes[0]?.pose??t.event.place?.[0];if(e?.lat===void 0||e.lng===void 0)return;const i=Math.cos(e.lat*Math.PI/180);for(const n of t.events??[]){if(n.eventType!=="fly"||n.who===void 0)continue;const s=t.decor.find(m=>m.id===n.who);if(!s||s.track?.length)continue;const r=n.params,a=n.until??Oe.endOf(t),c=r.headingDeg*Math.PI/180,h=(r.from.lng-e.lng)*Math.PI/180*Oe.R*i,l=(r.from.lat-e.lat)*Math.PI/180*Oe.R,u=r.speeds.map(({t:m,kmh:g,step:v})=>({t:m,value:g/3.6,step:v})),d=r.heights.map(({t:m,altitudeM:g,step:v})=>({t:m,value:g,step:v})),f=m=>{const g=Math.sign(m-r.at.t)*Oe.FLY_STEP_MS;let v=0;for(let M=r.at.t;g!==0&&(g>0?M<m:M>m);M+=g){const w=g>0?Math.min(m,M+g):Math.max(m,M+g);v+=(si.linear(u,M)+si.linear(u,w))/2*(w-M)/1e3}return v},p=[];for(let m=n.t;m<=a;m+=si.SAMPLE_MS){const g=r.at.metresBefore-f(m);p.push({t:m,eastM:h-Math.sin(c)*g,northM:l-Math.cos(c)*g,altitudeM:si.linear(d,m),headingDeg:r.headingDeg})}s.track=p,s.eastM=p[0].eastM,s.northM=p[0].northM,s.headingDeg=r.headingDeg,t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorTracks[s.id]=JSON.stringify(p)}}static R=63710088e-1;static FLY_STEP_MS=100;static expandObserver(t){const e=(t.events??[]).filter(m=>ys.isObserver(t,m)),i=e.find(m=>m.eventType==="drive"),n=e.find(m=>m.eventType==="lookAhead");if(t.observerTrack.allKeyframes.length>0)return;if(!i){new eo(t,e).keyframes().length>0&&(Nh.observer(t.observerTrack),t.eventsExpansion={...t.eventsExpansion,observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:t.eventsExpansion?.decorTracks??{}});return}if(!n)return;const s=i.until??Oe.endOf(t),r=i.params,a=new si(r,i.t,s),c=e.find(m=>m.eventType==="lean"),h=e.find(m=>m.eventType==="watch"),u=new Ze(a,r.eye,n.params,c&&{t:c.t,params:c.params},h&&{t:h.t,params:h.params},m=>{const g=Oe.stands(t).find(M=>M.eventType==="stand");if(!g)return Oe.phenomenonPitchAt(t,m);const v=a.stateAt(m);return vs.seenFrom(g.params,{lat:v.lat,lng:v.lng},m).altitudeDeg}).poses(i.t,s),d=u.map(m=>({t:m.t,pose:{lat:m.lat,lng:m.lng,elevationM:m.eye.y-Oe.STANDING_EYE_M,headingDeg:m.headingDeg,pitchDeg:m.pitchDeg,fovDeg:r.fovDeg??60}}));for(const m of d)t.observerTrack.addKeyframe(m.t,m.pose);Nh.observer(t.observerTrack);const f={observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:{}},p=r.vehicle===void 0?void 0:t.decor.find(m=>m.id===r.vehicle);if(p&&!p.track?.length){const m=u[0],g=M=>Math.cos(M*Math.PI/180),v=u.map(M=>{const w=M.roadDeg*Math.PI/180,y=-M.eye.z,b=M.eye.x,S=(M.lng-m.lng)*Oe.METERS_PER_DEGREE*g(M.lat),_=(M.lat-m.lat)*Oe.METERS_PER_DEGREE;return{t:M.t,eastM:S-y*Math.sin(w)-b*Math.cos(w),northM:_-y*Math.cos(w)+b*Math.sin(w),altitudeM:0,headingDeg:M.roadDeg}});p.track=v,p.eastM=v[0].eastM,p.northM=v[0].northM,p.headingDeg=v[0].headingDeg,f.decorTracks[p.id]=JSON.stringify(v)}t.eventsExpansion={...t.eventsExpansion,...f}}static expandBodies(t){const e=t.interpretation?.bodies??[],i=n=>(t.events??[]).some(s=>s.who===n.id&&s.eventType==="ride");for(const n of[...e.filter(s=>!i(s)),...e.filter(i)]){const s=(t.events??[]).filter(l=>l.who===n.id||yo.partOf(l.who,n.id)!==void 0);if(s.length===0)continue;const r=Math.min(...s.map(l=>l.t));if(n.track.some(l=>l.t>r))continue;const a=JSON.stringify(n.track),c=s.find(l=>l.eventType==="ride"),h=c&&e.find(l=>l.id===c.params.in);n.track=c?h?yo.ride(n,c,h):n.track:new yo(n,s,Oe.endOf(t),t.sampleMs).track(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.bodies={...t.eventsExpansion.bodies,[n.id]:{stated:a,expanded:JSON.stringify(n.track)}}}}static writtenInterpretation(t,e){const i=t.eventsExpansion?.bodies;return!e||!i?e:{...e,bodies:e.bodies.map(n=>{const s=i[n.id];return s&&JSON.stringify(n.track)===s.expanded?{...n,track:JSON.parse(s.stated)}:n})}}static refresh(t){const e=t.observerTrack.allKeyframes.length===0||Oe.observerTrackIsExpanded(t),i=t.timeline.allKeyframes.length===0||Oe.timelineIsExpanded(t);Oe.again(t,e,i)}static reset(t){Oe.again(t,!0,Oe.stands(t).length>0)}static again(t,e,i){for(const s of t.interpretation?.bodies??[]){const r=t.eventsExpansion?.bodies?.[s.id];r&&JSON.stringify(s.track)===r.expanded&&(s.track=JSON.parse(r.stated))}for(const s of t.decor)s.lights&&(s.lights=Oe.writtenLights(t,s.id,s.lights));if(e){for(const s of Object.keys(t.eventsExpansion?.decorTracks??{})){const r=t.decor.find(a=>a.id===s);r&&delete r.track}t.observerTrack.clear()}const n=t.timeline.toJSON().groups??[];if(i){for(const s of[...t.timeline.sourceIds])t.timeline.removeSource(s);t.timeline.setGroups(n,!1)}t.eventsExpansion=void 0,Oe.expand(t),i&&t.timeline.pruneGroups(),i&&(ln.toBounds(t),ln.toPosition(t)),Oe.settle(t)}static bodiesAreExpanded(t){const e=t.eventsExpansion?.bodies??{};return(t.interpretation?.bodies??[]).every(i=>!e[i.id]||JSON.stringify(i.track)===e[i.id].expanded)}static observerTrackIsExpanded(t){return t.eventsExpansion?.observerTrack!==void 0&&t.eventsExpansion.observerTrack===JSON.stringify(t.observerTrack.toJSON())}static decorTrackIsExpanded(t,e,i){const n=t.eventsExpansion?.decorTracks[e];return n!==void 0&&n===JSON.stringify(i)}static phenomenonPitchAt(t,e){let i;for(const n of t.timeline.sourceIds){const s=t.timeline.getInterpolatedShapeAt(e,n),r=s?.aim?.altitudeDeg;if(!s||s.transparency>=1||r===void 0)continue;const a=(s.angular?.widthDeg??0)*(s.angular?.heightDeg??0);(!i||a>i.area)&&(i={area:a,altitude:r})}return i?.altitude??0}static endOf(t){return t.event.durationSeconds!==void 0?t.event.durationSeconds*1e3:Math.max(...(t.events??[]).map(e=>e.until??e.t))}}function zA(o){return os.restore(BA(o),o.provenance)}function BA(o,t=!1){return ln.toAngular(o),ln.toAim(o),{version:3,id:o.id,time:Wf.write(o.event.time),endTime:Wf.write(o.event.endTime),durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:wb.write(o.event.place),observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:!t&&Oe.timelineIsExpanded(o)?Oe.timelineWithoutShapes(o):o.timeline.toJSON(),observerTrack:!t&&Oe.observerTrackIsExpanded(o)?void 0:Wn.restatedObserverTrack(o),events:o.events?.length?o.events:void 0,weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:Wn.restatedDecor(o).map(e=>{if(!t&&e.lights&&(e={...e,lights:Oe.writtenLights(o,e.id,e.lights)}),t||!Oe.decorTrackIsExpanded(o,e.id,e.track))return e;const{track:i,...n}=e;return n}),milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,metering:o.metering,sampleMs:o.sampleMs,lens:o.lens,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:t?Wn.restatedInterpretation(o):Oe.writtenInterpretation(o,Wn.restatedInterpretation(o)),variants:o.variants.length>0?o.variants:void 0,skyEvents:Pr.written(o.skyEvents),frozen:o.frozen}}function HA(o){Qo.check(o,"sighting");const t=Wi.toCurrent(o),{recording:e,provenance:i}=os.strip(t),n=GA(e);return n.provenance=i,n}function GA(o){const t=[],e=new C0({eventType:"sighting",time:Wf.read(o.time),endTime:Wf.read(o.endTime),durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:wb.read(o.place),description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Qu.fromJSON(o.timeline,t,!1),o.observerTrack?mu.fromJSON(o.observerTrack):new mu,o.weatherTrack?gu.fromJSON(o.weatherTrack):new gu,o.soundTrack?vu.fromJSON(o.soundTrack):new vu,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,(o.decor??[]).map(n=>{if(!n.facade?.plain)return n;const{plain:s,...r}=n.facade;return{...n,facade:{...r,openings:"plain"}}}),o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),ql(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.metering=o.metering,e.sampleMs=o.sampleMs,e.lens=o.lens,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle,e.events=o.events?.map(n=>n.who===void 0?{...n,who:Wi.observerIdOf(o)}:n);const i=Pr.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.frozen=o.frozen,e.loadIssues=t,Oe.expand(e),e.timeline.pruneGroups(),ln.toBounds(e),ln.toPosition(e),Oe.settle(e),e}class Wf{static read(t){return t===void 0||t.trim()===""?void 0:Dh(t)}static write(t){if(t===void 0)return;const e=jo(t);return e===""?void 0:e}}class wb{static read(t){if(t?.locations?.length)return t.locations.map(({lat:e,lng:i})=>({lat:e,lng:i,...t.name===void 0?{}:{name:t.name}}))}static write(t){if(!t?.length)return;const e=t.find(i=>i.name)?.name;return{...e===void 0?{}:{name:e},locations:t.map(({lat:i,lng:n})=>({lat:i,lng:n}))}}}class el{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=el.EN){return e[t.kind].replace("{path}",t.path).replace("{expected}",t.expected??"").replace("{found}",t.found??"")}static warn(t,e){if(t.length===0)return;const i=t.map(n=>` ${el.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
2402
2402
  ${i.join(`
2403
- `)}`)}}class ar{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!ar.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:ar.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(ar.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):ar.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:ar.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=ar.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:ar.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:ar.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return ar.isObject(t)&&"value"in t&&Object.keys(t).every(e=>e==="value"||e==="basis"||e==="rationale")}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class ur{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?ur.travelDegOver(t,e,i,i+n*1e3)/s/ur.PIXELS_PER_INSTANT:0,a=ur.flashesOver(t,n)*ur.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(ur.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=ur.directionAt(r,e,i),c=ur.directionAt(r,e,n),h=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(h)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=vr(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}}const P1=["en","fr","es","it"],VA={en:()=>De(()=>Promise.resolve().then(()=>ZA),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>De(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>De(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>De(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function WA(o){return VA[o]()}const XA={en:()=>De(()=>Promise.resolve().then(()=>NN),void 0,import.meta.url).then(o=>o.sightingMessages_en),fr:()=>De(()=>import("./SightingMessages_fr-DK90WaSj.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>De(()=>import("./SightingMessages_es-dFoOi4Xe.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>De(()=>import("./SightingMessages_it-BC3oCPqe.js"),[],import.meta.url).then(o=>o.sightingMessages_it)};function $A(o){return XA[o]()}const YA={en:()=>De(()=>Promise.resolve().then(()=>LN),void 0,import.meta.url).then(o=>o.shareMessages_en),fr:()=>De(()=>import("./ShareMessages_fr-DyOB2E5o.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>De(()=>import("./ShareMessages_es-BM5hHumO.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>De(()=>import("./ShareMessages_it-C9F8UHk_.js"),[],import.meta.url).then(o=>o.shareMessages_it)};function KA(o){return YA[o]()}function qA(o){switch(o){case"fr":return De(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return De(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return De(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}function bb(o){switch(o){case"fr":return De(()=>import("./SceneNames_fr-CRYRL6bz.js"),[],import.meta.url).then(t=>t.sceneNames_fr);case"es":return De(()=>import("./SceneNames_es-yKx3UAlW.js"),[],import.meta.url).then(t=>t.sceneNames_es);case"it":return De(()=>import("./SceneNames_it-YZZnoK8j.js"),[],import.meta.url).then(t=>t.sceneNames_it);default:return Promise.resolve(void 0)}}const xb={play:"Play",clickToPlay:"Click to play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:el.EN},ZA=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:xb},Symbol.toStringTag,{value:"Module"})),Sb=Math.PI/180,JA=180/Math.PI,jA=256,Eb=19,QA=1.25;function Ab(o,t){return 156543.03392*Math.cos(o*Sb)/2**t}function _b(o,t){return Ab(o,t)*jA}function t3(o,t){let e=0;for(;e<Eb&&_b(o,e+1)>=t;)e++;return e}function Tb(o,t){return _b(o,t)}function e3(o,t){const e=t*QA;let i=0;for(;i<Eb&&Ab(o,i)>e;)i++;return i}function xf(o){const t=o*Sb;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function Rb(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:xf(t)*i}}function Ib(o,t,e){const i=xf(o.north),n=xf(o.south);return{x:(t-o.west)/(o.east-o.west),y:(xf(e)-i)/(n-i)}}function i3(o,t,e){const{x:i,y:n}=Rb(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function n3(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=jM(o.y,t);return{south:jM(o.y+1,t),north:n,west:e,east:i}}function jM(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*JA}function Db(o,t,e,i){const n=i3(o,t,e),s=Math.floor(i/2),r=[];for(let h=-s;h<=s;h++)for(let l=-s;l<=s;l++)r.push({x:n.x+l,y:n.y+h,z:e});const a=r.map(n3),c={south:Math.min(...a.map(h=>h.south)),north:Math.max(...a.map(h=>h.north)),west:Math.min(...a.map(h=>h.west)),east:Math.max(...a.map(h=>h.east))};return{tiles:r,bounds:c}}const s3="#2ec4ff";class $o{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=Ib(t,i,e);return{x:n.x*this.width,y:n.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const n=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??s3;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,h)=>Math.hypot(h.x-a.x,h.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?h:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,h=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-h,c+h),s.closePath();const l=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);l.addColorStop(0,"rgba(255, 224, 130, 0.55)"),l.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),l.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=l,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:$o.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,$o.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=de(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=$o.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?$o.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(de(r,t.east,r,t.west).x)/this.width,h=$o.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(h===void 0)return;const l=h/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+l,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(h>=1e3?`${h/1e3} km`:`${h} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class di{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 di.including(t.boundsAround(di.MIN_SPAN_M,di.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const n=Math.min(di.MAX_ZOOM,Math.max(di.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),n=di.mercatorY01(e.north),s=di.mercatorY01(e.south),r=di.mercatorY01(i.north),a=di.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=di.mercatorY01(n.north),r=di.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(di.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=di.mercatorY01(t.north),n=di.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:di.latitudeAt(i+(this.centerY-e)*(n-i)),south:di.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=de(n,t.east,n,s).x;let a=r;for(const c of e){const{x:h,z:l}=de(c.lat,c.lng,n,s),u=Math.max(Math.abs(h),Math.abs(l));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:As(0,-a,n,s).lat,south:As(0,a,n,s).lat,east:As(a,0,n,s).lng,west:As(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=di.mercatorY01(t.north),s=di.mercatorY01(t.south);return{lat:di.latitudeAt(n+i*(s-n)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const Ws=256,QM=3,r3=32768;class a3{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(de(i,t.east,i,t.west).x),r=Math.abs(de(t.north,n,t.south,n).z),a=t3(i,Math.max(s,r)),{tiles:c}=Db(n,i,a,QM),h=QM*Ws,l=new Float32Array(h*h),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,l,h)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let m=0;m<e.width;m++){const g=t.west+(t.east-t.west)*(m/(e.width-1));d[f*e.width+m]=this.sampleAt(p,g,a,u,l,h)}}return{heights:d,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=Ws,c.height=Ws;const h=c.getContext("2d");if(!h)throw new Error("2D canvas context unavailable");h.drawImage(a,0,0);const{data:l}=h.getImageData(0,0,Ws,Ws),u=(t.x-e.x)*Ws,d=(t.y-e.y)*Ws;for(let f=0;f<Ws;f++)for(let p=0;p<Ws;p++){const m=(f*Ws+p)*4,g=l[m]*256+l[m+1]+l[m+2]/256-r3,v=u+p,M=d+f;i[M*n+v]=g}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=Rb(e,t,i),h=(a-n.x)*Ws,l=(c-n.y)*Ws,u=Math.max(0,Math.min(r-1,Math.floor(h))),d=Math.max(0,Math.min(r-1,Math.floor(l))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),m=h-u,g=l-d,v=s[d*r+u],M=s[d*r+f],w=s[p*r+u],y=s[p*r+f],b=v+(M-v)*m,S=w+(y-w)*m;return b+(S-b)*g}}class P0{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const M=i+2+v*12;s.set(e.getUint16(M,!0),{type:e.getUint16(M+2,!0),count:e.getUint32(M+4,!0),value:e.getUint32(M+8,!0)})}const r=(v,M)=>{const w=s.get(v);if(w===void 0){if(M===void 0)throw new Error(`TIFF without tag ${v}`);return M}return w.type===3?w.value&65535:w.value},a=v=>{const M=s.get(v);if(M===void 0)throw new Error(`TIFF without tag ${v}`);const w=M.type===3?2:4,y=[];if(M.count*w<=4){const b=new DataView(new ArrayBuffer(4));b.setUint32(0,M.value,!0);for(let S=0;S<M.count;S++)y.push(w===2?b.getUint16(S*2,!0):b.getUint32(0,!0))}else for(let b=0;b<M.count;b++)y.push(w===2?e.getUint16(M.value+b*2,!0):e.getUint32(M.value+b*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),h=r(257),l=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),m=new Uint8Array(c*h*l*(u/8));let g=0;for(let v=0;v<f.length&&g<m.length;v++){const M=Math.min(p[v],m.length-g);m.set(new Uint8Array(t,f[v],M),g),g+=M}if(g<m.length)throw new Error("Truncated TIFF");return new P0(c,h,l,d?new Float32Array(m.buffer):m)}}class Ha extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class o3{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class ke{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??ke.WMS,this.wfs=t.wfsEndpoint??ke.WFS}static radius(t){return Math.min(t,ke.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,ke.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=ke.lidarRadius(e),n=Math.ceil(2*i/ke.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,ke.HEIGHT_LAYER),this.raster(t,i,n,ke.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new Ha("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===ke.NO_DATA))throw new Ha("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),h=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,h[u]=d>120&&f<90&&p<90?1:0}const l=2*i/n;return{size:n,metresPerPixel:l,heights:a,vegetation:c,building:h,structures:new o3(a,c,h,n,l)}}async laserDate(t){return ke.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return ke.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=ke.radius(e),n=Math.min(ke.MAX_PHOTO_PIXELS,Math.ceil(2*i/ke.METRES_PER_PIXEL)),s=await this.raster(t,i,n,ke.PHOTO_LAYER);if(s.samples<3)throw new Ha("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=ke.radius(e),s=n/ke.METRES_PER_DEGREE,r=n/(ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[h,l,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,ke.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],g=[...f,...m];return{bridges:h,elevatedRoads:l,elevatedRailways:u,lines:d,buildings:g,zones:p,mapDate:ke.latest(g.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=ke.MAX_WHOLE_M/ke.METRES_PER_DEGREE;let h;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,m]=ke.extent(u);if(d>=n&&f>=s&&p<=r&&m<=a)continue;const g=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(m,a+c)];h=h?[Math.min(h[0],g[0]),Math.min(h[1],g[1]),Math.max(h[2],g[2]),Math.max(h[3],g[3])]:g}if(!h)return[];const l=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${h.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,ke.BUILDING_PROPERTIES,1e3)).filter(d=>!l.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const h of c)n.push(h.map(l=>({lat:l[1],lng:l[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/ke.METRES_PER_DEGREE,r=e/(ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(h=>h.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(h){throw new Ha("unreachable",h instanceof Error?h.message:String(h))}if(!c.ok)throw new Ha("unreachable",`The survey answered ${c.status}`);try{return P0.parse(await c.arrayBuffer())}catch(h){throw new Ha("unreachable",h instanceof Error?h.message:String(h))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new Ha("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new Ha("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class io{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>de(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>de(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],h=s[a+1],l=Math.hypot(h.x-c.x,h.z-c.z);if(l<1e-6)continue;const u=Math.max(1,Math.ceil(l/io.SAMPLE_M)),d=Math.atan2(h.x-c.x,-(h.z-c.z));for(let f=0;f<=u;f++){const p=f/u,m=io.nearest(n,c.x+(h.x-c.x)*p,c.z+(h.z-c.z)*p);m.distanceM>io.NEAR_M||io.angleBetween(d,m.heading)<=io.ALIGNED_DEG&&(r+=l/u)}}return r>=io.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,h=a.z-r.z,l=c*c+h*h,u=l<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*h)/l)),d=Math.hypot(e-(r.x+c*u),i-(r.z+h*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-h)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class Ce{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??Ce.WMS,this.timeoutMs=t.timeoutMs??Ce.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Ce.MAX_WINDOW_M,this.geoplatform=new ke({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!ke.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(de(n.lat,t.east,n.lat,t.west).x),r=Math.abs(de(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},h={south:t.south-c.y/Ce.METRES_PER_DEGREE,north:t.north+c.y/Ce.METRES_PER_DEGREE,west:t.west-c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},l=m=>Math.min(Ce.MAX_PIXELS,Math.max(Ce.MIN_PIXELS,Math.ceil(m/Ce.METRES_PER_PIXEL))),u={width:l(s+2*c.x),height:l(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>Ce.COARSE_METRES_PER_PIXEL;for(const m of p?[...Ce.LAYERS].reverse():Ce.LAYERS)try{const g=await this.heights(h,u,m);m===Ce.LAYERS[0]&&await this.layBridgeDecks(g,h,u,i?.route);const v=this.sample(g,e,t,h,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${m} does not cover this place`)}catch(g){f=g}throw f}finer(t,e,i){if(t.width<Ce.MESH_FROM_VERTICES||t.height<Ce.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Ce.FINE_SPACING_M),c=Math.max(r-1,Math.min(Ce.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return P0.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>Ce.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>io.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,Ce.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(g,[v,M,w])=>s.values[g*s.samples]===v&&s.values[g*s.samples+1]===M&&s.values[g*s.samples+2]===w,a=t.width,c=t.height,h=new Uint8Array(a*c);let l=!1;for(let g=0;g<h.length;g++)r(g,Ce.DECK)&&(h[g]=1,l=!0);if(!l)return;const u=Ce.DECK_END_PIXELS,d=[];for(let g=0;g<h.length;g++){if(h[g]!==1)continue;const v=g%a,M=(g-v)/a;for(let w=-u;w<=u;w++)for(let y=-u;y<=u;y++){const b=v+y,S=M+w;if(b<0||S<0||b>=a||S>=c)continue;const _=S*a+b;h[_]===0&&r(_,Ce.NO_CLASS)&&d.push(_)}}for(const g of d)h[g]=1;const f=this.paint(n,e,a,c),p=this.touching(h,f,a,c);if(p.every(g=>g===0))return;const m=await this.heights(e,i,Ce.SURFACE_LAYER);if(m.width!==a||m.height!==c)return;for(let g=0;g<p.length;g++){if(p[g]===0)continue;const v=m.values[g];Number.isFinite(v)&&v>Ce.NO_DATA_BELOW&&v>t.values[g]&&(t.values[g]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Ce.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),h=(i.north-i.south)*Ce.METRES_PER_DEGREE,l=c/s,u=h/r,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*c,y:(i.north-v.lat)/(i.north-i.south)*h}),f=(v,M)=>{const w=Math.floor(v/l),y=Math.floor(M/u);if(w<0||y<0||w>=s||y>=r)return;const b=e[y*s+w];return Number.isFinite(b)&&b>Ce.NO_DATA_BELOW?b:void 0},p=Ce.DECK_HALF_WIDTH_M,m=Ce.DECK_APPROACH_M,g=(v,M)=>{const w=Math.hypot(v.x-M.x,v.y-M.y)||1,y={x:(v.x-M.x)/w,y:(v.y-M.y)/w},b=[0,m/2,m].map(S=>f(v.x+y.x*S,v.y+y.y*S)).filter(S=>S!==void 0);return b.length>0?Math.max(...b):void 0};for(const v of Ce.chains(n.map(M=>M.map(d)))){const M=[0];for(let D=1;D<v.length;D++)M.push(M[D-1]+Math.hypot(v[D].x-v[D-1].x,v[D].y-v[D-1].y));const w=M[M.length-1];if(w<1||w>Ce.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),b=g(v[v.length-1],v[v.length-2]);if(y===void 0||b===void 0)continue;const S=p+m,_=Math.max(0,Math.floor((Math.min(...v.map(D=>D.x))-S)/l)),x=Math.min(s-1,Math.ceil((Math.max(...v.map(D=>D.x))+S)/l)),A=Math.max(0,Math.floor((Math.min(...v.map(D=>D.y))-S)/u)),I=Math.min(r-1,Math.ceil((Math.max(...v.map(D=>D.y))+S)/u));for(let D=A;D<=I;D++)for(let C=_;C<=x;C++){const N=Ce.nearestAlong(v,M,{x:(C+.5)*l,y:(D+.5)*u});if(N.distance>p||N.s<-m||N.s>w+m)continue;const L=y+(b-y)*Math.min(1,Math.max(0,N.s/w)),P=D*s+C;e[P]>=L||(t.values[P]=L)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],h=s[0],l=s[s.length-1];if(n(l,c[0]))s=[...s,...c.slice(1)];else if(n(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(h,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(h,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,h=a.y-r.y,l=c*c+h*h;if(l<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*h)/l;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+h*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(l),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let h=0;h<c.length-1;h++){const l=r(c[h].lng),u=a(c[h].lat),d=r(c[h+1].lng),f=a(c[h+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-l,f-u)*2));for(let m=0;m<=p;m++){const g=Math.floor(l+(d-l)*m/p),v=Math.floor(u+(f-u)*m/p);for(let M=-1;M<=1;M++)for(let w=-1;w<=1;w++){const y=g+w,b=v+M;y>=0&&b>=0&&y<i&&b<n&&(s[b*i+y]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],h=[a];r[a]=1;let l=!1;for(;h.length>0;){const u=h.pop();c.push(u),e[u]===1&&(l=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let m=-1;m<=1;m++){const g=d+m,v=f+p;if(g<0||v<0||g>=i||v>=n)continue;const M=v*i+g;t[M]===1&&r[M]===0&&(r[M]=1,h.push(M))}}if(l)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,h=new Float32Array(a*c),l=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const m=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),g=(n.north-m)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const w=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,w,g,Math.max(1,u),Math.max(1,d)):this.bilinear(t,w,g),b=p*a+v;y===void 0?f++:(h[b]=y,l[b]=1)}}if(!(f===a*c||f/(a*c)>Ce.MAX_HOLE_SHARE))return this.fill(h,l,a,c),h}tent(t,e,i,n,s){let r=0,a=0,c=0;const h=Math.max(0,Math.ceil(i-s)),l=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=h;f<=l;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let m=u;m<=d;m++){const g=p*(1-Math.abs(m-e)/n);if(g<=0)continue;c+=g;const v=t.at(m,f);!Number.isFinite(v)||v<Ce.NO_DATA_BELOW||(r+=g*v,a+=g)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),h=Math.max(0,Math.min(1,i-s)),l=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const g of[l,u,d,f])if(!Number.isFinite(g)||g<Ce.NO_DATA_BELOW)return;const p=l+(u-l)*c,m=d+(f-d)*c;return p+(m-p)*h}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const h=a*i+c;if(e[h])continue;let l=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,m=c+f;p<0||m<0||p>=n||m>=i||!e[p*i+m]||(l+=t[p*i+m],u++)}u>0&&r.push([h,l/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class c3{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const Sf=256,h3=5;async function Cb(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(de(n,o.east,n,o.west).x),a=Math.abs(de(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:h,gridSize:l}=l3(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=Db(s,n,h,l),f=l*Sf,p=document.createElement("canvas");p.width=f,p.height=f;const m=p.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=u[0];await Promise.all(u.map(async y=>{const b=e(y),S=await i(b);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${b}`);const _=await createImageBitmap(await S.blob());m.drawImage(_,(y.x-g.x)*Sf,(y.y-g.y)*Sf)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const M=document.createElement("canvas");M.width=v,M.height=v;const w=M.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(p,0,0,f,f,0,0,v,v),{source:M,width:v,height:v,bounds:d}}function l3(o,t,e){let i=e3(o,t/Math.max(1,e)),n=ty(o,i,t);for(;n>h3&&i>0;)i--,n=ty(o,i,t);return{zoom:i,gridSize:n,mPerPixel:Tb(o,i)/Sf}}function ty(o,t,e){const i=Math.ceil(e/2/Tb(o,t));return Math.max(3,2*i+1)}class Ob{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 Cb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class ws{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=ws.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,h=(s+a)/2,l=ws.FRANCE;return c>=l.south&&c<=l.north&&h>=l.west&&h<=l.east?[ws.FRANCE_ENDPOINT,...e.filter(d=>d!==ws.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=ws.queue.then(t,t);return ws.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??ws.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(ws.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,ws.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class no{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 ws(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${no.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:no.surfaceOf(s),widthM:no.widthOf(s),...no.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),h=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...h?{kind:h}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:no.WIDTH_M[t.highway]??no.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 fp="https://ufoathome.org/roads/index.json";class dh{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??dh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
2404
- `);let e=dh.shared.get(t);return e||(e=this.fetchFirstAvailable(),dh.shared.set(t,e),e.then(i=>{i.length===0&&dh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.161.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==fp?[e,fp]:[fp]).map(i=>i+t)}}class oo{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 ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>oo.wayOf(i,n))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const n=String(t.properties.nature??""),s=oo.BY_NATURE[n]??oo.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),h=oo.DIRECTIONS[String(t.properties.sens_de_circulation??"")],l=oo.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...l?{kind:l}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...h?{direction:h}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class u3{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(oo.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Bu{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>Bu.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const h=a.map(l=>Bu.open(l.map(u=>({lat:u[1],lng:u[0]})))).filter(l=>l.length>=3);return h.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:h}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class Yo{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new ws(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return Yo.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=h=>(r.members??[]).filter(l=>l.type==="way"&&l.role===h&&l.ref!==void 0&&i.has(l.ref)).map(l=>(s.add(l.ref),i.get(l.ref))),c=Yo.rings(a("inner"));for(const[h,l]of Yo.rings(a("outer")).entries()){const u=c.filter(d=>Yo.contains(l,d[0]));n.push({id:`osm-r${r.id}-${h}`,rings:[l,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of Yo.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],h=s[s.length-1];if(e(h,c[0]))s=[...s,...c.slice(1)];else if(e(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class d3{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Bu.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const pp="https://ufoathome.org/water/index.json";class fh{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??fh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
2405
- `);let e=fh.shared.get(t);return e||(e=this.fetchFirstAvailable(),fh.shared.set(t,e),e.then(i=>{i.length===0&&fh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.161.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==pp?[e,pp]:[pp]).map(i=>i+t)}}class fs{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=fs.key(t);let i=fs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),fs.asked.set(e,i),i.catch(()=>fs.asked.delete(e))),structuredClone(await i)}static forget(){fs.asked.clear()}static key(t){return`v${fs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await fs.openCache(),n=fs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<fs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&fs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-fs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(fs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class co{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 ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>co.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=co.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),h=Number(t.properties.position_par_rapport_au_sol),l=t.properties.cpx_toponyme,u=co.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=co.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>co.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof l=="string"&&l.length>0?{name:l}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(h)?h:0,points:m}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Cn{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 ws(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${Cn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return Cn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=Cn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>de(v.lat,v.lng,n.lat,n.lng)),c=new Map,h=new Map,l=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of Cn.samples(a)){u++;const M=Cn.waysAt(d,v);if(M.length===0)continue;const[w]=M;w.name&&c.set(w.name,(c.get(w.name)??0)+1),w.voltageV&&h.set(w.voltageV,(h.get(w.voltageV)??0)+1);for(const y of new Set(M.flatMap(b=>b.services)))l.set(y,(l.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,w)=>w[1]-M[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(h)),g=[...l.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...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 i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Cn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=Cn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=Cn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>de(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=Cn.SAMPLE_M/2;a<n;a+=Cn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(Cn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],h=s.path[a+1],l=h.x-c.x,u=h.z-c.z,d=Math.hypot(l,u);if(d<1e-6||Math.abs((l*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*l+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+l*f),e.z-(c.z+u*f));p<=Cn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class ph{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 ws(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${ph.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Cn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=Cn.voltageOf(r),h=ph.kindOf(r),l=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=ph.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:h,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(l)&&l>300?l:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:ph.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class f3{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(!co.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class an{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=an.key(t);let i=an.asked.get(e)??an.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},an.asked.set(e,i),n.catch(()=>an.asked.delete(e))}return structuredClone(await i.answer)}static forget(){an.asked.clear(),an.failedAt=-1/0}static key(t){return`v${an.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of an.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await an.openCache(),n=an.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:h}=await a.json();if(Array.isArray(h)){if(this.now()-c<an.MAX_AGE_MS)return h;s=h}}}catch{}if(this.now()-an.failedAt<an.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(an.failedAt=this.now(),s)return s;throw a}return i&&an.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-an.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(an.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const mp="https://ufoathome.org/railways/index.json";class mh{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??mh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
2406
- `);let e=mh.shared.get(t);return e||(e=this.fetchFirstAvailable(),mh.shared.set(t,e),e.then(i=>{i.length===0&&mh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.161.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==mp?[e,mp]:[mp]).map(i=>i+t)}}function Pb(){return{elevation:p3(),imagery:Nb(),roads:m3(),water:g3(),railways:v3()}}function p3(){return new c3(new Ce,new a3)}function Nb(){return new Ob}function m3(){return new dh({fallback:new u3(new oo,new no)})}function g3(){return new fh({fallback:new fs(new d3(new Bu,new Yo))})}function v3(){return new mh({fallback:new an(new f3(new co,new ph))})}const M3=new Set,Jr="show-observer-map",jr="hide-milestones",ec="minified";class Ge extends HTMLElement{static get observedAttributes(){return["src",Jr,jr,ec]}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 di;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=C0.create();issues=[];issueCheck=0;sightingAudio=new FA;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>Ge.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=xb;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Ge.setIcon(this.moreButton,t?Jt.UNFOLDED:Jt.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()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ge.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=di.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=di.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ge.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=di.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${DA}</style>${IA}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new tl(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new $o(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),h=this.player.seekableDuration;if(c.width<=0||h<=0)return;const l=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*h;this.player.seek(l),this.miniScrubTime.textContent=this.formatElapsedAt(l),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Jr&&this.applyObserverMapDefault(),t===jr&&this.setMilestonesShown(!this.hasAttribute(jr)),t===ec){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(ec)}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(kb)))};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 Eo.recording(t)}get sightingData(){return zA(this.currentSighting)}set sightingData(t){const e=Wi.toCurrent(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=HA(e),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await De(async()=>{const{default:r}=await import("./sightingSchema-CnDwuCov.js");return{default:r}},[],import.meta.url);n=new ar(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],el.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(y3,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=this.messages.recordingIssues.replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=el.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}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 selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!this.referenceOpacityTouched&&t.length>0&&(this.referenceOpacityInput.value=String(t[0].opacity));for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const h=document.createElement("input");return h.type="range",h.min="0",h.max="1",h.step="0.05",h.value=String(i.opacity),h.title=this.messages.referenceOpacity,h.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),h.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,h.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),h.addEventListener("input",()=>{i.opacity=Number(h.value),this.dispatchReferenceView()}),s.append(r,h),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ge.setIcon(this.referencesButton,i?Jt.PICTURES_ON:Jt.PICTURES_OFF);const n=e?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Ge.setIcon(this.tracesButton,this.tracesShownState?Jt.TRACES_ON:Jt.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?ql(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const h=document.createElement("i");h.className="seek-played",a.append(c,h),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:h,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ge.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ge.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?lp(a,s):void 0,h=c?this.said.read(c.label)??"":"",l=c?this.said.read(c.note):void 0,u=l?`${h} — ${l}`:h;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new tl(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=Ge.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?lp(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=ur.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ge.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ge.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ge.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ge.EXPOSURE_STEP_PX),s=Math.min(Ge.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const h=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),l=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(h,l))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=ki.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}onFrame(t,e){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:M3;this.canvasRenderer.setStarPoints(ki.starPointsOf(this.sighting.instrument,Le(this.sighting,t)?.fNumber));const n=(Le(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,h]of c.shapes){const l=c.share,u=l===1?h:{...h,transparency:1-(1-h.transparency)*l};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,h]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...h,selected:!0}):this.canvasRenderer.paintMemberOutline(h):this.canvasRenderer.paintSelectionOnly(this.shifted(h,r)));const a=this.selectionShown&&i.size>1?Us.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(h=>h.transparency<1).map(h=>this.shifted(h,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(db(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 CA(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Ge.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"?Jt.PLAY:Jt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ge.icons.get(t)!==e&&(Ge.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Ge.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(),Ge.setIcon(this.playPauseButton,t?Jt.PAUSE:Jt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Jr),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;Ge.setIcon(this.observerMapButton,t?Jt.MAP_ON:Jt.MAP_OFF);const e=t?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages.zoomMapIn],[this.mapZoomOutButton,this.messages.zoomMapOut],[this.mapFitButton,this.messages.fitMap]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Ph.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=di.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?di.expand(t,Ge.OBSERVER_MAP_IMAGERY_AHEAD):t,n=di.IMAGERY_PX*(e?1+2*Ge.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapFrozenImagery,r=s?void 0:Nb();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?di.expand(t,Ge.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(t){t!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=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 observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(h,l,u)=>{for(const d of e)if(!(d.x+d.width<h-u||d.x>l+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Ge.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Le(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},Ge.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?lp(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?ql(this.currentSighting.milestones):[]){const a=Le(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?$r.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(ki.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,ql(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,Ge.setIcon(this.milestonesButton,this.milestonesShown?Jt.MILESTONES_ON:Jt.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=Le(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=vr(i,t),{lat:s,lng:r}=As(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=Le(this.currentSighting,this.currentTime),s=$r.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ni.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=Ge.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 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)),Ge.setIcon(this.miniMuteButton,this.mutedState?Jt.MUTED:Jt.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){Ge.setIcon(this.muteButton,Jt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Ge.setIcon(this.muteButton,this.mutedState?Jt.MUTED:Jt.VOLUME);const i=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ge.setIcon(this.fullscreenButton,t?Jt.EXIT_FULLSCREEN:Jt.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 Es(Ao.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=C1(Ao.preferencesFor(this),P1);if(t===this.messagesLanguage||t==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=t;const e=await WA(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.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=ub(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Wm(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return Ga(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?iy(ey(this.realStartMs+i)):Ga(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Ga(t):Ga(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Ga(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return Ga(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Ga(this.currentSighting.timeline.duration):this.canShowClockTime?iy(ey(this.realStartMs+this.realDurationMs)):Ga(this.realDurationMs)}}function ey(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function iy(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function Ga(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Km="rr0-ufo";function Lb(){customElements.get(Km)||customElements.define(Km,Ge)}const y3="recordingissues",kb="minifiedreset";/**
2403
+ `)}`)}}class ar{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!ar.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:ar.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(ar.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):ar.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:ar.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=ar.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:ar.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:ar.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return ar.isObject(t)&&"value"in t&&Object.keys(t).every(e=>e==="value"||e==="basis"||e==="rationale")}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class ur{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?ur.travelDegOver(t,e,i,i+n*1e3)/s/ur.PIXELS_PER_INSTANT:0,a=ur.flashesOver(t,n)*ur.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(ur.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=ur.directionAt(r,e,i),c=ur.directionAt(r,e,n),h=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(h)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=vr(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}}const P1=["en","fr","es","it"],VA={en:()=>Ie(()=>Promise.resolve().then(()=>ZA),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>Ie(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>Ie(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>Ie(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function WA(o){return VA[o]()}const XA={en:()=>Ie(()=>Promise.resolve().then(()=>NN),void 0,import.meta.url).then(o=>o.sightingMessages_en),fr:()=>Ie(()=>import("./SightingMessages_fr-DQNbBD0c.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>Ie(()=>import("./SightingMessages_es-Dsr6169b.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>Ie(()=>import("./SightingMessages_it-WE-_Cuu4.js"),[],import.meta.url).then(o=>o.sightingMessages_it)};function $A(o){return XA[o]()}const YA={en:()=>Ie(()=>Promise.resolve().then(()=>LN),void 0,import.meta.url).then(o=>o.shareMessages_en),fr:()=>Ie(()=>import("./ShareMessages_fr-DyOB2E5o.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>Ie(()=>import("./ShareMessages_es-BM5hHumO.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>Ie(()=>import("./ShareMessages_it-C9F8UHk_.js"),[],import.meta.url).then(o=>o.shareMessages_it)};function KA(o){return YA[o]()}function qA(o){switch(o){case"fr":return Ie(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return Ie(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return Ie(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}function bb(o){switch(o){case"fr":return Ie(()=>import("./SceneNames_fr-CRYRL6bz.js"),[],import.meta.url).then(t=>t.sceneNames_fr);case"es":return Ie(()=>import("./SceneNames_es-yKx3UAlW.js"),[],import.meta.url).then(t=>t.sceneNames_es);case"it":return Ie(()=>import("./SceneNames_it-YZZnoK8j.js"),[],import.meta.url).then(t=>t.sceneNames_it);default:return Promise.resolve(void 0)}}const xb={play:"Play",clickToPlay:"Click to play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:el.EN},ZA=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:xb},Symbol.toStringTag,{value:"Module"})),Sb=Math.PI/180,JA=180/Math.PI,jA=256,Eb=19,QA=1.25;function Ab(o,t){return 156543.03392*Math.cos(o*Sb)/2**t}function _b(o,t){return Ab(o,t)*jA}function t3(o,t){let e=0;for(;e<Eb&&_b(o,e+1)>=t;)e++;return e}function Tb(o,t){return _b(o,t)}function e3(o,t){const e=t*QA;let i=0;for(;i<Eb&&Ab(o,i)>e;)i++;return i}function xf(o){const t=o*Sb;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function Rb(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:xf(t)*i}}function Ib(o,t,e){const i=xf(o.north),n=xf(o.south);return{x:(t-o.west)/(o.east-o.west),y:(xf(e)-i)/(n-i)}}function i3(o,t,e){const{x:i,y:n}=Rb(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function n3(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=jM(o.y,t);return{south:jM(o.y+1,t),north:n,west:e,east:i}}function jM(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*JA}function Db(o,t,e,i){const n=i3(o,t,e),s=Math.floor(i/2),r=[];for(let h=-s;h<=s;h++)for(let l=-s;l<=s;l++)r.push({x:n.x+l,y:n.y+h,z:e});const a=r.map(n3),c={south:Math.min(...a.map(h=>h.south)),north:Math.max(...a.map(h=>h.north)),west:Math.min(...a.map(h=>h.west)),east:Math.max(...a.map(h=>h.east))};return{tiles:r,bounds:c}}const s3="#2ec4ff";class $o{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=Ib(t,i,e);return{x:n.x*this.width,y:n.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const n=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??s3;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,h)=>Math.hypot(h.x-a.x,h.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?h:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,h=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-h,c+h),s.closePath();const l=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);l.addColorStop(0,"rgba(255, 224, 130, 0.55)"),l.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),l.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=l,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:$o.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,$o.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=de(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=$o.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?$o.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(de(r,t.east,r,t.west).x)/this.width,h=$o.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(h===void 0)return;const l=h/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+l,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(h>=1e3?`${h/1e3} km`:`${h} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class di{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 di.including(t.boundsAround(di.MIN_SPAN_M,di.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const n=Math.min(di.MAX_ZOOM,Math.max(di.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),n=di.mercatorY01(e.north),s=di.mercatorY01(e.south),r=di.mercatorY01(i.north),a=di.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=di.mercatorY01(n.north),r=di.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(di.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=di.mercatorY01(t.north),n=di.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:di.latitudeAt(i+(this.centerY-e)*(n-i)),south:di.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=de(n,t.east,n,s).x;let a=r;for(const c of e){const{x:h,z:l}=de(c.lat,c.lng,n,s),u=Math.max(Math.abs(h),Math.abs(l));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:As(0,-a,n,s).lat,south:As(0,a,n,s).lat,east:As(a,0,n,s).lng,west:As(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=di.mercatorY01(t.north),s=di.mercatorY01(t.south);return{lat:di.latitudeAt(n+i*(s-n)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const Ws=256,QM=3,r3=32768;class a3{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(de(i,t.east,i,t.west).x),r=Math.abs(de(t.north,n,t.south,n).z),a=t3(i,Math.max(s,r)),{tiles:c}=Db(n,i,a,QM),h=QM*Ws,l=new Float32Array(h*h),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,l,h)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let m=0;m<e.width;m++){const g=t.west+(t.east-t.west)*(m/(e.width-1));d[f*e.width+m]=this.sampleAt(p,g,a,u,l,h)}}return{heights:d,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=Ws,c.height=Ws;const h=c.getContext("2d");if(!h)throw new Error("2D canvas context unavailable");h.drawImage(a,0,0);const{data:l}=h.getImageData(0,0,Ws,Ws),u=(t.x-e.x)*Ws,d=(t.y-e.y)*Ws;for(let f=0;f<Ws;f++)for(let p=0;p<Ws;p++){const m=(f*Ws+p)*4,g=l[m]*256+l[m+1]+l[m+2]/256-r3,v=u+p,M=d+f;i[M*n+v]=g}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=Rb(e,t,i),h=(a-n.x)*Ws,l=(c-n.y)*Ws,u=Math.max(0,Math.min(r-1,Math.floor(h))),d=Math.max(0,Math.min(r-1,Math.floor(l))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),m=h-u,g=l-d,v=s[d*r+u],M=s[d*r+f],w=s[p*r+u],y=s[p*r+f],b=v+(M-v)*m,S=w+(y-w)*m;return b+(S-b)*g}}class P0{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const M=i+2+v*12;s.set(e.getUint16(M,!0),{type:e.getUint16(M+2,!0),count:e.getUint32(M+4,!0),value:e.getUint32(M+8,!0)})}const r=(v,M)=>{const w=s.get(v);if(w===void 0){if(M===void 0)throw new Error(`TIFF without tag ${v}`);return M}return w.type===3?w.value&65535:w.value},a=v=>{const M=s.get(v);if(M===void 0)throw new Error(`TIFF without tag ${v}`);const w=M.type===3?2:4,y=[];if(M.count*w<=4){const b=new DataView(new ArrayBuffer(4));b.setUint32(0,M.value,!0);for(let S=0;S<M.count;S++)y.push(w===2?b.getUint16(S*2,!0):b.getUint32(0,!0))}else for(let b=0;b<M.count;b++)y.push(w===2?e.getUint16(M.value+b*2,!0):e.getUint32(M.value+b*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),h=r(257),l=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),m=new Uint8Array(c*h*l*(u/8));let g=0;for(let v=0;v<f.length&&g<m.length;v++){const M=Math.min(p[v],m.length-g);m.set(new Uint8Array(t,f[v],M),g),g+=M}if(g<m.length)throw new Error("Truncated TIFF");return new P0(c,h,l,d?new Float32Array(m.buffer):m)}}class Ha extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class o3{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class ke{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??ke.WMS,this.wfs=t.wfsEndpoint??ke.WFS}static radius(t){return Math.min(t,ke.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,ke.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=ke.lidarRadius(e),n=Math.ceil(2*i/ke.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,ke.HEIGHT_LAYER),this.raster(t,i,n,ke.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new Ha("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===ke.NO_DATA))throw new Ha("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),h=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,h[u]=d>120&&f<90&&p<90?1:0}const l=2*i/n;return{size:n,metresPerPixel:l,heights:a,vegetation:c,building:h,structures:new o3(a,c,h,n,l)}}async laserDate(t){return ke.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return ke.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=ke.radius(e),n=Math.min(ke.MAX_PHOTO_PIXELS,Math.ceil(2*i/ke.METRES_PER_PIXEL)),s=await this.raster(t,i,n,ke.PHOTO_LAYER);if(s.samples<3)throw new Ha("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=ke.radius(e),s=n/ke.METRES_PER_DEGREE,r=n/(ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[h,l,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,ke.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],g=[...f,...m];return{bridges:h,elevatedRoads:l,elevatedRailways:u,lines:d,buildings:g,zones:p,mapDate:ke.latest(g.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=ke.MAX_WHOLE_M/ke.METRES_PER_DEGREE;let h;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,m]=ke.extent(u);if(d>=n&&f>=s&&p<=r&&m<=a)continue;const g=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(m,a+c)];h=h?[Math.min(h[0],g[0]),Math.min(h[1],g[1]),Math.max(h[2],g[2]),Math.max(h[3],g[3])]:g}if(!h)return[];const l=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${h.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,ke.BUILDING_PROPERTIES,1e3)).filter(d=>!l.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const h of c)n.push(h.map(l=>({lat:l[1],lng:l[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/ke.METRES_PER_DEGREE,r=e/(ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(h=>h.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(h){throw new Ha("unreachable",h instanceof Error?h.message:String(h))}if(!c.ok)throw new Ha("unreachable",`The survey answered ${c.status}`);try{return P0.parse(await c.arrayBuffer())}catch(h){throw new Ha("unreachable",h instanceof Error?h.message:String(h))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new Ha("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new Ha("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class io{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>de(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>de(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],h=s[a+1],l=Math.hypot(h.x-c.x,h.z-c.z);if(l<1e-6)continue;const u=Math.max(1,Math.ceil(l/io.SAMPLE_M)),d=Math.atan2(h.x-c.x,-(h.z-c.z));for(let f=0;f<=u;f++){const p=f/u,m=io.nearest(n,c.x+(h.x-c.x)*p,c.z+(h.z-c.z)*p);m.distanceM>io.NEAR_M||io.angleBetween(d,m.heading)<=io.ALIGNED_DEG&&(r+=l/u)}}return r>=io.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,h=a.z-r.z,l=c*c+h*h,u=l<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*h)/l)),d=Math.hypot(e-(r.x+c*u),i-(r.z+h*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-h)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class Ce{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??Ce.WMS,this.timeoutMs=t.timeoutMs??Ce.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Ce.MAX_WINDOW_M,this.geoplatform=new ke({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!ke.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(de(n.lat,t.east,n.lat,t.west).x),r=Math.abs(de(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},h={south:t.south-c.y/Ce.METRES_PER_DEGREE,north:t.north+c.y/Ce.METRES_PER_DEGREE,west:t.west-c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},l=m=>Math.min(Ce.MAX_PIXELS,Math.max(Ce.MIN_PIXELS,Math.ceil(m/Ce.METRES_PER_PIXEL))),u={width:l(s+2*c.x),height:l(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>Ce.COARSE_METRES_PER_PIXEL;for(const m of p?[...Ce.LAYERS].reverse():Ce.LAYERS)try{const g=await this.heights(h,u,m);m===Ce.LAYERS[0]&&await this.layBridgeDecks(g,h,u,i?.route);const v=this.sample(g,e,t,h,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${m} does not cover this place`)}catch(g){f=g}throw f}finer(t,e,i){if(t.width<Ce.MESH_FROM_VERTICES||t.height<Ce.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Ce.FINE_SPACING_M),c=Math.max(r-1,Math.min(Ce.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return P0.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>Ce.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>io.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,Ce.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(g,[v,M,w])=>s.values[g*s.samples]===v&&s.values[g*s.samples+1]===M&&s.values[g*s.samples+2]===w,a=t.width,c=t.height,h=new Uint8Array(a*c);let l=!1;for(let g=0;g<h.length;g++)r(g,Ce.DECK)&&(h[g]=1,l=!0);if(!l)return;const u=Ce.DECK_END_PIXELS,d=[];for(let g=0;g<h.length;g++){if(h[g]!==1)continue;const v=g%a,M=(g-v)/a;for(let w=-u;w<=u;w++)for(let y=-u;y<=u;y++){const b=v+y,S=M+w;if(b<0||S<0||b>=a||S>=c)continue;const _=S*a+b;h[_]===0&&r(_,Ce.NO_CLASS)&&d.push(_)}}for(const g of d)h[g]=1;const f=this.paint(n,e,a,c),p=this.touching(h,f,a,c);if(p.every(g=>g===0))return;const m=await this.heights(e,i,Ce.SURFACE_LAYER);if(m.width!==a||m.height!==c)return;for(let g=0;g<p.length;g++){if(p[g]===0)continue;const v=m.values[g];Number.isFinite(v)&&v>Ce.NO_DATA_BELOW&&v>t.values[g]&&(t.values[g]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Ce.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),h=(i.north-i.south)*Ce.METRES_PER_DEGREE,l=c/s,u=h/r,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*c,y:(i.north-v.lat)/(i.north-i.south)*h}),f=(v,M)=>{const w=Math.floor(v/l),y=Math.floor(M/u);if(w<0||y<0||w>=s||y>=r)return;const b=e[y*s+w];return Number.isFinite(b)&&b>Ce.NO_DATA_BELOW?b:void 0},p=Ce.DECK_HALF_WIDTH_M,m=Ce.DECK_APPROACH_M,g=(v,M)=>{const w=Math.hypot(v.x-M.x,v.y-M.y)||1,y={x:(v.x-M.x)/w,y:(v.y-M.y)/w},b=[0,m/2,m].map(S=>f(v.x+y.x*S,v.y+y.y*S)).filter(S=>S!==void 0);return b.length>0?Math.max(...b):void 0};for(const v of Ce.chains(n.map(M=>M.map(d)))){const M=[0];for(let D=1;D<v.length;D++)M.push(M[D-1]+Math.hypot(v[D].x-v[D-1].x,v[D].y-v[D-1].y));const w=M[M.length-1];if(w<1||w>Ce.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),b=g(v[v.length-1],v[v.length-2]);if(y===void 0||b===void 0)continue;const S=p+m,_=Math.max(0,Math.floor((Math.min(...v.map(D=>D.x))-S)/l)),x=Math.min(s-1,Math.ceil((Math.max(...v.map(D=>D.x))+S)/l)),A=Math.max(0,Math.floor((Math.min(...v.map(D=>D.y))-S)/u)),I=Math.min(r-1,Math.ceil((Math.max(...v.map(D=>D.y))+S)/u));for(let D=A;D<=I;D++)for(let C=_;C<=x;C++){const N=Ce.nearestAlong(v,M,{x:(C+.5)*l,y:(D+.5)*u});if(N.distance>p||N.s<-m||N.s>w+m)continue;const L=y+(b-y)*Math.min(1,Math.max(0,N.s/w)),P=D*s+C;e[P]>=L||(t.values[P]=L)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],h=s[0],l=s[s.length-1];if(n(l,c[0]))s=[...s,...c.slice(1)];else if(n(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(h,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(h,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,h=a.y-r.y,l=c*c+h*h;if(l<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*h)/l;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+h*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(l),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let h=0;h<c.length-1;h++){const l=r(c[h].lng),u=a(c[h].lat),d=r(c[h+1].lng),f=a(c[h+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-l,f-u)*2));for(let m=0;m<=p;m++){const g=Math.floor(l+(d-l)*m/p),v=Math.floor(u+(f-u)*m/p);for(let M=-1;M<=1;M++)for(let w=-1;w<=1;w++){const y=g+w,b=v+M;y>=0&&b>=0&&y<i&&b<n&&(s[b*i+y]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],h=[a];r[a]=1;let l=!1;for(;h.length>0;){const u=h.pop();c.push(u),e[u]===1&&(l=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let m=-1;m<=1;m++){const g=d+m,v=f+p;if(g<0||v<0||g>=i||v>=n)continue;const M=v*i+g;t[M]===1&&r[M]===0&&(r[M]=1,h.push(M))}}if(l)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,h=new Float32Array(a*c),l=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const m=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),g=(n.north-m)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const w=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,w,g,Math.max(1,u),Math.max(1,d)):this.bilinear(t,w,g),b=p*a+v;y===void 0?f++:(h[b]=y,l[b]=1)}}if(!(f===a*c||f/(a*c)>Ce.MAX_HOLE_SHARE))return this.fill(h,l,a,c),h}tent(t,e,i,n,s){let r=0,a=0,c=0;const h=Math.max(0,Math.ceil(i-s)),l=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=h;f<=l;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let m=u;m<=d;m++){const g=p*(1-Math.abs(m-e)/n);if(g<=0)continue;c+=g;const v=t.at(m,f);!Number.isFinite(v)||v<Ce.NO_DATA_BELOW||(r+=g*v,a+=g)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),h=Math.max(0,Math.min(1,i-s)),l=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const g of[l,u,d,f])if(!Number.isFinite(g)||g<Ce.NO_DATA_BELOW)return;const p=l+(u-l)*c,m=d+(f-d)*c;return p+(m-p)*h}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const h=a*i+c;if(e[h])continue;let l=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,m=c+f;p<0||m<0||p>=n||m>=i||!e[p*i+m]||(l+=t[p*i+m],u++)}u>0&&r.push([h,l/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class c3{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const Sf=256,h3=5;async function Cb(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(de(n,o.east,n,o.west).x),a=Math.abs(de(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:h,gridSize:l}=l3(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=Db(s,n,h,l),f=l*Sf,p=document.createElement("canvas");p.width=f,p.height=f;const m=p.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=u[0];await Promise.all(u.map(async y=>{const b=e(y),S=await i(b);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${b}`);const _=await createImageBitmap(await S.blob());m.drawImage(_,(y.x-g.x)*Sf,(y.y-g.y)*Sf)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const M=document.createElement("canvas");M.width=v,M.height=v;const w=M.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(p,0,0,f,f,0,0,v,v),{source:M,width:v,height:v,bounds:d}}function l3(o,t,e){let i=e3(o,t/Math.max(1,e)),n=ty(o,i,t);for(;n>h3&&i>0;)i--,n=ty(o,i,t);return{zoom:i,gridSize:n,mPerPixel:Tb(o,i)/Sf}}function ty(o,t,e){const i=Math.ceil(e/2/Tb(o,t));return Math.max(3,2*i+1)}class Ob{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 Cb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class ws{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=ws.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,h=(s+a)/2,l=ws.FRANCE;return c>=l.south&&c<=l.north&&h>=l.west&&h<=l.east?[ws.FRANCE_ENDPOINT,...e.filter(d=>d!==ws.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=ws.queue.then(t,t);return ws.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??ws.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(ws.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,ws.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class no{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 ws(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${no.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:no.surfaceOf(s),widthM:no.widthOf(s),...no.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),h=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...h?{kind:h}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:no.WIDTH_M[t.highway]??no.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 fp="https://ufoathome.org/roads/index.json";class dh{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??dh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
2404
+ `);let e=dh.shared.get(t);return e||(e=this.fetchFirstAvailable(),dh.shared.set(t,e),e.then(i=>{i.length===0&&dh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.162.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==fp?[e,fp]:[fp]).map(i=>i+t)}}class oo{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 ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>oo.wayOf(i,n))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const n=String(t.properties.nature??""),s=oo.BY_NATURE[n]??oo.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),h=oo.DIRECTIONS[String(t.properties.sens_de_circulation??"")],l=oo.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...l?{kind:l}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...h?{direction:h}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class u3{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(oo.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Bu{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>Bu.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const h=a.map(l=>Bu.open(l.map(u=>({lat:u[1],lng:u[0]})))).filter(l=>l.length>=3);return h.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:h}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class Yo{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new ws(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return Yo.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=h=>(r.members??[]).filter(l=>l.type==="way"&&l.role===h&&l.ref!==void 0&&i.has(l.ref)).map(l=>(s.add(l.ref),i.get(l.ref))),c=Yo.rings(a("inner"));for(const[h,l]of Yo.rings(a("outer")).entries()){const u=c.filter(d=>Yo.contains(l,d[0]));n.push({id:`osm-r${r.id}-${h}`,rings:[l,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of Yo.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],h=s[s.length-1];if(e(h,c[0]))s=[...s,...c.slice(1)];else if(e(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class d3{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Bu.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const pp="https://ufoathome.org/water/index.json";class fh{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??fh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
2405
+ `);let e=fh.shared.get(t);return e||(e=this.fetchFirstAvailable(),fh.shared.set(t,e),e.then(i=>{i.length===0&&fh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.162.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==pp?[e,pp]:[pp]).map(i=>i+t)}}class fs{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=fs.key(t);let i=fs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),fs.asked.set(e,i),i.catch(()=>fs.asked.delete(e))),structuredClone(await i)}static forget(){fs.asked.clear()}static key(t){return`v${fs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await fs.openCache(),n=fs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<fs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&fs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-fs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(fs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class co{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 ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>co.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=co.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),h=Number(t.properties.position_par_rapport_au_sol),l=t.properties.cpx_toponyme,u=co.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=co.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>co.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof l=="string"&&l.length>0?{name:l}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(h)?h:0,points:m}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Cn{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 ws(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${Cn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return Cn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=Cn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>de(v.lat,v.lng,n.lat,n.lng)),c=new Map,h=new Map,l=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of Cn.samples(a)){u++;const M=Cn.waysAt(d,v);if(M.length===0)continue;const[w]=M;w.name&&c.set(w.name,(c.get(w.name)??0)+1),w.voltageV&&h.set(w.voltageV,(h.get(w.voltageV)??0)+1);for(const y of new Set(M.flatMap(b=>b.services)))l.set(y,(l.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,w)=>w[1]-M[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(h)),g=[...l.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...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 i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Cn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=Cn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=Cn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>de(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=Cn.SAMPLE_M/2;a<n;a+=Cn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(Cn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],h=s.path[a+1],l=h.x-c.x,u=h.z-c.z,d=Math.hypot(l,u);if(d<1e-6||Math.abs((l*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*l+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+l*f),e.z-(c.z+u*f));p<=Cn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class ph{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 ws(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${ph.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Cn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=Cn.voltageOf(r),h=ph.kindOf(r),l=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=ph.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:h,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(l)&&l>300?l:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:ph.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class f3{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(!co.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class an{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=an.key(t);let i=an.asked.get(e)??an.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},an.asked.set(e,i),n.catch(()=>an.asked.delete(e))}return structuredClone(await i.answer)}static forget(){an.asked.clear(),an.failedAt=-1/0}static key(t){return`v${an.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of an.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await an.openCache(),n=an.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:h}=await a.json();if(Array.isArray(h)){if(this.now()-c<an.MAX_AGE_MS)return h;s=h}}}catch{}if(this.now()-an.failedAt<an.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(an.failedAt=this.now(),s)return s;throw a}return i&&an.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-an.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(an.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const mp="https://ufoathome.org/railways/index.json";class mh{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??mh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
2406
+ `);let e=mh.shared.get(t);return e||(e=this.fetchFirstAvailable(),mh.shared.set(t,e),e.then(i=>{i.length===0&&mh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.162.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==mp?[e,mp]:[mp]).map(i=>i+t)}}function Pb(){return{elevation:p3(),imagery:Nb(),roads:m3(),water:g3(),railways:v3()}}function p3(){return new c3(new Ce,new a3)}function Nb(){return new Ob}function m3(){return new dh({fallback:new u3(new oo,new no)})}function g3(){return new fh({fallback:new fs(new d3(new Bu,new Yo))})}function v3(){return new mh({fallback:new an(new f3(new co,new ph))})}const M3=new Set,Jr="show-observer-map",jr="hide-milestones",ec="minified";class Ge extends HTMLElement{static get observedAttributes(){return["src",Jr,jr,ec]}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 di;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=C0.create();issues=[];issueCheck=0;sightingAudio=new FA;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>Ge.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=xb;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Ge.setIcon(this.moreButton,t?Jt.UNFOLDED:Jt.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()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ge.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=di.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=di.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ge.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=di.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${DA}</style>${IA}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new tl(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new $o(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),h=this.player.seekableDuration;if(c.width<=0||h<=0)return;const l=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*h;this.player.seek(l),this.miniScrubTime.textContent=this.formatElapsedAt(l),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Jr&&this.applyObserverMapDefault(),t===jr&&this.setMilestonesShown(!this.hasAttribute(jr)),t===ec){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(ec)}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(kb)))};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 Eo.recording(t)}get sightingData(){return zA(this.currentSighting)}set sightingData(t){const e=Wi.toCurrent(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=HA(e),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await Ie(async()=>{const{default:r}=await import("./sightingSchema-CnDwuCov.js");return{default:r}},[],import.meta.url);n=new ar(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],el.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(y3,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=this.messages.recordingIssues.replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=el.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}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 selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!this.referenceOpacityTouched&&t.length>0&&(this.referenceOpacityInput.value=String(t[0].opacity));for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const h=document.createElement("input");return h.type="range",h.min="0",h.max="1",h.step="0.05",h.value=String(i.opacity),h.title=this.messages.referenceOpacity,h.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),h.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,h.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),h.addEventListener("input",()=>{i.opacity=Number(h.value),this.dispatchReferenceView()}),s.append(r,h),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ge.setIcon(this.referencesButton,i?Jt.PICTURES_ON:Jt.PICTURES_OFF);const n=e?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Ge.setIcon(this.tracesButton,this.tracesShownState?Jt.TRACES_ON:Jt.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?ql(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const h=document.createElement("i");h.className="seek-played",a.append(c,h),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:h,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ge.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ge.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?lp(a,s):void 0,h=c?this.said.read(c.label)??"":"",l=c?this.said.read(c.note):void 0,u=l?`${h} — ${l}`:h;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new tl(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=Ge.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?lp(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=ur.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ge.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ge.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ge.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ge.EXPOSURE_STEP_PX),s=Math.min(Ge.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const h=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),l=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(h,l))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=ki.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}onFrame(t,e){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:M3;this.canvasRenderer.setStarPoints(ki.starPointsOf(this.sighting.instrument,Le(this.sighting,t)?.fNumber));const n=(Le(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,h]of c.shapes){const l=c.share,u=l===1?h:{...h,transparency:1-(1-h.transparency)*l};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,h]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...h,selected:!0}):this.canvasRenderer.paintMemberOutline(h):this.canvasRenderer.paintSelectionOnly(this.shifted(h,r)));const a=this.selectionShown&&i.size>1?Us.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(h=>h.transparency<1).map(h=>this.shifted(h,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(db(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 CA(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Ge.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"?Jt.PLAY:Jt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ge.icons.get(t)!==e&&(Ge.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Ge.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(),Ge.setIcon(this.playPauseButton,t?Jt.PAUSE:Jt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Jr),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;Ge.setIcon(this.observerMapButton,t?Jt.MAP_ON:Jt.MAP_OFF);const e=t?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages.zoomMapIn],[this.mapZoomOutButton,this.messages.zoomMapOut],[this.mapFitButton,this.messages.fitMap]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Ph.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=di.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?di.expand(t,Ge.OBSERVER_MAP_IMAGERY_AHEAD):t,n=di.IMAGERY_PX*(e?1+2*Ge.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapFrozenImagery,r=s?void 0:Nb();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?di.expand(t,Ge.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(t){t!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=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 observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(h,l,u)=>{for(const d of e)if(!(d.x+d.width<h-u||d.x>l+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Ge.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Le(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},Ge.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?lp(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?ql(this.currentSighting.milestones):[]){const a=Le(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?$r.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(ki.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,ql(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,Ge.setIcon(this.milestonesButton,this.milestonesShown?Jt.MILESTONES_ON:Jt.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=Le(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=vr(i,t),{lat:s,lng:r}=As(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=Le(this.currentSighting,this.currentTime),s=$r.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ni.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=Ge.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 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)),Ge.setIcon(this.miniMuteButton,this.mutedState?Jt.MUTED:Jt.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){Ge.setIcon(this.muteButton,Jt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Ge.setIcon(this.muteButton,this.mutedState?Jt.MUTED:Jt.VOLUME);const i=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ge.setIcon(this.fullscreenButton,t?Jt.EXIT_FULLSCREEN:Jt.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 Es(Ao.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=C1(Ao.preferencesFor(this),P1);if(t===this.messagesLanguage||t==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=t;const e=await WA(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.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=ub(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Wm(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return Ga(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?iy(ey(this.realStartMs+i)):Ga(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Ga(t):Ga(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Ga(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return Ga(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Ga(this.currentSighting.timeline.duration):this.canShowClockTime?iy(ey(this.realStartMs+this.realDurationMs)):Ga(this.realDurationMs)}}function ey(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function iy(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function Ga(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Km="rr0-ufo";function Lb(){customElements.get(Km)||customElements.define(Km,Ge)}const y3="recordingissues",kb="minifiedreset";/**
2407
2407
  * @license
2408
2408
  * Copyright 2010-2026 Three.js Authors
2409
2409
  * SPDX-License-Identifier: MIT
@@ -6518,7 +6518,7 @@ void main() {
6518
6518
 
6519
6519
  }
6520
6520
 
6521
- }`;class tC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new cx(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new Te({vertexShader:jD,fragmentShader:QD,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Mt(new Jn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class eC extends Po{constructor(t,e){super();const i=this;let n=null,s=1,r=null,a="local-floor",c=1,h=null,l=null,u=null,d=null,f=null,p=null;const m=typeof XRWebGLBinding<"u",g=new tC,v={},M=e.getContextAttributes();let w=null,y=null;const b=[],S=[],_=new it;let x=null;const A=new Nn;A.viewport=new _e;const I=new Nn;I.viewport=new _e;const D=[A,I],C=new ZT;let N=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(q){let ct=b[q];return ct===void 0&&(ct=new Ap,b[q]=ct),ct.getTargetRaySpace()},this.getControllerGrip=function(q){let ct=b[q];return ct===void 0&&(ct=new Ap,b[q]=ct),ct.getGripSpace()},this.getHand=function(q){let ct=b[q];return ct===void 0&&(ct=new Ap,b[q]=ct),ct.getHandSpace()};function P(q){const ct=S.indexOf(q.inputSource);if(ct===-1)return;const at=b[ct];at!==void 0&&(at.update(q.inputSource,q.frame,h||r),at.dispatchEvent({type:q.type,data:q.inputSource}))}function z(){n.removeEventListener("select",P),n.removeEventListener("selectstart",P),n.removeEventListener("selectend",P),n.removeEventListener("squeeze",P),n.removeEventListener("squeezestart",P),n.removeEventListener("squeezeend",P),n.removeEventListener("end",z),n.removeEventListener("inputsourceschange",H);for(let q=0;q<b.length;q++){const ct=S[q];ct!==null&&(S[q]=null,b[q].disconnect(ct))}N=null,L=null,g.reset();for(const q in v)delete v[q];t.setRenderTarget(w),f=null,d=null,u=null,n=null,y=null,Yt.stop(),i.isPresenting=!1,t.setPixelRatio(x),t.setSize(_.width,_.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(q){s=q,i.isPresenting===!0&&Ut("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(q){a=q,i.isPresenting===!0&&Ut("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return h||r},this.setReferenceSpace=function(q){h=q},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(n,e)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(q){if(n=q,n!==null){if(w=t.getRenderTarget(),n.addEventListener("select",P),n.addEventListener("selectstart",P),n.addEventListener("selectend",P),n.addEventListener("squeeze",P),n.addEventListener("squeezestart",P),n.addEventListener("squeezeend",P),n.addEventListener("end",z),n.addEventListener("inputsourceschange",H),M.xrCompatible!==!0&&await e.makeXRCompatible(),x=t.getPixelRatio(),t.getSize(_),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let at=null,V=null,Ft=null;M.depth&&(Ft=M.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,at=M.stencil?ic:Pa,V=M.stencil?Vu:tr);const Kt={colorFormat:e.RGBA8,depthFormat:Ft,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Kt),n.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new Ke(d.textureWidth,d.textureHeight,{format:$i,type:Kn,depthTexture:new Co(d.textureWidth,d.textureHeight,V,void 0,void 0,void 0,void 0,void 0,void 0,at),stencilBuffer:M.stencil,colorSpace:t.outputColorSpace,samples:M.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const at={antialias:M.antialias,alpha:!0,depth:M.depth,stencil:M.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(n,e,at),n.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ke(f.framebufferWidth,f.framebufferHeight,{format:$i,type:Kn,colorSpace:t.outputColorSpace,stencilBuffer:M.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),h=null,r=await n.requestReferenceSpace(a),Yt.setContext(n),Yt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function H(q){for(let ct=0;ct<q.removed.length;ct++){const at=q.removed[ct],V=S.indexOf(at);V>=0&&(S[V]=null,b[V].disconnect(at))}for(let ct=0;ct<q.added.length;ct++){const at=q.added[ct];let V=S.indexOf(at);if(V===-1){for(let Kt=0;Kt<b.length;Kt++)if(Kt>=S.length){S.push(at),V=Kt;break}else if(S[Kt]===null){S[Kt]=at,V=Kt;break}if(V===-1)break}const Ft=b[V];Ft&&Ft.connect(at)}}const $=new T,Q=new T;function Z(q,ct,at){$.setFromMatrixPosition(ct.matrixWorld),Q.setFromMatrixPosition(at.matrixWorld);const V=$.distanceTo(Q),Ft=ct.projectionMatrix.elements,Kt=at.projectionMatrix.elements,Ht=Ft[14]/(Ft[10]-1),Rt=Ft[14]/(Ft[10]+1),jt=(Ft[9]+1)/Ft[5],ee=(Ft[9]-1)/Ft[5],ie=(Ft[8]-1)/Ft[0],Qe=(Kt[8]+1)/Kt[0],ti=Ht*ie,Fi=Ht*Qe,Ci=V/(-ie+Qe),zi=Ci*-ie;if(ct.matrixWorld.decompose(q.position,q.quaternion,q.scale),q.translateX(zi),q.translateZ(Ci),q.matrixWorld.compose(q.position,q.quaternion,q.scale),q.matrixWorldInverse.copy(q.matrixWorld).invert(),Ft[10]===-1)q.projectionMatrix.copy(ct.projectionMatrix),q.projectionMatrixInverse.copy(ct.projectionMatrixInverse);else{const sn=Ht+Ci,F=Rt+Ci,ds=ti-zi,ei=Fi+(V-zi),O=jt*Rt/F*sn,E=ee*Rt/F*sn;q.projectionMatrix.makePerspective(ds,ei,O,E,sn,F),q.projectionMatrixInverse.copy(q.projectionMatrix).invert()}}function nt(q,ct){ct===null?q.matrixWorld.copy(q.matrix):q.matrixWorld.multiplyMatrices(ct.matrixWorld,q.matrix),q.matrixWorldInverse.copy(q.matrixWorld).invert()}this.updateCamera=function(q){if(n===null)return;let ct=q.near,at=q.far;g.texture!==null&&(g.depthNear>0&&(ct=g.depthNear),g.depthFar>0&&(at=g.depthFar)),C.near=I.near=A.near=ct,C.far=I.far=A.far=at,(N!==C.near||L!==C.far)&&(n.updateRenderState({depthNear:C.near,depthFar:C.far}),N=C.near,L=C.far),C.layers.mask=q.layers.mask|6,A.layers.mask=C.layers.mask&-5,I.layers.mask=C.layers.mask&-3;const V=q.parent,Ft=C.cameras;nt(C,V);for(let Kt=0;Kt<Ft.length;Kt++)nt(Ft[Kt],V);Ft.length===2?Z(C,A,I):C.projectionMatrix.copy(A.projectionMatrix),ot(q,C,V)};function ot(q,ct,at){at===null?q.matrix.copy(ct.matrixWorld):(q.matrix.copy(at.matrixWorld),q.matrix.invert(),q.matrix.multiply(ct.matrixWorld)),q.matrix.decompose(q.position,q.quaternion,q.scale),q.updateMatrixWorld(!0),q.projectionMatrix.copy(ct.projectionMatrix),q.projectionMatrixInverse.copy(ct.projectionMatrixInverse),q.isPerspectiveCamera&&(q.fov=rl*2*Math.atan(1/q.projectionMatrix.elements[5]),q.zoom=1)}this.getCamera=function(){return C},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(q){c=q,d!==null&&(d.fixedFoveation=q),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=q)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(C)},this.getCameraTexture=function(q){return v[q]};let Wt=null;function qt(q,ct){if(l=ct.getViewerPose(h||r),p=ct,l!==null){const at=l.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let V=!1;at.length!==C.cameras.length&&(C.cameras.length=0,V=!0);for(let Rt=0;Rt<at.length;Rt++){const jt=at[Rt];let ee=null;if(f!==null)ee=f.getViewport(jt);else{const Qe=u.getViewSubImage(d,jt);ee=Qe.viewport,Rt===0&&(t.setRenderTargetTextures(y,Qe.colorTexture,Qe.depthStencilTexture),t.setRenderTarget(y))}let ie=D[Rt];ie===void 0&&(ie=new Nn,ie.layers.enable(Rt),ie.viewport=new _e,D[Rt]=ie),ie.matrix.fromArray(jt.transform.matrix),ie.matrix.decompose(ie.position,ie.quaternion,ie.scale),ie.projectionMatrix.fromArray(jt.projectionMatrix),ie.projectionMatrixInverse.copy(ie.projectionMatrix).invert(),ie.viewport.set(ee.x,ee.y,ee.width,ee.height),Rt===0&&(C.matrix.copy(ie.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale)),V===!0&&C.cameras.push(ie)}const Ft=n.enabledFeatures;if(Ft&&Ft.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&m){u=i.getBinding();const Rt=u.getDepthInformation(at[0]);Rt&&Rt.isValid&&Rt.texture&&g.init(Rt,n.renderState)}if(Ft&&Ft.includes("camera-access")&&m){t.state.unbindTexture(),u=i.getBinding();for(let Rt=0;Rt<at.length;Rt++){const jt=at[Rt].camera;if(jt){let ee=v[jt];ee||(ee=new cx,v[jt]=ee);const ie=u.getCameraImage(jt);ee.sourceTexture=ie}}}}for(let at=0;at<b.length;at++){const V=S[at],Ft=b[at];V!==null&&Ft!==void 0&&Ft.update(V,ct,h||r)}Wt&&Wt(q,ct),ct.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ct}),p=null}const Yt=new Ax;Yt.setAnimationLoop(qt),this.setAnimationLoop=function(q){Wt=q},this.dispose=function(){}}}const iC=new oe,Cx=new le;Cx.set(-1,0,0,0,1,0,0,0,1);function nC(o,t){function e(g,v){g.matrixAutoUpdate===!0&&g.updateMatrix(),v.value.copy(g.matrix)}function i(g,v){v.color.getRGB(g.fogColor.value,vx(o)),v.isFog?(g.fogNear.value=v.near,g.fogFar.value=v.far):v.isFogExp2&&(g.fogDensity.value=v.density)}function n(g,v,M,w,y){v.isNodeMaterial?v.uniformsNeedUpdate=!1:v.isMeshBasicMaterial?s(g,v):v.isMeshLambertMaterial?(s(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshToonMaterial?(s(g,v),u(g,v)):v.isMeshPhongMaterial?(s(g,v),l(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshStandardMaterial?(s(g,v),d(g,v),v.isMeshPhysicalMaterial&&f(g,v,y)):v.isMeshMatcapMaterial?(s(g,v),p(g,v)):v.isMeshDepthMaterial?s(g,v):v.isMeshDistanceMaterial?(s(g,v),m(g,v)):v.isMeshNormalMaterial?s(g,v):v.isLineBasicMaterial?(r(g,v),v.isLineDashedMaterial&&a(g,v)):v.isPointsMaterial?c(g,v,M,w):v.isSpriteMaterial?h(g,v):v.isShadowMaterial?(g.color.value.copy(v.color),g.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function s(g,v){g.opacity.value=v.opacity,v.color&&g.diffuse.value.copy(v.color),v.emissive&&g.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.bumpMap&&(g.bumpMap.value=v.bumpMap,e(v.bumpMap,g.bumpMapTransform),g.bumpScale.value=v.bumpScale,v.side===Pi&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,e(v.normalMap,g.normalMapTransform),g.normalScale.value.copy(v.normalScale),v.side===Pi&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,e(v.displacementMap,g.displacementMapTransform),g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap,e(v.emissiveMap,g.emissiveMapTransform)),v.specularMap&&(g.specularMap.value=v.specularMap,e(v.specularMap,g.specularMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);const M=t.get(v),w=M.envMap,y=M.envMapRotation;w&&(g.envMap.value=w,g.envMapRotation.value.setFromMatrix4(iC.makeRotationFromEuler(y)).transpose(),w.isCubeTexture&&w.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(Cx),g.reflectivity.value=v.reflectivity,g.ior.value=v.ior,g.refractionRatio.value=v.refractionRatio),v.lightMap&&(g.lightMap.value=v.lightMap,g.lightMapIntensity.value=v.lightMapIntensity,e(v.lightMap,g.lightMapTransform)),v.aoMap&&(g.aoMap.value=v.aoMap,g.aoMapIntensity.value=v.aoMapIntensity,e(v.aoMap,g.aoMapTransform))}function r(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform))}function a(g,v){g.dashSize.value=v.dashSize,g.totalSize.value=v.dashSize+v.gapSize,g.scale.value=v.scale}function c(g,v,M,w){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.size.value=v.size*M,g.scale.value=w*.5,v.map&&(g.map.value=v.map,e(v.map,g.uvTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function h(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.rotation.value=v.rotation,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function l(g,v){g.specular.value.copy(v.specular),g.shininess.value=Math.max(v.shininess,1e-4)}function u(g,v){v.gradientMap&&(g.gradientMap.value=v.gradientMap)}function d(g,v){g.metalness.value=v.metalness,v.metalnessMap&&(g.metalnessMap.value=v.metalnessMap,e(v.metalnessMap,g.metalnessMapTransform)),g.roughness.value=v.roughness,v.roughnessMap&&(g.roughnessMap.value=v.roughnessMap,e(v.roughnessMap,g.roughnessMapTransform)),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)}function f(g,v,M){g.ior.value=v.ior,v.sheen>0&&(g.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),g.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(g.sheenColorMap.value=v.sheenColorMap,e(v.sheenColorMap,g.sheenColorMapTransform)),v.sheenRoughnessMap&&(g.sheenRoughnessMap.value=v.sheenRoughnessMap,e(v.sheenRoughnessMap,g.sheenRoughnessMapTransform))),v.clearcoat>0&&(g.clearcoat.value=v.clearcoat,g.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(g.clearcoatMap.value=v.clearcoatMap,e(v.clearcoatMap,g.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,e(v.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(g.clearcoatNormalMap.value=v.clearcoatNormalMap,e(v.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Pi&&g.clearcoatNormalScale.value.negate())),v.dispersion>0&&(g.dispersion.value=v.dispersion),v.iridescence>0&&(g.iridescence.value=v.iridescence,g.iridescenceIOR.value=v.iridescenceIOR,g.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(g.iridescenceMap.value=v.iridescenceMap,e(v.iridescenceMap,g.iridescenceMapTransform)),v.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=v.iridescenceThicknessMap,e(v.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),v.transmission>0&&(g.transmission.value=v.transmission,g.transmissionSamplerMap.value=M.texture,g.transmissionSamplerSize.value.set(M.width,M.height),v.transmissionMap&&(g.transmissionMap.value=v.transmissionMap,e(v.transmissionMap,g.transmissionMapTransform)),g.thickness.value=v.thickness,v.thicknessMap&&(g.thicknessMap.value=v.thicknessMap,e(v.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=v.attenuationDistance,g.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(g.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(g.anisotropyMap.value=v.anisotropyMap,e(v.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=v.specularIntensity,g.specularColor.value.copy(v.specularColor),v.specularColorMap&&(g.specularColorMap.value=v.specularColorMap,e(v.specularColorMap,g.specularColorMapTransform)),v.specularIntensityMap&&(g.specularIntensityMap.value=v.specularIntensityMap,e(v.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,v){v.matcap&&(g.matcap.value=v.matcap)}function m(g,v){const M=t.get(v).light;g.referencePosition.value.setFromMatrixPosition(M.matrixWorld),g.nearDistance.value=M.shadow.camera.near,g.farDistance.value=M.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function sC(o,t,e,i){let n={},s={},r=[];const a=o.getParameter(o.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,b){const S=b.program;i.uniformBlockBinding(y,S)}function h(y,b){let S=n[y.id];S===void 0&&(g(y),S=l(y),n[y.id]=S,y.addEventListener("dispose",M));const _=b.program;i.updateUBOMapping(y,_);const x=t.render.frame;s[y.id]!==x&&(d(y),s[y.id]=x)}function l(y){const b=u();y.__bindingPointIndex=b;const S=o.createBuffer(),_=y.__size,x=y.usage;return o.bindBuffer(o.UNIFORM_BUFFER,S),o.bufferData(o.UNIFORM_BUFFER,_,x),o.bindBuffer(o.UNIFORM_BUFFER,null),o.bindBufferBase(o.UNIFORM_BUFFER,b,S),S}function u(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ae("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const b=n[y.id],S=y.uniforms,_=y.__cache;o.bindBuffer(o.UNIFORM_BUFFER,b);for(let x=0,A=S.length;x<A;x++){const I=S[x];if(Array.isArray(I))for(let D=0,C=I.length;D<C;D++)f(I[D],x,D,_);else f(I,x,0,_)}o.bindBuffer(o.UNIFORM_BUFFER,null)}function f(y,b,S,_){if(m(y,b,S,_)===!0){const x=y.__offset,A=y.value;if(Array.isArray(A)){let I=0;for(let D=0;D<A.length;D++){const C=A[D],N=v(C);p(C,y.__data,I),typeof C!="number"&&typeof C!="boolean"&&!C.isMatrix3&&!ArrayBuffer.isView(C)&&(I+=N.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);o.bufferSubData(o.UNIFORM_BUFFER,x,y.__data)}}function p(y,b,S){typeof y=="number"||typeof y=="boolean"?b[0]=y:y.isMatrix3?(b[0]=y.elements[0],b[1]=y.elements[1],b[2]=y.elements[2],b[3]=0,b[4]=y.elements[3],b[5]=y.elements[4],b[6]=y.elements[5],b[7]=0,b[8]=y.elements[6],b[9]=y.elements[7],b[10]=y.elements[8],b[11]=0):ArrayBuffer.isView(y)?b.set(new y.constructor(y.buffer,y.byteOffset,b.length)):y.toArray(b,S)}function m(y,b,S,_){const x=y.value,A=b+"_"+S;if(_[A]===void 0)return typeof x=="number"||typeof x=="boolean"?_[A]=x:ArrayBuffer.isView(x)?_[A]=x.slice():_[A]=x.clone(),!0;{const I=_[A];if(typeof x=="number"||typeof x=="boolean"){if(I!==x)return _[A]=x,!0}else{if(ArrayBuffer.isView(x))return!0;if(I.equals(x)===!1)return I.copy(x),!0}}return!1}function g(y){const b=y.uniforms;let S=0;const _=16;for(let A=0,I=b.length;A<I;A++){const D=Array.isArray(b[A])?b[A]:[b[A]];for(let C=0,N=D.length;C<N;C++){const L=D[C],P=Array.isArray(L.value)?L.value:[L.value];for(let z=0,H=P.length;z<H;z++){const $=P[z],Q=v($),Z=S%_,nt=Z%Q.boundary,ot=Z+nt;S+=nt,ot!==0&&_-ot<Q.storage&&(S+=_-ot),L.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=S,S+=Q.storage}}}const x=S%_;return x>0&&(S+=_-x),y.__size=S,y.__cache={},this}function v(y){const b={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(b.boundary=4,b.storage=4):y.isVector2?(b.boundary=8,b.storage=8):y.isVector3||y.isColor?(b.boundary=16,b.storage=12):y.isVector4?(b.boundary=16,b.storage=16):y.isMatrix3?(b.boundary=48,b.storage=48):y.isMatrix4?(b.boundary=64,b.storage=64):y.isTexture?Ut("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(b.boundary=16,b.storage=y.byteLength):Ut("WebGLRenderer: Unsupported uniform value type.",y),b}function M(y){const b=y.target;b.removeEventListener("dispose",M);const S=r.indexOf(b.__bindingPointIndex);r.splice(S,1),o.deleteBuffer(n[b.id]),delete n[b.id],delete s[b.id]}function w(){for(const y in n)o.deleteBuffer(n[y]);r=[],n={},s={}}return{bind:c,update:h,dispose:w}}const rC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let _r=null;function aC(){return _r===null&&(_r=new us(rC,16,16,bc,Xe),_r.name="DFG_LUT",_r.minFilter=ye,_r.magFilter=ye,_r.wrapS=Xi,_r.wrapT=Xi,_r.generateMipmaps=!1,_r.needsUpdate=!0),_r}class oC{constructor(t={}){const{canvas:e=e_(),context:i=null,depth:n=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:h=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Kn}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=r;const m=f,g=new Set([H1,B1,z1]),v=new Set([Kn,tr,Gu,Vu,U1,F1]),M=new Uint32Array(4),w=new Int32Array(4),y=new T;let b=null,S=null;const _=[],x=[];let A=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ea,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const I=this;let D=!1,C=null,N=null,L=null,P=null;this._outputColorSpace=An;let z=0,H=0,$=null,Q=-1,Z=null;const nt=new _e,ot=new _e;let Wt=null;const qt=new rt(0);let Yt=0,q=e.width,ct=e.height,at=1,V=null,Ft=null;const Kt=new _e(0,0,q,ct),Ht=new _e(0,0,q,ct);let Rt=!1;const jt=new L0;let ee=!1,ie=!1;const Qe=new oe,ti=new T,Fi=new _e,Ci={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let zi=!1;function sn(){return $===null?at:1}let F=i;function ds(R,B){return e.getContext(R,B)}try{const R={alpha:!0,depth:n,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:h,powerPreference:l,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${N1}`),e.addEventListener("webglcontextlost",Bi,!1),e.addEventListener("webglcontextrestored",yi,!1),e.addEventListener("webglcontextcreationerror",br,!1),F===null){const B="webgl2";if(F=ds(B,R),F===null)throw ds(B)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(R){throw ae("WebGLRenderer: "+R.message),R}let ei,O,E,G,Y,J,ht,pt,j,et,mt,Gt,wt,gt,Zt,ne,xe,U,dt,tt,vt,Et,st;function Bt(){ei=new aI(F),ei.init(),vt=new JD(F,ei),O=new j4(F,ei,t,vt),E=new qD(F,ei),O.reversedDepthBuffer&&d&&E.buffers.depth.setReversed(!0),N=F.createFramebuffer(),L=F.createFramebuffer(),P=F.createFramebuffer(),G=new hI(F),Y=new LD,J=new ZD(F,ei,E,Y,O,vt,G),ht=new rI(I),pt=new f5(F),Et=new Z4(F,pt),j=new oI(F,pt,G,Et),et=new uI(F,j,pt,Et,G),U=new lI(F,O,J),Zt=new Q4(Y),mt=new ND(I,ht,ei,O,Et,Zt),Gt=new nC(I,Y),wt=new UD,gt=new VD(ei),xe=new q4(I,ht,E,et,p,c),ne=new KD(I,et,O),st=new sC(F,G,O,E),dt=new J4(F,ei,G),tt=new cI(F,ei,G),G.programs=mt.programs,I.capabilities=O,I.extensions=ei,I.properties=Y,I.renderLists=wt,I.shadowMap=ne,I.state=E,I.info=G}Bt(),m!==Kn&&(A=new fI(m,e.width,e.height,a,n,s));const Pt=new eC(I,F);this.xr=Pt,this.getContext=function(){return F},this.getContextAttributes=function(){return F.getContextAttributes()},this.forceContextLoss=function(){const R=ei.get("WEBGL_lose_context");R&&R.loseContext()},this.forceContextRestore=function(){const R=ei.get("WEBGL_lose_context");R&&R.restoreContext()},this.getPixelRatio=function(){return at},this.setPixelRatio=function(R){R!==void 0&&(at=R,this.setSize(q,ct,!1))},this.getSize=function(R){return R.set(q,ct)},this.setSize=function(R,B,K=!0){if(Pt.isPresenting){Ut("WebGLRenderer: Can't change size while VR device is presenting.");return}q=R,ct=B,e.width=Math.floor(R*at),e.height=Math.floor(B*at),K===!0&&(e.style.width=R+"px",e.style.height=B+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,R,B)},this.getDrawingBufferSize=function(R){return R.set(q*at,ct*at).floor()},this.setDrawingBufferSize=function(R,B,K){q=R,ct=B,at=K,e.width=Math.floor(R*K),e.height=Math.floor(B*K),this.setViewport(0,0,R,B)},this.setEffects=function(R){if(m===Kn){ae("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(R){for(let B=0;B<R.length;B++)if(R[B].isOutputPass===!0){Ut("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(R||[])},this.getCurrentViewport=function(R){return R.copy(nt)},this.getViewport=function(R){return R.copy(Kt)},this.setViewport=function(R,B,K,W){R.isVector4?Kt.set(R.x,R.y,R.z,R.w):Kt.set(R,B,K,W),E.viewport(nt.copy(Kt).multiplyScalar(at).round())},this.getScissor=function(R){return R.copy(Ht)},this.setScissor=function(R,B,K,W){R.isVector4?Ht.set(R.x,R.y,R.z,R.w):Ht.set(R,B,K,W),E.scissor(ot.copy(Ht).multiplyScalar(at).round())},this.getScissorTest=function(){return Rt},this.setScissorTest=function(R){E.setScissorTest(Rt=R)},this.setOpaqueSort=function(R){V=R},this.setTransparentSort=function(R){Ft=R},this.getClearColor=function(R){return R.copy(xe.getClearColor())},this.setClearColor=function(){xe.setClearColor(...arguments)},this.getClearAlpha=function(){return xe.getClearAlpha()},this.setClearAlpha=function(){xe.setClearAlpha(...arguments)},this.clear=function(R=!0,B=!0,K=!0){let W=0;if(R){let X=!1;if($!==null){const St=$.texture.format;X=g.has(St)}if(X){const St=$.texture.type,It=v.has(St),xt=xe.getClearColor(),kt=xe.getClearAlpha(),Vt=xt.r,Se=xt.g,Ie=xt.b;It?(M[0]=Vt,M[1]=Se,M[2]=Ie,M[3]=kt,F.clearBufferuiv(F.COLOR,0,M)):(w[0]=Vt,w[1]=Se,w[2]=Ie,w[3]=kt,F.clearBufferiv(F.COLOR,0,w))}else W|=F.COLOR_BUFFER_BIT}B&&(W|=F.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),K&&(W|=F.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),W!==0&&F.clear(W)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(R){R.setRenderer(this),C=R},this.dispose=function(){e.removeEventListener("webglcontextlost",Bi,!1),e.removeEventListener("webglcontextrestored",yi,!1),e.removeEventListener("webglcontextcreationerror",br,!1),xe.dispose(),wt.dispose(),gt.dispose(),Y.dispose(),ht.dispose(),et.dispose(),Et.dispose(),st.dispose(),mt.dispose(),Pt.dispose(),Pt.removeEventListener("sessionstart",Av),Pt.removeEventListener("sessionend",_v),Lo.stop()};function Bi(R){R.preventDefault(),t0("WebGLRenderer: Context Lost."),D=!0}function yi(){t0("WebGLRenderer: Context Restored."),D=!1;const R=G.autoReset,B=ne.enabled,K=ne.autoUpdate,W=ne.needsUpdate,X=ne.type;Bt(),G.autoReset=R,ne.enabled=B,ne.autoUpdate=K,ne.needsUpdate=W,ne.type=X}function br(R){ae("WebGLRenderer: A WebGL context could not be created. Reason: ",R.statusMessage)}function xr(R){const B=R.target;B.removeEventListener("dispose",xr),DS(B)}function DS(R){CS(R),Y.remove(R)}function CS(R){const B=Y.get(R).programs;B!==void 0&&(B.forEach(function(K){mt.releaseProgram(K)}),R.isShaderMaterial&&mt.releaseShaderCache(R))}this.renderBufferDirect=function(R,B,K,W,X,St){B===null&&(B=Ci);const It=X.isMesh&&X.matrixWorld.determinantAffine()<0,xt=NS(R,B,K,W,X);E.setMaterial(W,It);let kt=K.index,Vt=1;if(W.wireframe===!0){if(kt=j.getWireframeAttribute(K),kt===void 0)return;Vt=2}const Se=K.drawRange,Ie=K.attributes.position;let Xt=Se.start*Vt,li=(Se.start+Se.count)*Vt;St!==null&&(Xt=Math.max(Xt,St.start*Vt),li=Math.min(li,(St.start+St.count)*Vt)),kt!==null?(Xt=Math.max(Xt,0),li=Math.min(li,kt.count)):Ie!=null&&(Xt=Math.max(Xt,0),li=Math.min(li,Ie.count));const Ki=li-Xt;if(Ki<0||Ki===1/0)return;Et.setup(X,W,xt,K,kt);let Hi,mi=dt;if(kt!==null&&(Hi=pt.get(kt),mi=tt,mi.setIndex(Hi)),X.isMesh)W.wireframe===!0?(E.setLineWidth(W.wireframeLinewidth*sn()),mi.setMode(F.LINES)):mi.setMode(F.TRIANGLES);else if(X.isLine){let Un=W.linewidth;Un===void 0&&(Un=1),E.setLineWidth(Un*sn()),X.isLineSegments?mi.setMode(F.LINES):X.isLineLoop?mi.setMode(F.LINE_LOOP):mi.setMode(F.LINE_STRIP)}else X.isPoints?mi.setMode(F.POINTS):X.isSprite&&mi.setMode(F.TRIANGLES);if(X.isBatchedMesh)if(ei.get("WEBGL_multi_draw"))mi.renderMultiDraw(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount);else{const Un=X._multiDrawStarts,Tt=X._multiDrawCounts,Ds=X._multiDrawCount,He=kt?pt.get(kt).bytesPerElement:1,Vs=Y.get(W).currentProgram.getUniforms();for(let Sr=0;Sr<Ds;Sr++)Vs.setValue(F,"_gl_DrawID",Sr),mi.render(Un[Sr]/He,Tt[Sr])}else if(X.isInstancedMesh)mi.renderInstances(Xt,Ki,X.count);else if(K.isInstancedBufferGeometry){const Un=K._maxInstanceCount!==void 0?K._maxInstanceCount:1/0,Tt=Math.min(K.instanceCount,Un);mi.renderInstances(Xt,Ki,Tt)}else mi.render(Xt,Ki)};function Ev(R,B,K){R.transparent===!0&&R.side===_n&&R.forceSinglePass===!1?(R.side=Pi,R.needsUpdate=!0,od(R,B,K),R.side=Io,R.needsUpdate=!0,od(R,B,K),R.side=_n):od(R,B,K)}this.compile=function(R,B,K=null){K===null&&(K=R),S=gt.get(K),S.init(B),x.push(S),K.traverseVisible(function(X){X.isLight&&X.layers.test(B.layers)&&(S.pushLight(X),X.castShadow&&S.pushShadow(X))}),R!==K&&R.traverseVisible(function(X){X.isLight&&X.layers.test(B.layers)&&(S.pushLight(X),X.castShadow&&S.pushShadow(X))}),S.setupLights();const W=new Set;return R.traverse(function(X){if(!(X.isMesh||X.isPoints||X.isLine||X.isSprite))return;const St=X.material;if(St)if(Array.isArray(St))for(let It=0;It<St.length;It++){const xt=St[It];Ev(xt,K,X),W.add(xt)}else Ev(St,K,X),W.add(St)}),S=x.pop(),W},this.compileAsync=function(R,B,K=null){const W=this.compile(R,B,K);return new Promise(X=>{function St(){if(W.forEach(function(It){Y.get(It).currentProgram.isReady()&&W.delete(It)}),W.size===0){X(R);return}setTimeout(St,10)}ei.get("KHR_parallel_shader_compile")!==null?St():setTimeout(St,10)})};let Z0=null;function OS(R){Z0&&Z0(R)}function Av(){Lo.stop()}function _v(){Lo.start()}const Lo=new Ax;Lo.setAnimationLoop(OS),typeof self<"u"&&Lo.setContext(self),this.setAnimationLoop=function(R){Z0=R,Pt.setAnimationLoop(R),R===null?Lo.stop():Lo.start()},Pt.addEventListener("sessionstart",Av),Pt.addEventListener("sessionend",_v),this.render=function(R,B){if(B!==void 0&&B.isCamera!==!0){ae("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;C!==null&&C.renderStart(R,B);const K=Pt.enabled===!0&&Pt.isPresenting===!0,W=A!==null&&($===null||K)&&A.begin(I,$);if(R.matrixWorldAutoUpdate===!0&&R.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),Pt.enabled===!0&&Pt.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(Pt.cameraAutoUpdate===!0&&Pt.updateCamera(B),B=Pt.getCamera()),R.isScene===!0&&R.onBeforeRender(I,R,B,$),S=gt.get(R,x.length),S.init(B),S.state.textureUnits=J.getTextureUnits(),x.push(S),Qe.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),jt.setFromProjectionMatrix(Qe,Qr,B.reversedDepth),ie=this.localClippingEnabled,ee=Zt.init(this.clippingPlanes,ie),b=wt.get(R,_.length),b.init(),_.push(b),Pt.enabled===!0&&Pt.isPresenting===!0){const It=I.xr.getDepthSensingMesh();It!==null&&J0(It,B,-1/0,I.sortObjects)}J0(R,B,0,I.sortObjects),b.finish(),I.sortObjects===!0&&b.sort(V,Ft,B.reversedDepth),zi=Pt.enabled===!1||Pt.isPresenting===!1||Pt.hasDepthSensing()===!1,zi&&xe.addToRenderList(b,R),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ee===!0&&Zt.beginShadows();const X=S.state.shadowsArray;if(ne.render(X,R,B),ee===!0&&Zt.endShadows(),(W&&A.hasRenderPass())===!1){const It=b.opaque,xt=b.transmissive;if(S.setupLights(),B.isArrayCamera){const kt=B.cameras;if(xt.length>0)for(let Vt=0,Se=kt.length;Vt<Se;Vt++){const Ie=kt[Vt];Rv(It,xt,R,Ie)}zi&&xe.render(R);for(let Vt=0,Se=kt.length;Vt<Se;Vt++){const Ie=kt[Vt];Tv(b,R,Ie,Ie.viewport)}}else xt.length>0&&Rv(It,xt,R,B),zi&&xe.render(R),Tv(b,R,B)}$!==null&&H===0&&(J.updateMultisampleRenderTarget($),J.updateRenderTargetMipmap($)),W&&A.end(I),R.isScene===!0&&R.onAfterRender(I,R,B),Et.resetDefaultState(),Q=-1,Z=null,x.pop(),x.length>0?(S=x[x.length-1],J.setTextureUnits(S.state.textureUnits),ee===!0&&Zt.setGlobalState(I.clippingPlanes,S.state.camera)):S=null,_.pop(),_.length>0?b=_[_.length-1]:b=null,C!==null&&C.renderEnd()};function J0(R,B,K,W){if(R.visible===!1)return;if(R.layers.test(B.layers)){if(R.isGroup)K=R.renderOrder;else if(R.isLOD)R.autoUpdate===!0&&R.update(B);else if(R.isLightProbeGrid)S.pushLightProbeGrid(R);else if(R.isLight)S.pushLight(R),R.castShadow&&S.pushShadow(R);else if(R.isSprite){if(!R.frustumCulled||jt.intersectsSprite(R)){W&&Fi.setFromMatrixPosition(R.matrixWorld).applyMatrix4(Qe);const It=et.update(R),xt=R.material;xt.visible&&b.push(R,It,xt,K,Fi.z,null)}}else if((R.isMesh||R.isLine||R.isPoints)&&(!R.frustumCulled||jt.intersectsObject(R))){const It=et.update(R),xt=R.material;if(W&&(R.boundingSphere!==void 0?(R.boundingSphere===null&&R.computeBoundingSphere(),Fi.copy(R.boundingSphere.center)):(It.boundingSphere===null&&It.computeBoundingSphere(),Fi.copy(It.boundingSphere.center)),Fi.applyMatrix4(R.matrixWorld).applyMatrix4(Qe)),Array.isArray(xt)){const kt=It.groups;for(let Vt=0,Se=kt.length;Vt<Se;Vt++){const Ie=kt[Vt],Xt=xt[Ie.materialIndex];Xt&&Xt.visible&&b.push(R,It,Xt,K,Fi.z,Ie)}}else xt.visible&&b.push(R,It,xt,K,Fi.z,null)}}const St=R.children;for(let It=0,xt=St.length;It<xt;It++)J0(St[It],B,K,W)}function Tv(R,B,K,W){const{opaque:X,transmissive:St,transparent:It}=R;S.setupLightsView(K),ee===!0&&Zt.setGlobalState(I.clippingPlanes,K),W&&E.viewport(nt.copy(W)),X.length>0&&ad(X,B,K),St.length>0&&ad(St,B,K),It.length>0&&ad(It,B,K),E.buffers.depth.setTest(!0),E.buffers.depth.setMask(!0),E.buffers.color.setMask(!0),E.setPolygonOffset(!1)}function Rv(R,B,K,W){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[W.id]===void 0){const Xt=ei.has("EXT_color_buffer_half_float")||ei.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[W.id]=new Ke(1,1,{generateMipmaps:!0,type:Xt?Xe:Kn,minFilter:Bs,samples:Math.max(4,O.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Fe.workingColorSpace})}const St=S.state.transmissionRenderTarget[W.id],It=W.viewport||nt;St.setSize(It.z*I.transmissionResolutionScale,It.w*I.transmissionResolutionScale);const xt=I.getRenderTarget(),kt=I.getActiveCubeFace(),Vt=I.getActiveMipmapLevel();I.setRenderTarget(St),I.getClearColor(qt),Yt=I.getClearAlpha(),Yt<1&&I.setClearColor(16777215,.5),I.clear(),zi&&xe.render(K);const Se=I.toneMapping;I.toneMapping=ea;const Ie=W.viewport;if(W.viewport!==void 0&&(W.viewport=void 0),S.setupLightsView(W),ee===!0&&Zt.setGlobalState(I.clippingPlanes,W),ad(R,K,W),J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St),ei.has("WEBGL_multisampled_render_to_texture")===!1){let Xt=!1;for(let li=0,Ki=B.length;li<Ki;li++){const Hi=B[li],{object:mi,geometry:Un,material:Tt,group:Ds}=Hi;if(Tt.side===_n&&mi.layers.test(W.layers)){const He=Tt.side;Tt.side=Pi,Tt.needsUpdate=!0,Iv(mi,K,W,Un,Tt,Ds),Tt.side=He,Tt.needsUpdate=!0,Xt=!0}}Xt===!0&&(J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St))}I.setRenderTarget(xt,kt,Vt),I.setClearColor(qt,Yt),Ie!==void 0&&(W.viewport=Ie),I.toneMapping=Se}function ad(R,B,K){const W=B.isScene===!0?B.overrideMaterial:null;for(let X=0,St=R.length;X<St;X++){const It=R[X],{object:xt,geometry:kt,group:Vt}=It;let Se=It.material;Se.allowOverride===!0&&W!==null&&(Se=W),xt.layers.test(K.layers)&&Iv(xt,B,K,kt,Se,Vt)}}function Iv(R,B,K,W,X,St){R.onBeforeRender(I,B,K,W,X,St),R.modelViewMatrix.multiplyMatrices(K.matrixWorldInverse,R.matrixWorld),R.normalMatrix.getNormalMatrix(R.modelViewMatrix),X.onBeforeRender(I,B,K,W,R,St),X.transparent===!0&&X.side===_n&&X.forceSinglePass===!1?(X.side=Pi,X.needsUpdate=!0,I.renderBufferDirect(K,B,W,X,R,St),X.side=Io,X.needsUpdate=!0,I.renderBufferDirect(K,B,W,X,R,St),X.side=_n):I.renderBufferDirect(K,B,W,X,R,St),R.onAfterRender(I,B,K,W,X,St)}function od(R,B,K){B.isScene!==!0&&(B=Ci);const W=Y.get(R),X=S.state.lights,St=S.state.shadowsArray,It=X.state.version,xt=mt.getParameters(R,X.state,St,B,K,S.state.lightProbeGridArray),kt=mt.getProgramCacheKey(xt);let Vt=W.programs;W.environment=R.isMeshStandardMaterial||R.isMeshLambertMaterial||R.isMeshPhongMaterial?B.environment:null,W.fog=B.fog;const Se=R.isMeshStandardMaterial||R.isMeshLambertMaterial&&!R.envMap||R.isMeshPhongMaterial&&!R.envMap;W.envMap=ht.get(R.envMap||W.environment,Se),W.envMapRotation=W.environment!==null&&R.envMap===null?B.environmentRotation:R.envMapRotation,Vt===void 0&&(R.addEventListener("dispose",xr),Vt=new Map,W.programs=Vt);let Ie=Vt.get(kt);if(Ie!==void 0){if(W.currentProgram===Ie&&W.lightsStateVersion===It)return Cv(R,xt),Ie}else xt.uniforms=mt.getUniforms(R),C!==null&&R.isNodeMaterial&&C.build(R,K,xt),R.onBeforeCompile(xt,I),Ie=mt.acquireProgram(xt,kt),Vt.set(kt,Ie),W.uniforms=xt.uniforms;const Xt=W.uniforms;return(!R.isShaderMaterial&&!R.isRawShaderMaterial||R.clipping===!0)&&(Xt.clippingPlanes=Zt.uniform),Cv(R,xt),W.needsLights=kS(R),W.lightsStateVersion=It,W.needsLights&&(Xt.ambientLightColor.value=X.state.ambient,Xt.lightProbe.value=X.state.probe,Xt.directionalLights.value=X.state.directional,Xt.directionalLightShadows.value=X.state.directionalShadow,Xt.spotLights.value=X.state.spot,Xt.spotLightShadows.value=X.state.spotShadow,Xt.rectAreaLights.value=X.state.rectArea,Xt.ltc_1.value=X.state.rectAreaLTC1,Xt.ltc_2.value=X.state.rectAreaLTC2,Xt.pointLights.value=X.state.point,Xt.pointLightShadows.value=X.state.pointShadow,Xt.hemisphereLights.value=X.state.hemi,Xt.directionalShadowMatrix.value=X.state.directionalShadowMatrix,Xt.spotLightMatrix.value=X.state.spotLightMatrix,Xt.spotLightMap.value=X.state.spotLightMap,Xt.pointShadowMatrix.value=X.state.pointShadowMatrix),W.lightProbeGrid=S.state.lightProbeGridArray.length>0,W.currentProgram=Ie,W.uniformsList=null,Ie}function Dv(R){if(R.uniformsList===null){const B=R.currentProgram.getUniforms();R.uniformsList=Df.seqWithValue(B.seq,R.uniforms)}return R.uniformsList}function Cv(R,B){const K=Y.get(R);K.outputColorSpace=B.outputColorSpace,K.batching=B.batching,K.batchingColor=B.batchingColor,K.instancing=B.instancing,K.instancingColor=B.instancingColor,K.instancingMorph=B.instancingMorph,K.skinning=B.skinning,K.morphTargets=B.morphTargets,K.morphNormals=B.morphNormals,K.morphColors=B.morphColors,K.morphTargetsCount=B.morphTargetsCount,K.numClippingPlanes=B.numClippingPlanes,K.numIntersection=B.numClipIntersection,K.vertexAlphas=B.vertexAlphas,K.vertexTangents=B.vertexTangents,K.toneMapping=B.toneMapping}function PS(R,B){if(R.length===0)return null;if(R.length===1)return R[0].texture!==null?R[0]:null;y.setFromMatrixPosition(B.matrixWorld);for(let K=0,W=R.length;K<W;K++){const X=R[K];if(X.texture!==null&&X.boundingBox.containsPoint(y))return X}return null}function NS(R,B,K,W,X){B.isScene!==!0&&(B=Ci),J.resetTextureUnits();const St=B.fog,It=W.isMeshStandardMaterial||W.isMeshLambertMaterial||W.isMeshPhongMaterial?B.environment:null,xt=$===null?I.outputColorSpace:$.isXRRenderTarget===!0?$.texture.colorSpace:Fe.workingColorSpace,kt=W.isMeshStandardMaterial||W.isMeshLambertMaterial&&!W.envMap||W.isMeshPhongMaterial&&!W.envMap,Vt=ht.get(W.envMap||It,kt),Se=W.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,Ie=!!K.attributes.tangent&&(!!W.normalMap||W.anisotropy>0),Xt=!!K.morphAttributes.position,li=!!K.morphAttributes.normal,Ki=!!K.morphAttributes.color;let Hi=ea;W.toneMapped&&($===null||$.isXRRenderTarget===!0)&&(Hi=I.toneMapping);const mi=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Un=mi!==void 0?mi.length:0,Tt=Y.get(W),Ds=S.state.lights;if(ee===!0&&(ie===!0||R!==Z)){const wi=R===Z&&W.id===Q;Zt.setState(W,R,wi)}let He=!1;W.version===Tt.__version?(Tt.needsLights&&Tt.lightsStateVersion!==Ds.state.version||Tt.outputColorSpace!==xt||X.isBatchedMesh&&Tt.batching===!1||!X.isBatchedMesh&&Tt.batching===!0||X.isBatchedMesh&&Tt.batchingColor===!0&&X.colorTexture===null||X.isBatchedMesh&&Tt.batchingColor===!1&&X.colorTexture!==null||X.isInstancedMesh&&Tt.instancing===!1||!X.isInstancedMesh&&Tt.instancing===!0||X.isSkinnedMesh&&Tt.skinning===!1||!X.isSkinnedMesh&&Tt.skinning===!0||X.isInstancedMesh&&Tt.instancingColor===!0&&X.instanceColor===null||X.isInstancedMesh&&Tt.instancingColor===!1&&X.instanceColor!==null||X.isInstancedMesh&&Tt.instancingMorph===!0&&X.morphTexture===null||X.isInstancedMesh&&Tt.instancingMorph===!1&&X.morphTexture!==null||Tt.envMap!==Vt||W.fog===!0&&Tt.fog!==St||Tt.numClippingPlanes!==void 0&&(Tt.numClippingPlanes!==Zt.numPlanes||Tt.numIntersection!==Zt.numIntersection)||Tt.vertexAlphas!==Se||Tt.vertexTangents!==Ie||Tt.morphTargets!==Xt||Tt.morphNormals!==li||Tt.morphColors!==Ki||Tt.toneMapping!==Hi||Tt.morphTargetsCount!==Un||!!Tt.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(He=!0):(He=!0,Tt.__version=W.version);let Vs=Tt.currentProgram;He===!0&&(Vs=od(W,B,X),C&&W.isNodeMaterial&&C.onUpdateProgram(W,Vs,Tt));let Sr=!1,Fa=!1,_c=!1;const gi=Vs.getUniforms(),qi=Tt.uniforms;if(E.useProgram(Vs.program)&&(Sr=!0,Fa=!0,_c=!0),W.id!==Q&&(Q=W.id,Fa=!0),Tt.needsLights){const wi=PS(S.state.lightProbeGridArray,X);Tt.lightProbeGrid!==wi&&(Tt.lightProbeGrid=wi,Fa=!0)}if(Sr||Z!==R){E.buffers.depth.getReversed()&&R.reversedDepth!==!0&&(R._reversedDepth=!0,R.updateProjectionMatrix()),gi.setValue(F,"projectionMatrix",R.projectionMatrix),gi.setValue(F,"viewMatrix",R.matrixWorldInverse);const Ba=gi.map.cameraPosition;Ba!==void 0&&Ba.setValue(F,ti.setFromMatrixPosition(R.matrixWorld)),O.logarithmicDepthBuffer&&gi.setValue(F,"logDepthBufFC",2/(Math.log(R.far+1)/Math.LN2)),(W.isMeshPhongMaterial||W.isMeshToonMaterial||W.isMeshLambertMaterial||W.isMeshBasicMaterial||W.isMeshStandardMaterial||W.isShaderMaterial)&&gi.setValue(F,"isOrthographic",R.isOrthographicCamera===!0),Z!==R&&(Z=R,Fa=!0,_c=!0)}if(Tt.needsLights&&(Ds.state.directionalShadowMap.length>0&&gi.setValue(F,"directionalShadowMap",Ds.state.directionalShadowMap,J),Ds.state.spotShadowMap.length>0&&gi.setValue(F,"spotShadowMap",Ds.state.spotShadowMap,J),Ds.state.pointShadowMap.length>0&&gi.setValue(F,"pointShadowMap",Ds.state.pointShadowMap,J)),X.isSkinnedMesh){gi.setOptional(F,X,"bindMatrix"),gi.setOptional(F,X,"bindMatrixInverse");const wi=X.skeleton;wi&&(wi.boneTexture===null&&wi.computeBoneTexture(),gi.setValue(F,"boneTexture",wi.boneTexture,J))}X.isBatchedMesh&&(gi.setOptional(F,X,"batchingTexture"),gi.setValue(F,"batchingTexture",X._matricesTexture,J),gi.setOptional(F,X,"batchingIdTexture"),gi.setValue(F,"batchingIdTexture",X._indirectTexture,J),gi.setOptional(F,X,"batchingColorTexture"),X._colorsTexture!==null&&gi.setValue(F,"batchingColorTexture",X._colorsTexture,J));const za=K.morphAttributes;if((za.position!==void 0||za.normal!==void 0||za.color!==void 0)&&U.update(X,K,Vs),(Fa||Tt.receiveShadow!==X.receiveShadow)&&(Tt.receiveShadow=X.receiveShadow,gi.setValue(F,"receiveShadow",X.receiveShadow)),(W.isMeshStandardMaterial||W.isMeshLambertMaterial||W.isMeshPhongMaterial)&&W.envMap===null&&B.environment!==null&&(qi.envMapIntensity.value=B.environmentIntensity),qi.dfgLUT!==void 0&&(qi.dfgLUT.value=aC()),Fa){if(gi.setValue(F,"toneMappingExposure",I.toneMappingExposure),Tt.needsLights&&LS(qi,_c),St&&W.fog===!0&&Gt.refreshFogUniforms(qi,St),Gt.refreshMaterialUniforms(qi,W,at,ct,S.state.transmissionRenderTarget[R.id]),Tt.needsLights&&Tt.lightProbeGrid){const wi=Tt.lightProbeGrid;qi.probesSH.value=wi.texture,qi.probesMin.value.copy(wi.boundingBox.min),qi.probesMax.value.copy(wi.boundingBox.max),qi.probesResolution.value.copy(wi.resolution)}Df.upload(F,Dv(Tt),qi,J)}if(W.isShaderMaterial&&W.uniformsNeedUpdate===!0&&(Df.upload(F,Dv(Tt),qi,J),W.uniformsNeedUpdate=!1),W.isSpriteMaterial&&gi.setValue(F,"center",X.center),gi.setValue(F,"modelViewMatrix",X.modelViewMatrix),gi.setValue(F,"normalMatrix",X.normalMatrix),gi.setValue(F,"modelMatrix",X.matrixWorld),W.uniformsGroups!==void 0){const wi=W.uniformsGroups;for(let Ba=0,Tc=wi.length;Ba<Tc;Ba++){const Ov=wi[Ba];st.update(Ov,Vs),st.bind(Ov,Vs)}}return Vs}function LS(R,B){R.ambientLightColor.needsUpdate=B,R.lightProbe.needsUpdate=B,R.directionalLights.needsUpdate=B,R.directionalLightShadows.needsUpdate=B,R.pointLights.needsUpdate=B,R.pointLightShadows.needsUpdate=B,R.spotLights.needsUpdate=B,R.spotLightShadows.needsUpdate=B,R.rectAreaLights.needsUpdate=B,R.hemisphereLights.needsUpdate=B}function kS(R){return R.isMeshLambertMaterial||R.isMeshToonMaterial||R.isMeshPhongMaterial||R.isMeshStandardMaterial||R.isShadowMaterial||R.isShaderMaterial&&R.lights===!0}this.getActiveCubeFace=function(){return z},this.getActiveMipmapLevel=function(){return H},this.getRenderTarget=function(){return $},this.setRenderTargetTextures=function(R,B,K){const W=Y.get(R);W.__autoAllocateDepthBuffer=R.resolveDepthBuffer===!1,W.__autoAllocateDepthBuffer===!1&&(W.__useRenderToTexture=!1),Y.get(R.texture).__webglTexture=B,Y.get(R.depthTexture).__webglTexture=W.__autoAllocateDepthBuffer?void 0:K,W.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(R,B){const K=Y.get(R);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0},this.setRenderTarget=function(R,B=0,K=0){$=R,z=B,H=K;let W=null,X=!1,St=!1;if(R){const xt=Y.get(R);if(xt.__useDefaultFramebuffer!==void 0){E.bindFramebuffer(F.FRAMEBUFFER,xt.__webglFramebuffer),nt.copy(R.viewport),ot.copy(R.scissor),Wt=R.scissorTest,E.viewport(nt),E.scissor(ot),E.setScissorTest(Wt),Q=-1;return}else if(xt.__webglFramebuffer===void 0)J.setupRenderTarget(R);else if(xt.__hasExternalTextures)J.rebindTextures(R,Y.get(R.texture).__webglTexture,Y.get(R.depthTexture).__webglTexture);else if(R.depthBuffer){const Se=R.depthTexture;if(xt.__boundDepthTexture!==Se){if(Se!==null&&Y.has(Se)&&(R.width!==Se.image.width||R.height!==Se.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");J.setupDepthRenderbuffer(R)}}const kt=R.texture;(kt.isData3DTexture||kt.isDataArrayTexture||kt.isCompressedArrayTexture)&&(St=!0);const Vt=Y.get(R).__webglFramebuffer;R.isWebGLCubeRenderTarget?(Array.isArray(Vt[B])?W=Vt[B][K]:W=Vt[B],X=!0):R.samples>0&&J.useMultisampledRTT(R)===!1?W=Y.get(R).__webglMultisampledFramebuffer:Array.isArray(Vt)?W=Vt[K]:W=Vt,nt.copy(R.viewport),ot.copy(R.scissor),Wt=R.scissorTest}else nt.copy(Kt).multiplyScalar(at).floor(),ot.copy(Ht).multiplyScalar(at).floor(),Wt=Rt;if(K!==0&&(W=N),E.bindFramebuffer(F.FRAMEBUFFER,W)&&E.drawBuffers(R,W),E.viewport(nt),E.scissor(ot),E.setScissorTest(Wt),X){const xt=Y.get(R.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+B,xt.__webglTexture,K)}else if(St){const xt=B;for(let kt=0;kt<R.textures.length;kt++){const Vt=Y.get(R.textures[kt]);F.framebufferTextureLayer(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0+kt,Vt.__webglTexture,K,xt)}}else if(R!==null&&K!==0){const xt=Y.get(R.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,xt.__webglTexture,K)}Q=-1},this.readRenderTargetPixels=function(R,B,K,W,X,St,It,xt=0){if(!(R&&R.isWebGLRenderTarget)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let kt=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&It!==void 0&&(kt=kt[It]),kt){E.bindFramebuffer(F.FRAMEBUFFER,kt);try{const Vt=R.textures[xt],Se=Vt.format,Ie=Vt.type;if(R.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+xt),!O.textureFormatReadable(Se)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!O.textureTypeReadable(Ie)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}B>=0&&B<=R.width-W&&K>=0&&K<=R.height-X&&F.readPixels(B,K,W,X,vt.convert(Se),vt.convert(Ie),St)}finally{const Vt=$!==null?Y.get($).__webglFramebuffer:null;E.bindFramebuffer(F.FRAMEBUFFER,Vt)}}},this.readRenderTargetPixelsAsync=async function(R,B,K,W,X,St,It,xt=0){if(!(R&&R.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let kt=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&It!==void 0&&(kt=kt[It]),kt)if(B>=0&&B<=R.width-W&&K>=0&&K<=R.height-X){E.bindFramebuffer(F.FRAMEBUFFER,kt);const Vt=R.textures[xt],Se=Vt.format,Ie=Vt.type;if(R.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+xt),!O.textureFormatReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!O.textureTypeReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Xt=F.createBuffer();F.bindBuffer(F.PIXEL_PACK_BUFFER,Xt),F.bufferData(F.PIXEL_PACK_BUFFER,St.byteLength,F.STREAM_READ),F.readPixels(B,K,W,X,vt.convert(Se),vt.convert(Ie),0);const li=$!==null?Y.get($).__webglFramebuffer:null;E.bindFramebuffer(F.FRAMEBUFFER,li);const Ki=F.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);return F.flush(),await i_(F,Ki,4),F.bindBuffer(F.PIXEL_PACK_BUFFER,Xt),F.getBufferSubData(F.PIXEL_PACK_BUFFER,0,St),F.deleteBuffer(Xt),F.deleteSync(Ki),St}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(R,B=null,K=0){const W=Math.pow(2,-K),X=Math.floor(R.image.width*W),St=Math.floor(R.image.height*W),It=B!==null?B.x:0,xt=B!==null?B.y:0;J.setTexture2D(R,0),F.copyTexSubImage2D(F.TEXTURE_2D,K,0,0,It,xt,X,St),E.unbindTexture()},this.copyTextureToTexture=function(R,B,K=null,W=null,X=0,St=0){let It,xt,kt,Vt,Se,Ie,Xt,li,Ki;const Hi=R.isCompressedTexture?R.mipmaps[St]:R.image;if(K!==null)It=K.max.x-K.min.x,xt=K.max.y-K.min.y,kt=K.isBox3?K.max.z-K.min.z:1,Vt=K.min.x,Se=K.min.y,Ie=K.isBox3?K.min.z:0;else{const qi=Math.pow(2,-X);It=Math.floor(Hi.width*qi),xt=Math.floor(Hi.height*qi),R.isDataArrayTexture?kt=Hi.depth:R.isData3DTexture?kt=Math.floor(Hi.depth*qi):kt=1,Vt=0,Se=0,Ie=0}W!==null?(Xt=W.x,li=W.y,Ki=W.z):(Xt=0,li=0,Ki=0);const mi=vt.convert(B.format),Un=vt.convert(B.type);let Tt;B.isData3DTexture?(J.setTexture3D(B,0),Tt=F.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(J.setTexture2DArray(B,0),Tt=F.TEXTURE_2D_ARRAY):(J.setTexture2D(B,0),Tt=F.TEXTURE_2D),E.activeTexture(F.TEXTURE0),E.pixelStorei(F.UNPACK_FLIP_Y_WEBGL,B.flipY),E.pixelStorei(F.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),E.pixelStorei(F.UNPACK_ALIGNMENT,B.unpackAlignment);const Ds=E.getParameter(F.UNPACK_ROW_LENGTH),He=E.getParameter(F.UNPACK_IMAGE_HEIGHT),Vs=E.getParameter(F.UNPACK_SKIP_PIXELS),Sr=E.getParameter(F.UNPACK_SKIP_ROWS),Fa=E.getParameter(F.UNPACK_SKIP_IMAGES);E.pixelStorei(F.UNPACK_ROW_LENGTH,Hi.width),E.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Hi.height),E.pixelStorei(F.UNPACK_SKIP_PIXELS,Vt),E.pixelStorei(F.UNPACK_SKIP_ROWS,Se),E.pixelStorei(F.UNPACK_SKIP_IMAGES,Ie);const _c=R.isDataArrayTexture||R.isData3DTexture,gi=B.isDataArrayTexture||B.isData3DTexture;if(R.isDepthTexture){const qi=Y.get(R),za=Y.get(B),wi=Y.get(qi.__renderTarget),Ba=Y.get(za.__renderTarget);E.bindFramebuffer(F.READ_FRAMEBUFFER,wi.__webglFramebuffer),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,Ba.__webglFramebuffer);for(let Tc=0;Tc<kt;Tc++)_c&&(F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,Y.get(R).__webglTexture,X,Ie+Tc),F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,Y.get(B).__webglTexture,St,Ki+Tc)),F.blitFramebuffer(Vt,Se,It,xt,Xt,li,It,xt,F.DEPTH_BUFFER_BIT,F.NEAREST);E.bindFramebuffer(F.READ_FRAMEBUFFER,null),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else if(X!==0||R.isRenderTargetTexture||Y.has(R)){const qi=Y.get(R),za=Y.get(B);E.bindFramebuffer(F.READ_FRAMEBUFFER,L),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,P);for(let wi=0;wi<kt;wi++)_c?F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,qi.__webglTexture,X,Ie+wi):F.framebufferTexture2D(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,qi.__webglTexture,X),gi?F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,za.__webglTexture,St,Ki+wi):F.framebufferTexture2D(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,za.__webglTexture,St),X!==0?F.blitFramebuffer(Vt,Se,It,xt,Xt,li,It,xt,F.COLOR_BUFFER_BIT,F.NEAREST):gi?F.copyTexSubImage3D(Tt,St,Xt,li,Ki+wi,Vt,Se,It,xt):F.copyTexSubImage2D(Tt,St,Xt,li,Vt,Se,It,xt);E.bindFramebuffer(F.READ_FRAMEBUFFER,null),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else gi?R.isDataTexture||R.isData3DTexture?F.texSubImage3D(Tt,St,Xt,li,Ki,It,xt,kt,mi,Un,Hi.data):B.isCompressedArrayTexture?F.compressedTexSubImage3D(Tt,St,Xt,li,Ki,It,xt,kt,mi,Hi.data):F.texSubImage3D(Tt,St,Xt,li,Ki,It,xt,kt,mi,Un,Hi):R.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,St,Xt,li,It,xt,mi,Un,Hi.data):R.isCompressedTexture?F.compressedTexSubImage2D(F.TEXTURE_2D,St,Xt,li,Hi.width,Hi.height,mi,Hi.data):F.texSubImage2D(F.TEXTURE_2D,St,Xt,li,It,xt,mi,Un,Hi);E.pixelStorei(F.UNPACK_ROW_LENGTH,Ds),E.pixelStorei(F.UNPACK_IMAGE_HEIGHT,He),E.pixelStorei(F.UNPACK_SKIP_PIXELS,Vs),E.pixelStorei(F.UNPACK_SKIP_ROWS,Sr),E.pixelStorei(F.UNPACK_SKIP_IMAGES,Fa),St===0&&B.generateMipmaps&&F.generateMipmap(Tt),E.unbindTexture()},this.initRenderTarget=function(R){Y.get(R).__webglFramebuffer===void 0&&J.setupRenderTarget(R)},this.initTexture=function(R){R.isCubeTexture?J.setTextureCube(R,0):R.isData3DTexture?J.setTexture3D(R,0):R.isDataArrayTexture||R.isCompressedArrayTexture?J.setTexture2DArray(R,0):J.setTexture2D(R,0),E.unbindTexture()},this.resetState=function(){z=0,H=0,$=null,E.reset(),Et.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Qr}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=Fe._getDrawingBufferColorSpace(t),e.unpackColorSpace=Fe._getUnpackColorSpace()}}const cC=`
6521
+ }`;class tC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new cx(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new Te({vertexShader:jD,fragmentShader:QD,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Mt(new Jn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class eC extends Po{constructor(t,e){super();const i=this;let n=null,s=1,r=null,a="local-floor",c=1,h=null,l=null,u=null,d=null,f=null,p=null;const m=typeof XRWebGLBinding<"u",g=new tC,v={},M=e.getContextAttributes();let w=null,y=null;const b=[],S=[],_=new it;let x=null;const A=new Nn;A.viewport=new _e;const I=new Nn;I.viewport=new _e;const D=[A,I],C=new ZT;let N=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(q){let ct=b[q];return ct===void 0&&(ct=new Ap,b[q]=ct),ct.getTargetRaySpace()},this.getControllerGrip=function(q){let ct=b[q];return ct===void 0&&(ct=new Ap,b[q]=ct),ct.getGripSpace()},this.getHand=function(q){let ct=b[q];return ct===void 0&&(ct=new Ap,b[q]=ct),ct.getHandSpace()};function P(q){const ct=S.indexOf(q.inputSource);if(ct===-1)return;const at=b[ct];at!==void 0&&(at.update(q.inputSource,q.frame,h||r),at.dispatchEvent({type:q.type,data:q.inputSource}))}function z(){n.removeEventListener("select",P),n.removeEventListener("selectstart",P),n.removeEventListener("selectend",P),n.removeEventListener("squeeze",P),n.removeEventListener("squeezestart",P),n.removeEventListener("squeezeend",P),n.removeEventListener("end",z),n.removeEventListener("inputsourceschange",H);for(let q=0;q<b.length;q++){const ct=S[q];ct!==null&&(S[q]=null,b[q].disconnect(ct))}N=null,L=null,g.reset();for(const q in v)delete v[q];t.setRenderTarget(w),f=null,d=null,u=null,n=null,y=null,Yt.stop(),i.isPresenting=!1,t.setPixelRatio(x),t.setSize(_.width,_.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(q){s=q,i.isPresenting===!0&&Ut("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(q){a=q,i.isPresenting===!0&&Ut("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return h||r},this.setReferenceSpace=function(q){h=q},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(n,e)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(q){if(n=q,n!==null){if(w=t.getRenderTarget(),n.addEventListener("select",P),n.addEventListener("selectstart",P),n.addEventListener("selectend",P),n.addEventListener("squeeze",P),n.addEventListener("squeezestart",P),n.addEventListener("squeezeend",P),n.addEventListener("end",z),n.addEventListener("inputsourceschange",H),M.xrCompatible!==!0&&await e.makeXRCompatible(),x=t.getPixelRatio(),t.getSize(_),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let at=null,V=null,Ft=null;M.depth&&(Ft=M.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,at=M.stencil?ic:Pa,V=M.stencil?Vu:tr);const Kt={colorFormat:e.RGBA8,depthFormat:Ft,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Kt),n.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new Ke(d.textureWidth,d.textureHeight,{format:$i,type:Kn,depthTexture:new Co(d.textureWidth,d.textureHeight,V,void 0,void 0,void 0,void 0,void 0,void 0,at),stencilBuffer:M.stencil,colorSpace:t.outputColorSpace,samples:M.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const at={antialias:M.antialias,alpha:!0,depth:M.depth,stencil:M.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(n,e,at),n.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ke(f.framebufferWidth,f.framebufferHeight,{format:$i,type:Kn,colorSpace:t.outputColorSpace,stencilBuffer:M.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),h=null,r=await n.requestReferenceSpace(a),Yt.setContext(n),Yt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function H(q){for(let ct=0;ct<q.removed.length;ct++){const at=q.removed[ct],V=S.indexOf(at);V>=0&&(S[V]=null,b[V].disconnect(at))}for(let ct=0;ct<q.added.length;ct++){const at=q.added[ct];let V=S.indexOf(at);if(V===-1){for(let Kt=0;Kt<b.length;Kt++)if(Kt>=S.length){S.push(at),V=Kt;break}else if(S[Kt]===null){S[Kt]=at,V=Kt;break}if(V===-1)break}const Ft=b[V];Ft&&Ft.connect(at)}}const $=new T,Q=new T;function Z(q,ct,at){$.setFromMatrixPosition(ct.matrixWorld),Q.setFromMatrixPosition(at.matrixWorld);const V=$.distanceTo(Q),Ft=ct.projectionMatrix.elements,Kt=at.projectionMatrix.elements,Ht=Ft[14]/(Ft[10]-1),Rt=Ft[14]/(Ft[10]+1),jt=(Ft[9]+1)/Ft[5],ee=(Ft[9]-1)/Ft[5],ie=(Ft[8]-1)/Ft[0],Qe=(Kt[8]+1)/Kt[0],ti=Ht*ie,Fi=Ht*Qe,Ci=V/(-ie+Qe),zi=Ci*-ie;if(ct.matrixWorld.decompose(q.position,q.quaternion,q.scale),q.translateX(zi),q.translateZ(Ci),q.matrixWorld.compose(q.position,q.quaternion,q.scale),q.matrixWorldInverse.copy(q.matrixWorld).invert(),Ft[10]===-1)q.projectionMatrix.copy(ct.projectionMatrix),q.projectionMatrixInverse.copy(ct.projectionMatrixInverse);else{const sn=Ht+Ci,F=Rt+Ci,ds=ti-zi,ei=Fi+(V-zi),O=jt*Rt/F*sn,E=ee*Rt/F*sn;q.projectionMatrix.makePerspective(ds,ei,O,E,sn,F),q.projectionMatrixInverse.copy(q.projectionMatrix).invert()}}function nt(q,ct){ct===null?q.matrixWorld.copy(q.matrix):q.matrixWorld.multiplyMatrices(ct.matrixWorld,q.matrix),q.matrixWorldInverse.copy(q.matrixWorld).invert()}this.updateCamera=function(q){if(n===null)return;let ct=q.near,at=q.far;g.texture!==null&&(g.depthNear>0&&(ct=g.depthNear),g.depthFar>0&&(at=g.depthFar)),C.near=I.near=A.near=ct,C.far=I.far=A.far=at,(N!==C.near||L!==C.far)&&(n.updateRenderState({depthNear:C.near,depthFar:C.far}),N=C.near,L=C.far),C.layers.mask=q.layers.mask|6,A.layers.mask=C.layers.mask&-5,I.layers.mask=C.layers.mask&-3;const V=q.parent,Ft=C.cameras;nt(C,V);for(let Kt=0;Kt<Ft.length;Kt++)nt(Ft[Kt],V);Ft.length===2?Z(C,A,I):C.projectionMatrix.copy(A.projectionMatrix),ot(q,C,V)};function ot(q,ct,at){at===null?q.matrix.copy(ct.matrixWorld):(q.matrix.copy(at.matrixWorld),q.matrix.invert(),q.matrix.multiply(ct.matrixWorld)),q.matrix.decompose(q.position,q.quaternion,q.scale),q.updateMatrixWorld(!0),q.projectionMatrix.copy(ct.projectionMatrix),q.projectionMatrixInverse.copy(ct.projectionMatrixInverse),q.isPerspectiveCamera&&(q.fov=rl*2*Math.atan(1/q.projectionMatrix.elements[5]),q.zoom=1)}this.getCamera=function(){return C},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(q){c=q,d!==null&&(d.fixedFoveation=q),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=q)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(C)},this.getCameraTexture=function(q){return v[q]};let Wt=null;function qt(q,ct){if(l=ct.getViewerPose(h||r),p=ct,l!==null){const at=l.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let V=!1;at.length!==C.cameras.length&&(C.cameras.length=0,V=!0);for(let Rt=0;Rt<at.length;Rt++){const jt=at[Rt];let ee=null;if(f!==null)ee=f.getViewport(jt);else{const Qe=u.getViewSubImage(d,jt);ee=Qe.viewport,Rt===0&&(t.setRenderTargetTextures(y,Qe.colorTexture,Qe.depthStencilTexture),t.setRenderTarget(y))}let ie=D[Rt];ie===void 0&&(ie=new Nn,ie.layers.enable(Rt),ie.viewport=new _e,D[Rt]=ie),ie.matrix.fromArray(jt.transform.matrix),ie.matrix.decompose(ie.position,ie.quaternion,ie.scale),ie.projectionMatrix.fromArray(jt.projectionMatrix),ie.projectionMatrixInverse.copy(ie.projectionMatrix).invert(),ie.viewport.set(ee.x,ee.y,ee.width,ee.height),Rt===0&&(C.matrix.copy(ie.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale)),V===!0&&C.cameras.push(ie)}const Ft=n.enabledFeatures;if(Ft&&Ft.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&m){u=i.getBinding();const Rt=u.getDepthInformation(at[0]);Rt&&Rt.isValid&&Rt.texture&&g.init(Rt,n.renderState)}if(Ft&&Ft.includes("camera-access")&&m){t.state.unbindTexture(),u=i.getBinding();for(let Rt=0;Rt<at.length;Rt++){const jt=at[Rt].camera;if(jt){let ee=v[jt];ee||(ee=new cx,v[jt]=ee);const ie=u.getCameraImage(jt);ee.sourceTexture=ie}}}}for(let at=0;at<b.length;at++){const V=S[at],Ft=b[at];V!==null&&Ft!==void 0&&Ft.update(V,ct,h||r)}Wt&&Wt(q,ct),ct.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ct}),p=null}const Yt=new Ax;Yt.setAnimationLoop(qt),this.setAnimationLoop=function(q){Wt=q},this.dispose=function(){}}}const iC=new oe,Cx=new le;Cx.set(-1,0,0,0,1,0,0,0,1);function nC(o,t){function e(g,v){g.matrixAutoUpdate===!0&&g.updateMatrix(),v.value.copy(g.matrix)}function i(g,v){v.color.getRGB(g.fogColor.value,vx(o)),v.isFog?(g.fogNear.value=v.near,g.fogFar.value=v.far):v.isFogExp2&&(g.fogDensity.value=v.density)}function n(g,v,M,w,y){v.isNodeMaterial?v.uniformsNeedUpdate=!1:v.isMeshBasicMaterial?s(g,v):v.isMeshLambertMaterial?(s(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshToonMaterial?(s(g,v),u(g,v)):v.isMeshPhongMaterial?(s(g,v),l(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshStandardMaterial?(s(g,v),d(g,v),v.isMeshPhysicalMaterial&&f(g,v,y)):v.isMeshMatcapMaterial?(s(g,v),p(g,v)):v.isMeshDepthMaterial?s(g,v):v.isMeshDistanceMaterial?(s(g,v),m(g,v)):v.isMeshNormalMaterial?s(g,v):v.isLineBasicMaterial?(r(g,v),v.isLineDashedMaterial&&a(g,v)):v.isPointsMaterial?c(g,v,M,w):v.isSpriteMaterial?h(g,v):v.isShadowMaterial?(g.color.value.copy(v.color),g.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function s(g,v){g.opacity.value=v.opacity,v.color&&g.diffuse.value.copy(v.color),v.emissive&&g.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.bumpMap&&(g.bumpMap.value=v.bumpMap,e(v.bumpMap,g.bumpMapTransform),g.bumpScale.value=v.bumpScale,v.side===Pi&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,e(v.normalMap,g.normalMapTransform),g.normalScale.value.copy(v.normalScale),v.side===Pi&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,e(v.displacementMap,g.displacementMapTransform),g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap,e(v.emissiveMap,g.emissiveMapTransform)),v.specularMap&&(g.specularMap.value=v.specularMap,e(v.specularMap,g.specularMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);const M=t.get(v),w=M.envMap,y=M.envMapRotation;w&&(g.envMap.value=w,g.envMapRotation.value.setFromMatrix4(iC.makeRotationFromEuler(y)).transpose(),w.isCubeTexture&&w.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(Cx),g.reflectivity.value=v.reflectivity,g.ior.value=v.ior,g.refractionRatio.value=v.refractionRatio),v.lightMap&&(g.lightMap.value=v.lightMap,g.lightMapIntensity.value=v.lightMapIntensity,e(v.lightMap,g.lightMapTransform)),v.aoMap&&(g.aoMap.value=v.aoMap,g.aoMapIntensity.value=v.aoMapIntensity,e(v.aoMap,g.aoMapTransform))}function r(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform))}function a(g,v){g.dashSize.value=v.dashSize,g.totalSize.value=v.dashSize+v.gapSize,g.scale.value=v.scale}function c(g,v,M,w){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.size.value=v.size*M,g.scale.value=w*.5,v.map&&(g.map.value=v.map,e(v.map,g.uvTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function h(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.rotation.value=v.rotation,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function l(g,v){g.specular.value.copy(v.specular),g.shininess.value=Math.max(v.shininess,1e-4)}function u(g,v){v.gradientMap&&(g.gradientMap.value=v.gradientMap)}function d(g,v){g.metalness.value=v.metalness,v.metalnessMap&&(g.metalnessMap.value=v.metalnessMap,e(v.metalnessMap,g.metalnessMapTransform)),g.roughness.value=v.roughness,v.roughnessMap&&(g.roughnessMap.value=v.roughnessMap,e(v.roughnessMap,g.roughnessMapTransform)),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)}function f(g,v,M){g.ior.value=v.ior,v.sheen>0&&(g.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),g.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(g.sheenColorMap.value=v.sheenColorMap,e(v.sheenColorMap,g.sheenColorMapTransform)),v.sheenRoughnessMap&&(g.sheenRoughnessMap.value=v.sheenRoughnessMap,e(v.sheenRoughnessMap,g.sheenRoughnessMapTransform))),v.clearcoat>0&&(g.clearcoat.value=v.clearcoat,g.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(g.clearcoatMap.value=v.clearcoatMap,e(v.clearcoatMap,g.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,e(v.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(g.clearcoatNormalMap.value=v.clearcoatNormalMap,e(v.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Pi&&g.clearcoatNormalScale.value.negate())),v.dispersion>0&&(g.dispersion.value=v.dispersion),v.iridescence>0&&(g.iridescence.value=v.iridescence,g.iridescenceIOR.value=v.iridescenceIOR,g.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(g.iridescenceMap.value=v.iridescenceMap,e(v.iridescenceMap,g.iridescenceMapTransform)),v.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=v.iridescenceThicknessMap,e(v.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),v.transmission>0&&(g.transmission.value=v.transmission,g.transmissionSamplerMap.value=M.texture,g.transmissionSamplerSize.value.set(M.width,M.height),v.transmissionMap&&(g.transmissionMap.value=v.transmissionMap,e(v.transmissionMap,g.transmissionMapTransform)),g.thickness.value=v.thickness,v.thicknessMap&&(g.thicknessMap.value=v.thicknessMap,e(v.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=v.attenuationDistance,g.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(g.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(g.anisotropyMap.value=v.anisotropyMap,e(v.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=v.specularIntensity,g.specularColor.value.copy(v.specularColor),v.specularColorMap&&(g.specularColorMap.value=v.specularColorMap,e(v.specularColorMap,g.specularColorMapTransform)),v.specularIntensityMap&&(g.specularIntensityMap.value=v.specularIntensityMap,e(v.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,v){v.matcap&&(g.matcap.value=v.matcap)}function m(g,v){const M=t.get(v).light;g.referencePosition.value.setFromMatrixPosition(M.matrixWorld),g.nearDistance.value=M.shadow.camera.near,g.farDistance.value=M.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function sC(o,t,e,i){let n={},s={},r=[];const a=o.getParameter(o.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,b){const S=b.program;i.uniformBlockBinding(y,S)}function h(y,b){let S=n[y.id];S===void 0&&(g(y),S=l(y),n[y.id]=S,y.addEventListener("dispose",M));const _=b.program;i.updateUBOMapping(y,_);const x=t.render.frame;s[y.id]!==x&&(d(y),s[y.id]=x)}function l(y){const b=u();y.__bindingPointIndex=b;const S=o.createBuffer(),_=y.__size,x=y.usage;return o.bindBuffer(o.UNIFORM_BUFFER,S),o.bufferData(o.UNIFORM_BUFFER,_,x),o.bindBuffer(o.UNIFORM_BUFFER,null),o.bindBufferBase(o.UNIFORM_BUFFER,b,S),S}function u(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ae("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const b=n[y.id],S=y.uniforms,_=y.__cache;o.bindBuffer(o.UNIFORM_BUFFER,b);for(let x=0,A=S.length;x<A;x++){const I=S[x];if(Array.isArray(I))for(let D=0,C=I.length;D<C;D++)f(I[D],x,D,_);else f(I,x,0,_)}o.bindBuffer(o.UNIFORM_BUFFER,null)}function f(y,b,S,_){if(m(y,b,S,_)===!0){const x=y.__offset,A=y.value;if(Array.isArray(A)){let I=0;for(let D=0;D<A.length;D++){const C=A[D],N=v(C);p(C,y.__data,I),typeof C!="number"&&typeof C!="boolean"&&!C.isMatrix3&&!ArrayBuffer.isView(C)&&(I+=N.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);o.bufferSubData(o.UNIFORM_BUFFER,x,y.__data)}}function p(y,b,S){typeof y=="number"||typeof y=="boolean"?b[0]=y:y.isMatrix3?(b[0]=y.elements[0],b[1]=y.elements[1],b[2]=y.elements[2],b[3]=0,b[4]=y.elements[3],b[5]=y.elements[4],b[6]=y.elements[5],b[7]=0,b[8]=y.elements[6],b[9]=y.elements[7],b[10]=y.elements[8],b[11]=0):ArrayBuffer.isView(y)?b.set(new y.constructor(y.buffer,y.byteOffset,b.length)):y.toArray(b,S)}function m(y,b,S,_){const x=y.value,A=b+"_"+S;if(_[A]===void 0)return typeof x=="number"||typeof x=="boolean"?_[A]=x:ArrayBuffer.isView(x)?_[A]=x.slice():_[A]=x.clone(),!0;{const I=_[A];if(typeof x=="number"||typeof x=="boolean"){if(I!==x)return _[A]=x,!0}else{if(ArrayBuffer.isView(x))return!0;if(I.equals(x)===!1)return I.copy(x),!0}}return!1}function g(y){const b=y.uniforms;let S=0;const _=16;for(let A=0,I=b.length;A<I;A++){const D=Array.isArray(b[A])?b[A]:[b[A]];for(let C=0,N=D.length;C<N;C++){const L=D[C],P=Array.isArray(L.value)?L.value:[L.value];for(let z=0,H=P.length;z<H;z++){const $=P[z],Q=v($),Z=S%_,nt=Z%Q.boundary,ot=Z+nt;S+=nt,ot!==0&&_-ot<Q.storage&&(S+=_-ot),L.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=S,S+=Q.storage}}}const x=S%_;return x>0&&(S+=_-x),y.__size=S,y.__cache={},this}function v(y){const b={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(b.boundary=4,b.storage=4):y.isVector2?(b.boundary=8,b.storage=8):y.isVector3||y.isColor?(b.boundary=16,b.storage=12):y.isVector4?(b.boundary=16,b.storage=16):y.isMatrix3?(b.boundary=48,b.storage=48):y.isMatrix4?(b.boundary=64,b.storage=64):y.isTexture?Ut("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(b.boundary=16,b.storage=y.byteLength):Ut("WebGLRenderer: Unsupported uniform value type.",y),b}function M(y){const b=y.target;b.removeEventListener("dispose",M);const S=r.indexOf(b.__bindingPointIndex);r.splice(S,1),o.deleteBuffer(n[b.id]),delete n[b.id],delete s[b.id]}function w(){for(const y in n)o.deleteBuffer(n[y]);r=[],n={},s={}}return{bind:c,update:h,dispose:w}}const rC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let _r=null;function aC(){return _r===null&&(_r=new us(rC,16,16,bc,Xe),_r.name="DFG_LUT",_r.minFilter=ye,_r.magFilter=ye,_r.wrapS=Xi,_r.wrapT=Xi,_r.generateMipmaps=!1,_r.needsUpdate=!0),_r}class oC{constructor(t={}){const{canvas:e=e_(),context:i=null,depth:n=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:h=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Kn}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=r;const m=f,g=new Set([H1,B1,z1]),v=new Set([Kn,tr,Gu,Vu,U1,F1]),M=new Uint32Array(4),w=new Int32Array(4),y=new T;let b=null,S=null;const _=[],x=[];let A=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ea,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const I=this;let D=!1,C=null,N=null,L=null,P=null;this._outputColorSpace=An;let z=0,H=0,$=null,Q=-1,Z=null;const nt=new _e,ot=new _e;let Wt=null;const qt=new rt(0);let Yt=0,q=e.width,ct=e.height,at=1,V=null,Ft=null;const Kt=new _e(0,0,q,ct),Ht=new _e(0,0,q,ct);let Rt=!1;const jt=new L0;let ee=!1,ie=!1;const Qe=new oe,ti=new T,Fi=new _e,Ci={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let zi=!1;function sn(){return $===null?at:1}let F=i;function ds(R,B){return e.getContext(R,B)}try{const R={alpha:!0,depth:n,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:h,powerPreference:l,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${N1}`),e.addEventListener("webglcontextlost",Bi,!1),e.addEventListener("webglcontextrestored",yi,!1),e.addEventListener("webglcontextcreationerror",br,!1),F===null){const B="webgl2";if(F=ds(B,R),F===null)throw ds(B)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(R){throw ae("WebGLRenderer: "+R.message),R}let ei,O,E,G,Y,J,ht,pt,j,et,mt,Gt,wt,gt,Zt,ne,xe,U,dt,tt,vt,Et,st;function Bt(){ei=new aI(F),ei.init(),vt=new JD(F,ei),O=new j4(F,ei,t,vt),E=new qD(F,ei),O.reversedDepthBuffer&&d&&E.buffers.depth.setReversed(!0),N=F.createFramebuffer(),L=F.createFramebuffer(),P=F.createFramebuffer(),G=new hI(F),Y=new LD,J=new ZD(F,ei,E,Y,O,vt,G),ht=new rI(I),pt=new f5(F),Et=new Z4(F,pt),j=new oI(F,pt,G,Et),et=new uI(F,j,pt,Et,G),U=new lI(F,O,J),Zt=new Q4(Y),mt=new ND(I,ht,ei,O,Et,Zt),Gt=new nC(I,Y),wt=new UD,gt=new VD(ei),xe=new q4(I,ht,E,et,p,c),ne=new KD(I,et,O),st=new sC(F,G,O,E),dt=new J4(F,ei,G),tt=new cI(F,ei,G),G.programs=mt.programs,I.capabilities=O,I.extensions=ei,I.properties=Y,I.renderLists=wt,I.shadowMap=ne,I.state=E,I.info=G}Bt(),m!==Kn&&(A=new fI(m,e.width,e.height,a,n,s));const Pt=new eC(I,F);this.xr=Pt,this.getContext=function(){return F},this.getContextAttributes=function(){return F.getContextAttributes()},this.forceContextLoss=function(){const R=ei.get("WEBGL_lose_context");R&&R.loseContext()},this.forceContextRestore=function(){const R=ei.get("WEBGL_lose_context");R&&R.restoreContext()},this.getPixelRatio=function(){return at},this.setPixelRatio=function(R){R!==void 0&&(at=R,this.setSize(q,ct,!1))},this.getSize=function(R){return R.set(q,ct)},this.setSize=function(R,B,K=!0){if(Pt.isPresenting){Ut("WebGLRenderer: Can't change size while VR device is presenting.");return}q=R,ct=B,e.width=Math.floor(R*at),e.height=Math.floor(B*at),K===!0&&(e.style.width=R+"px",e.style.height=B+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,R,B)},this.getDrawingBufferSize=function(R){return R.set(q*at,ct*at).floor()},this.setDrawingBufferSize=function(R,B,K){q=R,ct=B,at=K,e.width=Math.floor(R*K),e.height=Math.floor(B*K),this.setViewport(0,0,R,B)},this.setEffects=function(R){if(m===Kn){ae("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(R){for(let B=0;B<R.length;B++)if(R[B].isOutputPass===!0){Ut("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(R||[])},this.getCurrentViewport=function(R){return R.copy(nt)},this.getViewport=function(R){return R.copy(Kt)},this.setViewport=function(R,B,K,W){R.isVector4?Kt.set(R.x,R.y,R.z,R.w):Kt.set(R,B,K,W),E.viewport(nt.copy(Kt).multiplyScalar(at).round())},this.getScissor=function(R){return R.copy(Ht)},this.setScissor=function(R,B,K,W){R.isVector4?Ht.set(R.x,R.y,R.z,R.w):Ht.set(R,B,K,W),E.scissor(ot.copy(Ht).multiplyScalar(at).round())},this.getScissorTest=function(){return Rt},this.setScissorTest=function(R){E.setScissorTest(Rt=R)},this.setOpaqueSort=function(R){V=R},this.setTransparentSort=function(R){Ft=R},this.getClearColor=function(R){return R.copy(xe.getClearColor())},this.setClearColor=function(){xe.setClearColor(...arguments)},this.getClearAlpha=function(){return xe.getClearAlpha()},this.setClearAlpha=function(){xe.setClearAlpha(...arguments)},this.clear=function(R=!0,B=!0,K=!0){let W=0;if(R){let X=!1;if($!==null){const St=$.texture.format;X=g.has(St)}if(X){const St=$.texture.type,It=v.has(St),xt=xe.getClearColor(),kt=xe.getClearAlpha(),Vt=xt.r,Se=xt.g,De=xt.b;It?(M[0]=Vt,M[1]=Se,M[2]=De,M[3]=kt,F.clearBufferuiv(F.COLOR,0,M)):(w[0]=Vt,w[1]=Se,w[2]=De,w[3]=kt,F.clearBufferiv(F.COLOR,0,w))}else W|=F.COLOR_BUFFER_BIT}B&&(W|=F.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),K&&(W|=F.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),W!==0&&F.clear(W)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(R){R.setRenderer(this),C=R},this.dispose=function(){e.removeEventListener("webglcontextlost",Bi,!1),e.removeEventListener("webglcontextrestored",yi,!1),e.removeEventListener("webglcontextcreationerror",br,!1),xe.dispose(),wt.dispose(),gt.dispose(),Y.dispose(),ht.dispose(),et.dispose(),Et.dispose(),st.dispose(),mt.dispose(),Pt.dispose(),Pt.removeEventListener("sessionstart",Av),Pt.removeEventListener("sessionend",_v),Lo.stop()};function Bi(R){R.preventDefault(),t0("WebGLRenderer: Context Lost."),D=!0}function yi(){t0("WebGLRenderer: Context Restored."),D=!1;const R=G.autoReset,B=ne.enabled,K=ne.autoUpdate,W=ne.needsUpdate,X=ne.type;Bt(),G.autoReset=R,ne.enabled=B,ne.autoUpdate=K,ne.needsUpdate=W,ne.type=X}function br(R){ae("WebGLRenderer: A WebGL context could not be created. Reason: ",R.statusMessage)}function xr(R){const B=R.target;B.removeEventListener("dispose",xr),DS(B)}function DS(R){CS(R),Y.remove(R)}function CS(R){const B=Y.get(R).programs;B!==void 0&&(B.forEach(function(K){mt.releaseProgram(K)}),R.isShaderMaterial&&mt.releaseShaderCache(R))}this.renderBufferDirect=function(R,B,K,W,X,St){B===null&&(B=Ci);const It=X.isMesh&&X.matrixWorld.determinantAffine()<0,xt=NS(R,B,K,W,X);E.setMaterial(W,It);let kt=K.index,Vt=1;if(W.wireframe===!0){if(kt=j.getWireframeAttribute(K),kt===void 0)return;Vt=2}const Se=K.drawRange,De=K.attributes.position;let Xt=Se.start*Vt,li=(Se.start+Se.count)*Vt;St!==null&&(Xt=Math.max(Xt,St.start*Vt),li=Math.min(li,(St.start+St.count)*Vt)),kt!==null?(Xt=Math.max(Xt,0),li=Math.min(li,kt.count)):De!=null&&(Xt=Math.max(Xt,0),li=Math.min(li,De.count));const Ki=li-Xt;if(Ki<0||Ki===1/0)return;Et.setup(X,W,xt,K,kt);let Hi,mi=dt;if(kt!==null&&(Hi=pt.get(kt),mi=tt,mi.setIndex(Hi)),X.isMesh)W.wireframe===!0?(E.setLineWidth(W.wireframeLinewidth*sn()),mi.setMode(F.LINES)):mi.setMode(F.TRIANGLES);else if(X.isLine){let Un=W.linewidth;Un===void 0&&(Un=1),E.setLineWidth(Un*sn()),X.isLineSegments?mi.setMode(F.LINES):X.isLineLoop?mi.setMode(F.LINE_LOOP):mi.setMode(F.LINE_STRIP)}else X.isPoints?mi.setMode(F.POINTS):X.isSprite&&mi.setMode(F.TRIANGLES);if(X.isBatchedMesh)if(ei.get("WEBGL_multi_draw"))mi.renderMultiDraw(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount);else{const Un=X._multiDrawStarts,Tt=X._multiDrawCounts,Ds=X._multiDrawCount,He=kt?pt.get(kt).bytesPerElement:1,Vs=Y.get(W).currentProgram.getUniforms();for(let Sr=0;Sr<Ds;Sr++)Vs.setValue(F,"_gl_DrawID",Sr),mi.render(Un[Sr]/He,Tt[Sr])}else if(X.isInstancedMesh)mi.renderInstances(Xt,Ki,X.count);else if(K.isInstancedBufferGeometry){const Un=K._maxInstanceCount!==void 0?K._maxInstanceCount:1/0,Tt=Math.min(K.instanceCount,Un);mi.renderInstances(Xt,Ki,Tt)}else mi.render(Xt,Ki)};function Ev(R,B,K){R.transparent===!0&&R.side===_n&&R.forceSinglePass===!1?(R.side=Pi,R.needsUpdate=!0,od(R,B,K),R.side=Io,R.needsUpdate=!0,od(R,B,K),R.side=_n):od(R,B,K)}this.compile=function(R,B,K=null){K===null&&(K=R),S=gt.get(K),S.init(B),x.push(S),K.traverseVisible(function(X){X.isLight&&X.layers.test(B.layers)&&(S.pushLight(X),X.castShadow&&S.pushShadow(X))}),R!==K&&R.traverseVisible(function(X){X.isLight&&X.layers.test(B.layers)&&(S.pushLight(X),X.castShadow&&S.pushShadow(X))}),S.setupLights();const W=new Set;return R.traverse(function(X){if(!(X.isMesh||X.isPoints||X.isLine||X.isSprite))return;const St=X.material;if(St)if(Array.isArray(St))for(let It=0;It<St.length;It++){const xt=St[It];Ev(xt,K,X),W.add(xt)}else Ev(St,K,X),W.add(St)}),S=x.pop(),W},this.compileAsync=function(R,B,K=null){const W=this.compile(R,B,K);return new Promise(X=>{function St(){if(W.forEach(function(It){Y.get(It).currentProgram.isReady()&&W.delete(It)}),W.size===0){X(R);return}setTimeout(St,10)}ei.get("KHR_parallel_shader_compile")!==null?St():setTimeout(St,10)})};let Z0=null;function OS(R){Z0&&Z0(R)}function Av(){Lo.stop()}function _v(){Lo.start()}const Lo=new Ax;Lo.setAnimationLoop(OS),typeof self<"u"&&Lo.setContext(self),this.setAnimationLoop=function(R){Z0=R,Pt.setAnimationLoop(R),R===null?Lo.stop():Lo.start()},Pt.addEventListener("sessionstart",Av),Pt.addEventListener("sessionend",_v),this.render=function(R,B){if(B!==void 0&&B.isCamera!==!0){ae("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;C!==null&&C.renderStart(R,B);const K=Pt.enabled===!0&&Pt.isPresenting===!0,W=A!==null&&($===null||K)&&A.begin(I,$);if(R.matrixWorldAutoUpdate===!0&&R.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),Pt.enabled===!0&&Pt.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(Pt.cameraAutoUpdate===!0&&Pt.updateCamera(B),B=Pt.getCamera()),R.isScene===!0&&R.onBeforeRender(I,R,B,$),S=gt.get(R,x.length),S.init(B),S.state.textureUnits=J.getTextureUnits(),x.push(S),Qe.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),jt.setFromProjectionMatrix(Qe,Qr,B.reversedDepth),ie=this.localClippingEnabled,ee=Zt.init(this.clippingPlanes,ie),b=wt.get(R,_.length),b.init(),_.push(b),Pt.enabled===!0&&Pt.isPresenting===!0){const It=I.xr.getDepthSensingMesh();It!==null&&J0(It,B,-1/0,I.sortObjects)}J0(R,B,0,I.sortObjects),b.finish(),I.sortObjects===!0&&b.sort(V,Ft,B.reversedDepth),zi=Pt.enabled===!1||Pt.isPresenting===!1||Pt.hasDepthSensing()===!1,zi&&xe.addToRenderList(b,R),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ee===!0&&Zt.beginShadows();const X=S.state.shadowsArray;if(ne.render(X,R,B),ee===!0&&Zt.endShadows(),(W&&A.hasRenderPass())===!1){const It=b.opaque,xt=b.transmissive;if(S.setupLights(),B.isArrayCamera){const kt=B.cameras;if(xt.length>0)for(let Vt=0,Se=kt.length;Vt<Se;Vt++){const De=kt[Vt];Rv(It,xt,R,De)}zi&&xe.render(R);for(let Vt=0,Se=kt.length;Vt<Se;Vt++){const De=kt[Vt];Tv(b,R,De,De.viewport)}}else xt.length>0&&Rv(It,xt,R,B),zi&&xe.render(R),Tv(b,R,B)}$!==null&&H===0&&(J.updateMultisampleRenderTarget($),J.updateRenderTargetMipmap($)),W&&A.end(I),R.isScene===!0&&R.onAfterRender(I,R,B),Et.resetDefaultState(),Q=-1,Z=null,x.pop(),x.length>0?(S=x[x.length-1],J.setTextureUnits(S.state.textureUnits),ee===!0&&Zt.setGlobalState(I.clippingPlanes,S.state.camera)):S=null,_.pop(),_.length>0?b=_[_.length-1]:b=null,C!==null&&C.renderEnd()};function J0(R,B,K,W){if(R.visible===!1)return;if(R.layers.test(B.layers)){if(R.isGroup)K=R.renderOrder;else if(R.isLOD)R.autoUpdate===!0&&R.update(B);else if(R.isLightProbeGrid)S.pushLightProbeGrid(R);else if(R.isLight)S.pushLight(R),R.castShadow&&S.pushShadow(R);else if(R.isSprite){if(!R.frustumCulled||jt.intersectsSprite(R)){W&&Fi.setFromMatrixPosition(R.matrixWorld).applyMatrix4(Qe);const It=et.update(R),xt=R.material;xt.visible&&b.push(R,It,xt,K,Fi.z,null)}}else if((R.isMesh||R.isLine||R.isPoints)&&(!R.frustumCulled||jt.intersectsObject(R))){const It=et.update(R),xt=R.material;if(W&&(R.boundingSphere!==void 0?(R.boundingSphere===null&&R.computeBoundingSphere(),Fi.copy(R.boundingSphere.center)):(It.boundingSphere===null&&It.computeBoundingSphere(),Fi.copy(It.boundingSphere.center)),Fi.applyMatrix4(R.matrixWorld).applyMatrix4(Qe)),Array.isArray(xt)){const kt=It.groups;for(let Vt=0,Se=kt.length;Vt<Se;Vt++){const De=kt[Vt],Xt=xt[De.materialIndex];Xt&&Xt.visible&&b.push(R,It,Xt,K,Fi.z,De)}}else xt.visible&&b.push(R,It,xt,K,Fi.z,null)}}const St=R.children;for(let It=0,xt=St.length;It<xt;It++)J0(St[It],B,K,W)}function Tv(R,B,K,W){const{opaque:X,transmissive:St,transparent:It}=R;S.setupLightsView(K),ee===!0&&Zt.setGlobalState(I.clippingPlanes,K),W&&E.viewport(nt.copy(W)),X.length>0&&ad(X,B,K),St.length>0&&ad(St,B,K),It.length>0&&ad(It,B,K),E.buffers.depth.setTest(!0),E.buffers.depth.setMask(!0),E.buffers.color.setMask(!0),E.setPolygonOffset(!1)}function Rv(R,B,K,W){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[W.id]===void 0){const Xt=ei.has("EXT_color_buffer_half_float")||ei.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[W.id]=new Ke(1,1,{generateMipmaps:!0,type:Xt?Xe:Kn,minFilter:Bs,samples:Math.max(4,O.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Fe.workingColorSpace})}const St=S.state.transmissionRenderTarget[W.id],It=W.viewport||nt;St.setSize(It.z*I.transmissionResolutionScale,It.w*I.transmissionResolutionScale);const xt=I.getRenderTarget(),kt=I.getActiveCubeFace(),Vt=I.getActiveMipmapLevel();I.setRenderTarget(St),I.getClearColor(qt),Yt=I.getClearAlpha(),Yt<1&&I.setClearColor(16777215,.5),I.clear(),zi&&xe.render(K);const Se=I.toneMapping;I.toneMapping=ea;const De=W.viewport;if(W.viewport!==void 0&&(W.viewport=void 0),S.setupLightsView(W),ee===!0&&Zt.setGlobalState(I.clippingPlanes,W),ad(R,K,W),J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St),ei.has("WEBGL_multisampled_render_to_texture")===!1){let Xt=!1;for(let li=0,Ki=B.length;li<Ki;li++){const Hi=B[li],{object:mi,geometry:Un,material:Tt,group:Ds}=Hi;if(Tt.side===_n&&mi.layers.test(W.layers)){const He=Tt.side;Tt.side=Pi,Tt.needsUpdate=!0,Iv(mi,K,W,Un,Tt,Ds),Tt.side=He,Tt.needsUpdate=!0,Xt=!0}}Xt===!0&&(J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St))}I.setRenderTarget(xt,kt,Vt),I.setClearColor(qt,Yt),De!==void 0&&(W.viewport=De),I.toneMapping=Se}function ad(R,B,K){const W=B.isScene===!0?B.overrideMaterial:null;for(let X=0,St=R.length;X<St;X++){const It=R[X],{object:xt,geometry:kt,group:Vt}=It;let Se=It.material;Se.allowOverride===!0&&W!==null&&(Se=W),xt.layers.test(K.layers)&&Iv(xt,B,K,kt,Se,Vt)}}function Iv(R,B,K,W,X,St){R.onBeforeRender(I,B,K,W,X,St),R.modelViewMatrix.multiplyMatrices(K.matrixWorldInverse,R.matrixWorld),R.normalMatrix.getNormalMatrix(R.modelViewMatrix),X.onBeforeRender(I,B,K,W,R,St),X.transparent===!0&&X.side===_n&&X.forceSinglePass===!1?(X.side=Pi,X.needsUpdate=!0,I.renderBufferDirect(K,B,W,X,R,St),X.side=Io,X.needsUpdate=!0,I.renderBufferDirect(K,B,W,X,R,St),X.side=_n):I.renderBufferDirect(K,B,W,X,R,St),R.onAfterRender(I,B,K,W,X,St)}function od(R,B,K){B.isScene!==!0&&(B=Ci);const W=Y.get(R),X=S.state.lights,St=S.state.shadowsArray,It=X.state.version,xt=mt.getParameters(R,X.state,St,B,K,S.state.lightProbeGridArray),kt=mt.getProgramCacheKey(xt);let Vt=W.programs;W.environment=R.isMeshStandardMaterial||R.isMeshLambertMaterial||R.isMeshPhongMaterial?B.environment:null,W.fog=B.fog;const Se=R.isMeshStandardMaterial||R.isMeshLambertMaterial&&!R.envMap||R.isMeshPhongMaterial&&!R.envMap;W.envMap=ht.get(R.envMap||W.environment,Se),W.envMapRotation=W.environment!==null&&R.envMap===null?B.environmentRotation:R.envMapRotation,Vt===void 0&&(R.addEventListener("dispose",xr),Vt=new Map,W.programs=Vt);let De=Vt.get(kt);if(De!==void 0){if(W.currentProgram===De&&W.lightsStateVersion===It)return Cv(R,xt),De}else xt.uniforms=mt.getUniforms(R),C!==null&&R.isNodeMaterial&&C.build(R,K,xt),R.onBeforeCompile(xt,I),De=mt.acquireProgram(xt,kt),Vt.set(kt,De),W.uniforms=xt.uniforms;const Xt=W.uniforms;return(!R.isShaderMaterial&&!R.isRawShaderMaterial||R.clipping===!0)&&(Xt.clippingPlanes=Zt.uniform),Cv(R,xt),W.needsLights=kS(R),W.lightsStateVersion=It,W.needsLights&&(Xt.ambientLightColor.value=X.state.ambient,Xt.lightProbe.value=X.state.probe,Xt.directionalLights.value=X.state.directional,Xt.directionalLightShadows.value=X.state.directionalShadow,Xt.spotLights.value=X.state.spot,Xt.spotLightShadows.value=X.state.spotShadow,Xt.rectAreaLights.value=X.state.rectArea,Xt.ltc_1.value=X.state.rectAreaLTC1,Xt.ltc_2.value=X.state.rectAreaLTC2,Xt.pointLights.value=X.state.point,Xt.pointLightShadows.value=X.state.pointShadow,Xt.hemisphereLights.value=X.state.hemi,Xt.directionalShadowMatrix.value=X.state.directionalShadowMatrix,Xt.spotLightMatrix.value=X.state.spotLightMatrix,Xt.spotLightMap.value=X.state.spotLightMap,Xt.pointShadowMatrix.value=X.state.pointShadowMatrix),W.lightProbeGrid=S.state.lightProbeGridArray.length>0,W.currentProgram=De,W.uniformsList=null,De}function Dv(R){if(R.uniformsList===null){const B=R.currentProgram.getUniforms();R.uniformsList=Df.seqWithValue(B.seq,R.uniforms)}return R.uniformsList}function Cv(R,B){const K=Y.get(R);K.outputColorSpace=B.outputColorSpace,K.batching=B.batching,K.batchingColor=B.batchingColor,K.instancing=B.instancing,K.instancingColor=B.instancingColor,K.instancingMorph=B.instancingMorph,K.skinning=B.skinning,K.morphTargets=B.morphTargets,K.morphNormals=B.morphNormals,K.morphColors=B.morphColors,K.morphTargetsCount=B.morphTargetsCount,K.numClippingPlanes=B.numClippingPlanes,K.numIntersection=B.numClipIntersection,K.vertexAlphas=B.vertexAlphas,K.vertexTangents=B.vertexTangents,K.toneMapping=B.toneMapping}function PS(R,B){if(R.length===0)return null;if(R.length===1)return R[0].texture!==null?R[0]:null;y.setFromMatrixPosition(B.matrixWorld);for(let K=0,W=R.length;K<W;K++){const X=R[K];if(X.texture!==null&&X.boundingBox.containsPoint(y))return X}return null}function NS(R,B,K,W,X){B.isScene!==!0&&(B=Ci),J.resetTextureUnits();const St=B.fog,It=W.isMeshStandardMaterial||W.isMeshLambertMaterial||W.isMeshPhongMaterial?B.environment:null,xt=$===null?I.outputColorSpace:$.isXRRenderTarget===!0?$.texture.colorSpace:Fe.workingColorSpace,kt=W.isMeshStandardMaterial||W.isMeshLambertMaterial&&!W.envMap||W.isMeshPhongMaterial&&!W.envMap,Vt=ht.get(W.envMap||It,kt),Se=W.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,De=!!K.attributes.tangent&&(!!W.normalMap||W.anisotropy>0),Xt=!!K.morphAttributes.position,li=!!K.morphAttributes.normal,Ki=!!K.morphAttributes.color;let Hi=ea;W.toneMapped&&($===null||$.isXRRenderTarget===!0)&&(Hi=I.toneMapping);const mi=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Un=mi!==void 0?mi.length:0,Tt=Y.get(W),Ds=S.state.lights;if(ee===!0&&(ie===!0||R!==Z)){const wi=R===Z&&W.id===Q;Zt.setState(W,R,wi)}let He=!1;W.version===Tt.__version?(Tt.needsLights&&Tt.lightsStateVersion!==Ds.state.version||Tt.outputColorSpace!==xt||X.isBatchedMesh&&Tt.batching===!1||!X.isBatchedMesh&&Tt.batching===!0||X.isBatchedMesh&&Tt.batchingColor===!0&&X.colorTexture===null||X.isBatchedMesh&&Tt.batchingColor===!1&&X.colorTexture!==null||X.isInstancedMesh&&Tt.instancing===!1||!X.isInstancedMesh&&Tt.instancing===!0||X.isSkinnedMesh&&Tt.skinning===!1||!X.isSkinnedMesh&&Tt.skinning===!0||X.isInstancedMesh&&Tt.instancingColor===!0&&X.instanceColor===null||X.isInstancedMesh&&Tt.instancingColor===!1&&X.instanceColor!==null||X.isInstancedMesh&&Tt.instancingMorph===!0&&X.morphTexture===null||X.isInstancedMesh&&Tt.instancingMorph===!1&&X.morphTexture!==null||Tt.envMap!==Vt||W.fog===!0&&Tt.fog!==St||Tt.numClippingPlanes!==void 0&&(Tt.numClippingPlanes!==Zt.numPlanes||Tt.numIntersection!==Zt.numIntersection)||Tt.vertexAlphas!==Se||Tt.vertexTangents!==De||Tt.morphTargets!==Xt||Tt.morphNormals!==li||Tt.morphColors!==Ki||Tt.toneMapping!==Hi||Tt.morphTargetsCount!==Un||!!Tt.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(He=!0):(He=!0,Tt.__version=W.version);let Vs=Tt.currentProgram;He===!0&&(Vs=od(W,B,X),C&&W.isNodeMaterial&&C.onUpdateProgram(W,Vs,Tt));let Sr=!1,Fa=!1,_c=!1;const gi=Vs.getUniforms(),qi=Tt.uniforms;if(E.useProgram(Vs.program)&&(Sr=!0,Fa=!0,_c=!0),W.id!==Q&&(Q=W.id,Fa=!0),Tt.needsLights){const wi=PS(S.state.lightProbeGridArray,X);Tt.lightProbeGrid!==wi&&(Tt.lightProbeGrid=wi,Fa=!0)}if(Sr||Z!==R){E.buffers.depth.getReversed()&&R.reversedDepth!==!0&&(R._reversedDepth=!0,R.updateProjectionMatrix()),gi.setValue(F,"projectionMatrix",R.projectionMatrix),gi.setValue(F,"viewMatrix",R.matrixWorldInverse);const Ba=gi.map.cameraPosition;Ba!==void 0&&Ba.setValue(F,ti.setFromMatrixPosition(R.matrixWorld)),O.logarithmicDepthBuffer&&gi.setValue(F,"logDepthBufFC",2/(Math.log(R.far+1)/Math.LN2)),(W.isMeshPhongMaterial||W.isMeshToonMaterial||W.isMeshLambertMaterial||W.isMeshBasicMaterial||W.isMeshStandardMaterial||W.isShaderMaterial)&&gi.setValue(F,"isOrthographic",R.isOrthographicCamera===!0),Z!==R&&(Z=R,Fa=!0,_c=!0)}if(Tt.needsLights&&(Ds.state.directionalShadowMap.length>0&&gi.setValue(F,"directionalShadowMap",Ds.state.directionalShadowMap,J),Ds.state.spotShadowMap.length>0&&gi.setValue(F,"spotShadowMap",Ds.state.spotShadowMap,J),Ds.state.pointShadowMap.length>0&&gi.setValue(F,"pointShadowMap",Ds.state.pointShadowMap,J)),X.isSkinnedMesh){gi.setOptional(F,X,"bindMatrix"),gi.setOptional(F,X,"bindMatrixInverse");const wi=X.skeleton;wi&&(wi.boneTexture===null&&wi.computeBoneTexture(),gi.setValue(F,"boneTexture",wi.boneTexture,J))}X.isBatchedMesh&&(gi.setOptional(F,X,"batchingTexture"),gi.setValue(F,"batchingTexture",X._matricesTexture,J),gi.setOptional(F,X,"batchingIdTexture"),gi.setValue(F,"batchingIdTexture",X._indirectTexture,J),gi.setOptional(F,X,"batchingColorTexture"),X._colorsTexture!==null&&gi.setValue(F,"batchingColorTexture",X._colorsTexture,J));const za=K.morphAttributes;if((za.position!==void 0||za.normal!==void 0||za.color!==void 0)&&U.update(X,K,Vs),(Fa||Tt.receiveShadow!==X.receiveShadow)&&(Tt.receiveShadow=X.receiveShadow,gi.setValue(F,"receiveShadow",X.receiveShadow)),(W.isMeshStandardMaterial||W.isMeshLambertMaterial||W.isMeshPhongMaterial)&&W.envMap===null&&B.environment!==null&&(qi.envMapIntensity.value=B.environmentIntensity),qi.dfgLUT!==void 0&&(qi.dfgLUT.value=aC()),Fa){if(gi.setValue(F,"toneMappingExposure",I.toneMappingExposure),Tt.needsLights&&LS(qi,_c),St&&W.fog===!0&&Gt.refreshFogUniforms(qi,St),Gt.refreshMaterialUniforms(qi,W,at,ct,S.state.transmissionRenderTarget[R.id]),Tt.needsLights&&Tt.lightProbeGrid){const wi=Tt.lightProbeGrid;qi.probesSH.value=wi.texture,qi.probesMin.value.copy(wi.boundingBox.min),qi.probesMax.value.copy(wi.boundingBox.max),qi.probesResolution.value.copy(wi.resolution)}Df.upload(F,Dv(Tt),qi,J)}if(W.isShaderMaterial&&W.uniformsNeedUpdate===!0&&(Df.upload(F,Dv(Tt),qi,J),W.uniformsNeedUpdate=!1),W.isSpriteMaterial&&gi.setValue(F,"center",X.center),gi.setValue(F,"modelViewMatrix",X.modelViewMatrix),gi.setValue(F,"normalMatrix",X.normalMatrix),gi.setValue(F,"modelMatrix",X.matrixWorld),W.uniformsGroups!==void 0){const wi=W.uniformsGroups;for(let Ba=0,Tc=wi.length;Ba<Tc;Ba++){const Ov=wi[Ba];st.update(Ov,Vs),st.bind(Ov,Vs)}}return Vs}function LS(R,B){R.ambientLightColor.needsUpdate=B,R.lightProbe.needsUpdate=B,R.directionalLights.needsUpdate=B,R.directionalLightShadows.needsUpdate=B,R.pointLights.needsUpdate=B,R.pointLightShadows.needsUpdate=B,R.spotLights.needsUpdate=B,R.spotLightShadows.needsUpdate=B,R.rectAreaLights.needsUpdate=B,R.hemisphereLights.needsUpdate=B}function kS(R){return R.isMeshLambertMaterial||R.isMeshToonMaterial||R.isMeshPhongMaterial||R.isMeshStandardMaterial||R.isShadowMaterial||R.isShaderMaterial&&R.lights===!0}this.getActiveCubeFace=function(){return z},this.getActiveMipmapLevel=function(){return H},this.getRenderTarget=function(){return $},this.setRenderTargetTextures=function(R,B,K){const W=Y.get(R);W.__autoAllocateDepthBuffer=R.resolveDepthBuffer===!1,W.__autoAllocateDepthBuffer===!1&&(W.__useRenderToTexture=!1),Y.get(R.texture).__webglTexture=B,Y.get(R.depthTexture).__webglTexture=W.__autoAllocateDepthBuffer?void 0:K,W.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(R,B){const K=Y.get(R);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0},this.setRenderTarget=function(R,B=0,K=0){$=R,z=B,H=K;let W=null,X=!1,St=!1;if(R){const xt=Y.get(R);if(xt.__useDefaultFramebuffer!==void 0){E.bindFramebuffer(F.FRAMEBUFFER,xt.__webglFramebuffer),nt.copy(R.viewport),ot.copy(R.scissor),Wt=R.scissorTest,E.viewport(nt),E.scissor(ot),E.setScissorTest(Wt),Q=-1;return}else if(xt.__webglFramebuffer===void 0)J.setupRenderTarget(R);else if(xt.__hasExternalTextures)J.rebindTextures(R,Y.get(R.texture).__webglTexture,Y.get(R.depthTexture).__webglTexture);else if(R.depthBuffer){const Se=R.depthTexture;if(xt.__boundDepthTexture!==Se){if(Se!==null&&Y.has(Se)&&(R.width!==Se.image.width||R.height!==Se.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");J.setupDepthRenderbuffer(R)}}const kt=R.texture;(kt.isData3DTexture||kt.isDataArrayTexture||kt.isCompressedArrayTexture)&&(St=!0);const Vt=Y.get(R).__webglFramebuffer;R.isWebGLCubeRenderTarget?(Array.isArray(Vt[B])?W=Vt[B][K]:W=Vt[B],X=!0):R.samples>0&&J.useMultisampledRTT(R)===!1?W=Y.get(R).__webglMultisampledFramebuffer:Array.isArray(Vt)?W=Vt[K]:W=Vt,nt.copy(R.viewport),ot.copy(R.scissor),Wt=R.scissorTest}else nt.copy(Kt).multiplyScalar(at).floor(),ot.copy(Ht).multiplyScalar(at).floor(),Wt=Rt;if(K!==0&&(W=N),E.bindFramebuffer(F.FRAMEBUFFER,W)&&E.drawBuffers(R,W),E.viewport(nt),E.scissor(ot),E.setScissorTest(Wt),X){const xt=Y.get(R.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+B,xt.__webglTexture,K)}else if(St){const xt=B;for(let kt=0;kt<R.textures.length;kt++){const Vt=Y.get(R.textures[kt]);F.framebufferTextureLayer(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0+kt,Vt.__webglTexture,K,xt)}}else if(R!==null&&K!==0){const xt=Y.get(R.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,xt.__webglTexture,K)}Q=-1},this.readRenderTargetPixels=function(R,B,K,W,X,St,It,xt=0){if(!(R&&R.isWebGLRenderTarget)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let kt=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&It!==void 0&&(kt=kt[It]),kt){E.bindFramebuffer(F.FRAMEBUFFER,kt);try{const Vt=R.textures[xt],Se=Vt.format,De=Vt.type;if(R.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+xt),!O.textureFormatReadable(Se)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!O.textureTypeReadable(De)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}B>=0&&B<=R.width-W&&K>=0&&K<=R.height-X&&F.readPixels(B,K,W,X,vt.convert(Se),vt.convert(De),St)}finally{const Vt=$!==null?Y.get($).__webglFramebuffer:null;E.bindFramebuffer(F.FRAMEBUFFER,Vt)}}},this.readRenderTargetPixelsAsync=async function(R,B,K,W,X,St,It,xt=0){if(!(R&&R.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let kt=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&It!==void 0&&(kt=kt[It]),kt)if(B>=0&&B<=R.width-W&&K>=0&&K<=R.height-X){E.bindFramebuffer(F.FRAMEBUFFER,kt);const Vt=R.textures[xt],Se=Vt.format,De=Vt.type;if(R.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+xt),!O.textureFormatReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!O.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Xt=F.createBuffer();F.bindBuffer(F.PIXEL_PACK_BUFFER,Xt),F.bufferData(F.PIXEL_PACK_BUFFER,St.byteLength,F.STREAM_READ),F.readPixels(B,K,W,X,vt.convert(Se),vt.convert(De),0);const li=$!==null?Y.get($).__webglFramebuffer:null;E.bindFramebuffer(F.FRAMEBUFFER,li);const Ki=F.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);return F.flush(),await i_(F,Ki,4),F.bindBuffer(F.PIXEL_PACK_BUFFER,Xt),F.getBufferSubData(F.PIXEL_PACK_BUFFER,0,St),F.deleteBuffer(Xt),F.deleteSync(Ki),St}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(R,B=null,K=0){const W=Math.pow(2,-K),X=Math.floor(R.image.width*W),St=Math.floor(R.image.height*W),It=B!==null?B.x:0,xt=B!==null?B.y:0;J.setTexture2D(R,0),F.copyTexSubImage2D(F.TEXTURE_2D,K,0,0,It,xt,X,St),E.unbindTexture()},this.copyTextureToTexture=function(R,B,K=null,W=null,X=0,St=0){let It,xt,kt,Vt,Se,De,Xt,li,Ki;const Hi=R.isCompressedTexture?R.mipmaps[St]:R.image;if(K!==null)It=K.max.x-K.min.x,xt=K.max.y-K.min.y,kt=K.isBox3?K.max.z-K.min.z:1,Vt=K.min.x,Se=K.min.y,De=K.isBox3?K.min.z:0;else{const qi=Math.pow(2,-X);It=Math.floor(Hi.width*qi),xt=Math.floor(Hi.height*qi),R.isDataArrayTexture?kt=Hi.depth:R.isData3DTexture?kt=Math.floor(Hi.depth*qi):kt=1,Vt=0,Se=0,De=0}W!==null?(Xt=W.x,li=W.y,Ki=W.z):(Xt=0,li=0,Ki=0);const mi=vt.convert(B.format),Un=vt.convert(B.type);let Tt;B.isData3DTexture?(J.setTexture3D(B,0),Tt=F.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(J.setTexture2DArray(B,0),Tt=F.TEXTURE_2D_ARRAY):(J.setTexture2D(B,0),Tt=F.TEXTURE_2D),E.activeTexture(F.TEXTURE0),E.pixelStorei(F.UNPACK_FLIP_Y_WEBGL,B.flipY),E.pixelStorei(F.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),E.pixelStorei(F.UNPACK_ALIGNMENT,B.unpackAlignment);const Ds=E.getParameter(F.UNPACK_ROW_LENGTH),He=E.getParameter(F.UNPACK_IMAGE_HEIGHT),Vs=E.getParameter(F.UNPACK_SKIP_PIXELS),Sr=E.getParameter(F.UNPACK_SKIP_ROWS),Fa=E.getParameter(F.UNPACK_SKIP_IMAGES);E.pixelStorei(F.UNPACK_ROW_LENGTH,Hi.width),E.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Hi.height),E.pixelStorei(F.UNPACK_SKIP_PIXELS,Vt),E.pixelStorei(F.UNPACK_SKIP_ROWS,Se),E.pixelStorei(F.UNPACK_SKIP_IMAGES,De);const _c=R.isDataArrayTexture||R.isData3DTexture,gi=B.isDataArrayTexture||B.isData3DTexture;if(R.isDepthTexture){const qi=Y.get(R),za=Y.get(B),wi=Y.get(qi.__renderTarget),Ba=Y.get(za.__renderTarget);E.bindFramebuffer(F.READ_FRAMEBUFFER,wi.__webglFramebuffer),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,Ba.__webglFramebuffer);for(let Tc=0;Tc<kt;Tc++)_c&&(F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,Y.get(R).__webglTexture,X,De+Tc),F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,Y.get(B).__webglTexture,St,Ki+Tc)),F.blitFramebuffer(Vt,Se,It,xt,Xt,li,It,xt,F.DEPTH_BUFFER_BIT,F.NEAREST);E.bindFramebuffer(F.READ_FRAMEBUFFER,null),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else if(X!==0||R.isRenderTargetTexture||Y.has(R)){const qi=Y.get(R),za=Y.get(B);E.bindFramebuffer(F.READ_FRAMEBUFFER,L),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,P);for(let wi=0;wi<kt;wi++)_c?F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,qi.__webglTexture,X,De+wi):F.framebufferTexture2D(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,qi.__webglTexture,X),gi?F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,za.__webglTexture,St,Ki+wi):F.framebufferTexture2D(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,za.__webglTexture,St),X!==0?F.blitFramebuffer(Vt,Se,It,xt,Xt,li,It,xt,F.COLOR_BUFFER_BIT,F.NEAREST):gi?F.copyTexSubImage3D(Tt,St,Xt,li,Ki+wi,Vt,Se,It,xt):F.copyTexSubImage2D(Tt,St,Xt,li,Vt,Se,It,xt);E.bindFramebuffer(F.READ_FRAMEBUFFER,null),E.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else gi?R.isDataTexture||R.isData3DTexture?F.texSubImage3D(Tt,St,Xt,li,Ki,It,xt,kt,mi,Un,Hi.data):B.isCompressedArrayTexture?F.compressedTexSubImage3D(Tt,St,Xt,li,Ki,It,xt,kt,mi,Hi.data):F.texSubImage3D(Tt,St,Xt,li,Ki,It,xt,kt,mi,Un,Hi):R.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,St,Xt,li,It,xt,mi,Un,Hi.data):R.isCompressedTexture?F.compressedTexSubImage2D(F.TEXTURE_2D,St,Xt,li,Hi.width,Hi.height,mi,Hi.data):F.texSubImage2D(F.TEXTURE_2D,St,Xt,li,It,xt,mi,Un,Hi);E.pixelStorei(F.UNPACK_ROW_LENGTH,Ds),E.pixelStorei(F.UNPACK_IMAGE_HEIGHT,He),E.pixelStorei(F.UNPACK_SKIP_PIXELS,Vs),E.pixelStorei(F.UNPACK_SKIP_ROWS,Sr),E.pixelStorei(F.UNPACK_SKIP_IMAGES,Fa),St===0&&B.generateMipmaps&&F.generateMipmap(Tt),E.unbindTexture()},this.initRenderTarget=function(R){Y.get(R).__webglFramebuffer===void 0&&J.setupRenderTarget(R)},this.initTexture=function(R){R.isCubeTexture?J.setTextureCube(R,0):R.isData3DTexture?J.setTexture3D(R,0):R.isDataArrayTexture||R.isCompressedArrayTexture?J.setTexture2DArray(R,0):J.setTexture2D(R,0),E.unbindTexture()},this.resetState=function(){z=0,H=0,$=null,E.reset(),Et.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Qr}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=Fe._getDrawingBufferColorSpace(t),e.unpackColorSpace=Fe._getUnpackColorSpace()}}const cC=`
6522
6522
  varying vec3 vDir;
6523
6523
  varying vec3 vWorldDir;
6524
6524
 
@@ -7538,7 +7538,7 @@ float grassNoise(vec2 p) {
7538
7538
  + (grassNoise(vGrassPatchXZ * 21.0) - 0.5) * 0.6 * (1.0 - smoothstep(2.5, 12.0, eye));
7539
7539
  float d = grain * uGrassContrast * grass;
7540
7540
  diffuseColor.rgb *= vec3(1.0 + d * 1.1, 1.0 + d, 1.0 + d * 1.25);
7541
- }`)},t.customProgramCacheKey=()=>e?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class Ir{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(t,e,i){const n=i&&i.length>=2?Ir.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=Ir.fill(t,r).filter(l=>!n?.[l]);if(a.length===0)continue;const c=a.map(l=>t.heights[l]).filter(Number.isFinite).sort((l,u)=>l-u);if(c.length===0)continue;const h=c[Math.floor((c.length-1)*Ir.LEVEL_QUANTILE)];for(const l of a)t.heights[l]>h&&(t.heights[l]=h,s++)}return s}static fill(t,e){const{width:i,height:n,bounds:s}=t,r=d=>(d-s.west)/(s.east-s.west)*(i-1),a=d=>(s.north-d)/(s.north-s.south)*(n-1),c=[];for(const d of e.rings)for(let f=0;f<d.length;f++){const p=d[f],m=d[(f+1)%d.length],g={r0:a(p.lat),c0:r(p.lng),r1:a(m.lat),c1:r(m.lng)};g.r0!==g.r1&&c.push(g)}const h=[];if(c.length===0)return h;const l=Math.max(0,Math.ceil(Math.min(...c.map(d=>Math.min(d.r0,d.r1))))),u=Math.min(n-1,Math.floor(Math.max(...c.map(d=>Math.max(d.r0,d.r1)))));for(let d=l;d<=u;d++){const f=[];for(const{r0:p,c0:m,r1:g,c1:v}of c)p<=d!=g<=d&&f.push(m+(v-m)*(d-p)/(g-p));f.sort((p,m)=>p-m);for(let p=0;p+1<f.length;p+=2){const m=Math.max(0,Math.ceil(f[p])),g=Math.min(i-1,Math.floor(f[p+1]));for(let v=m;v<=g;v++)h.push(d*i+v)}}return h}static alongRoute(t,e){const{width:i,height:n,bounds:s}=t,r=(s.east-s.west)*Ir.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*Ir.METRES_PER_DEGREE/(n-1),c=Math.ceil(Ir.ROUTE_CLEARANCE_M/r),h=Math.ceil(Ir.ROUTE_CLEARANCE_M/a),l=new Uint8Array(i*n),u=f=>(f-s.west)/(s.east-s.west)*(i-1),d=f=>(s.north-f)/(s.north-s.south)*(n-1);for(let f=0;f+1<e.length;f++){const[p,m,g,v]=[u(e[f].lng),d(e[f].lat),u(e[f+1].lng),d(e[f+1].lat)];if(Math.max(p,g)<-c||Math.min(p,g)>i-1+c||Math.max(m,v)<-h||Math.min(m,v)>n-1+h)continue;const M=Math.max(1,Math.ceil(Math.hypot(g-p,v-m)*2));for(let w=0;w<=M;w++){const y=Math.round(p+(g-p)*w/M),b=Math.round(m+(v-m)*w/M);for(let S=-h;S<=h;S++)for(let _=-c;_<=c;_++){const x=b+S,A=y+_;x<0||A<0||x>=n||A>=i||Math.hypot(_*r,S*a)<=Ir.ROUTE_CLEARANCE_M&&(l[x*i+A]=1)}}}return l}}const j6=64,K2=j6+1,q2=2048,Q6=900,tO=700/900,eO=0,iO=.01,nO=1500;function ru(o,t,e){return{north:As(0,-e,o,t).lat,south:As(0,e,o,t).lat,east:As(e,0,o,t).lng,west:As(-e,0,o,t).lng}}async function Z2(o,t,e,i=Q6,n,s){const r=i,a=i*tO,c=ru(o,t,r),h={width:K2,height:K2},l=s?void 0:e.water?.getWater(c).catch(N=>(console.warn("Water unavailable, drawing none:",N),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,h,n),e.imagery.getImageryTexture(c,{width:q2,height:q2})]);let f;const p=l?await Promise.race([l,new Promise(N=>{f=setTimeout(()=>N(void 0),nO)})]):void 0;if(clearTimeout(f),u.width!==u.height||u.width<3||u.heights.length!==u.width*u.height)throw new Error("The ground came as a grid that is not square");p0.fill(u.heights,u.width),p&&p.length>0&&Ir.flatten(u,p,n?.route);const m=u.width,g=m-1,v=Math.floor(m/2),M=u.heights[v*m+v],w=s?.referenceElevationM??M,y=new Float32Array(m*m*3),b=new Float32Array(m*m*2),S=new Float32Array(m*m*4);for(let N=0;N<m;N++){const L=N/(m-1),P=c.north+(c.south-c.north)*L;for(let z=0;z<m;z++){const H=z/(m-1),$=c.west+(c.east-c.west)*H,{x:Q,z:Z}=de(P,$,o,t),nt=u.heights[N*m+z],ot=Math.max(Math.abs(Q),Math.abs(Z)),Wt=s&&ot<s.innerM?0:1-sO((ot-a)/(r-a),0,1),qt=eO+iO+(nt-w),Yt=N*m+z;y[Yt*3]=Q,y[Yt*3+1]=qt,y[Yt*3+2]=Z;const q=Ib(d.bounds,$,P);b[Yt*2]=q.x,b[Yt*2+1]=q.y,S[Yt*4]=1,S[Yt*4+1]=1,S[Yt*4+2]=1,S[Yt*4+3]=Wt}}const _=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let x=0;for(let N=0;N<g;N++)for(let L=0;L<g;L++){const P=N*m+L,z=P+1,H=P+m,$=H+1;_[x++]=P,_[x++]=H,_[x++]=z,_[x++]=z,_[x++]=H,_[x++]=$}const A=new me;A.setAttribute("position",new fe(y,3)),A.setAttribute("uv",new fe(b,2)),A.setAttribute("color",new fe(S,4)),A.setIndex(new fe(_,1)),A.computeVertexNormals();const I=new No(d.source);I.flipY=!1,I.colorSpace=An,I.anisotropy=8;const D=new er({map:I,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||Gh.install(D);const C=new Mt(A,D);return C.receiveShadow=!s,C.castShadow=!s,{mesh:C,attribution:e.imagery.attribution,originElevationM:Number.isFinite(M)?M:void 0,...p?{water:p}:l?{waterLater:l}:{}}}class p0{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<p0.LOWEST_GROUND_M;let n=0;for(let s=0;s<t.length;s++)i(t[s])&&n++;for(let s=0;n>0&&s<p0.MAX_PASSES;s++){const r=[];for(let a=0;a<e;a++)for(let c=0;c<e;c++){const h=a*e+c;if(!i(t[h]))continue;let l=0,u=0;for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){const p=a+d,m=c+f;if(p<0||m<0||p>=e||m>=e)continue;const g=t[p*e+m];i(g)||(l+=g,u++)}u>0&&r.push([h,l/u])}for(const[a,c]of r)t[a]=c;if(n-=r.length,r.length===0)break}if(n>0)for(let s=0;s<t.length;s++)i(t[s])&&(t[s]=0)}}function sO(o,t,e){return Math.max(t,Math.min(e,o))}class Me{static STEP_M=8;stepM=Me.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new it;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Be;surveyed=new Be;stated=new Be;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(t){this.stepM=Number.isFinite(t)&&t>0?Math.min(Me.STEP_M,Math.max(1.5,t/2)):Me.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=Me.within(t,e,i,r);Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const h=new Map,l=c.map(f=>f.points.map(p=>de(p.lat,p.lng,e,i))),u=c.map((f,p)=>this.streetOf(f,l[p],a));for(const[f,p]of c.entries()){const m=h.get(p.surface)??Me.batchFor(p.surface);h.set(p.surface,m);const g=u[f];this.appendPath(l[f],p.widthM,n,m,g?{lateralAt:(v,M,w,y)=>g(v,M,w,y).carriageway}:{})}for(const[f,p]of h){const m=this.meshOf(f,p,s);m&&this.surveyed.add(m)}const d=this.sidewalks(c,l,u,n);if(d.indices.length>0){const f=this.meshOf("paved",d,!1,Me.SIDEWALK_ALBEDO,!1);f&&(f.name="roads sidewalks",this.surveyed.add(f))}this.paint(c,e,i,n,s)}paint(t,e,i,n,s){if(!t.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(Me.markingsModule??=De(()=>import("./RoadMarkings-DKxgMzE-.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const c={positions:[],indices:[]};if(a.lay(t,e,i,(u,d,f)=>this.appendPath(u,d,n,c,{offsetM:f.offsetM,liftM:Me.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,Me.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=Me.MARKINGS_RENDER_ORDER,u.material.polygonOffsetFactor=-4,u.material.polygonOffsetUnits=-4,this.surveyed.add(u))}const l=a.barrierGeometry(a.barriers(t,e,i),n);if(l.indices.length>0){const u=this.meshOf("paved",l,s,Me.BARRIER_ALBEDO,!1);u&&(u.name="roads barriers",u.material.polygonOffset=!1,u.castShadow=!0,this.surveyed.add(u))}this.onMarkings?.()})}onMarkings;anchorGrain(t,e){if(this.grainReference){const n=de(this.grainReference.lat,this.grainReference.lng,t,e);Math.hypot(n.x,n.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:t,lng:e};const i=de(this.grainReference.lat,this.grainReference.lng,t,e);this.grainOrigin.set(-i.x,-i.z)}static within(t,e,i,n){if(!Number.isFinite(n))return t;const s=n*1.1+100;return t.filter(r=>{let a;for(const c of r.points){const h=de(c.lat,c.lng,e,i);if(Math.hypot(h.x,h.z)<=s||a&&Math.hypot((h.x+a.x)/2,(h.z+a.z)/2)<=s)return!0;a=h}return!1})}streetOf(t,e,i){if(!t.urban||t.surface!=="paved")return;const n=Me.surveyedAcross(t);if(!i||!i.near(e))return()=>n;const s=new Map,r=(f,p,m,g)=>{const v=`${f.toFixed(2)}:${p.toFixed(2)}`;let M=s.get(v);return M||(M=i.across(f,p,m,g),s.set(v,M)),M},a=this.rungsOf(e),c=a.flatMap(f=>{const p=r(f.x,f.z,f.dirX,f.dirZ);return p.leftM!==void 0&&p.rightM!==void 0?[(p.leftM-p.rightM)/2]:[]}).sort((f,p)=>f-p),h=i.lampsAlong(e);if(c.length===0&&h.length===0)return()=>n;const l=c.length>0?c[Math.floor((c.length-1)/2)]:0,u=Me.clearOf(h,t.widthM/2,Math.max(-2.5,Math.min(Me.STREET_MIDDLE_MOST_M,l))),d={rungs:a,across:(f,p,m,g)=>Me.betweenWalls(t,u,r(f,p,m,g).leftM,r(f,p,m,g).rightM)};return this.laidStreets.push(d),(f,p,m,g)=>{const v=r(f,p,m,g);return Me.betweenWalls(t,u,v.leftM,v.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+Me.LAMP_CLEARANCE_M);if(n(i))return i;const s=Me.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*s;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=s&&n(a))return a;return i}atKerb(t,e){let i;for(const d of this.laidStreets)for(const f of d.rungs){const p=Math.hypot(t-f.x,e-f.z);p<=Me.KERB_REACH_M&&(!i||p<i.distance)&&(i={rung:f,across:d.across(f.x,f.z,f.dirX,f.dirZ),distance:p})}if(!i)return{x:t,z:e};const{rung:n,across:s}=i,r=(t-n.x)*-n.dirZ+(e-n.z)*n.dirX,a=(t-n.x)*n.dirX+(e-n.z)*n.dirZ,h=(r>=s.carriageway.offsetM?s.left:s.right)??s.left??s.right;if(!h)return{x:t,z:e};const l=Math.sign(h.outerM-h.kerbM),u=h.kerbM+l*Math.min(Me.LAMP_FROM_KERB_M,Math.abs(h.outerM-h.kerbM)/2);return{x:n.x+n.dirX*a-n.dirZ*u,z:n.z+n.dirZ*a+n.dirX*u}}rungsOf(t){const e=this.resample(t);return e.map((i,n)=>{const s=e[Math.max(0,n-1)],r=e[Math.min(e.length-1,n+1)],a=r.x-s.x,c=r.z-s.z,h=Math.hypot(a,c);return h<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/h,dirZ:c/h}})}static surveyedAcross(t){const e=t.widthM/2,i={offsetM:0,halfM:e};return t.widthM<Me.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+Me.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-Me.SIDEWALK_WIDTH_M}}}static betweenWalls(t,e,i,n){const s=t.widthM/2,r={offsetM:e,halfM:s},a=e+s,c=e-s,h=i??a+Me.SIDEWALK_WIDTH_M,l=-(n??-c+Me.SIDEWALK_WIDTH_M);return{carriageway:r,...h-a>=Me.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:h}}:{},...c-l>=Me.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:l}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new Dr(t,e);return t.forEach((a,c)=>{const h=i[c];if(!h)return;const l=(u,d)=>r.onAnotherCarriageway(u,d,c);for(const u of["left","right"]){const d=(f,p,m,g)=>{const v=h(f,p,m,g)[u];return v&&{offsetM:(v.kerbM+v.outerM)/2,halfM:Math.abs(v.outerM-v.kerbM)/2}};this.appendPath(e[c],0,n,s,{lateralAt:d,liftM:Me.LIFT_M+Me.SIDEWALK_KERB_M,minHalfM:0,skip:l}),this.appendKerb(e[c],n,s,(f,p,m,g)=>h(f,p,m,g)[u]?.kerbM,u==="left",l)}}),s}setStated(t,e){Me.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??Me.batchFor(n.surface);i.set(n.surface,s),this.appendPath(n.path.map(r=>({x:r.eastM,z:-r.northM})),n.widthM,e,s)}for(const[n,s]of i){const r=this.meshOf(n,s,!1);r&&this.stated.add(r)}}clear(){Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(t){for(const e of[...t.children]){t.remove(e);const i=e;i.geometry?.dispose(),i.material?.dispose()}}dispose(){Me.empty(this.surveyed),Me.empty(this.stated)}appendPath(t,e,i,n,s={}){const r=this.resample(t);if(r.length<2)return;const a=Math.max(s.minHalfM??.5,e/2),c=s.liftM??Me.LIFT_M,h=s.offsetM??0,l=n.positions.length/3,u=[],d=[],f=[];for(let m=0;m<r.length;m++){const g=r[Math.max(0,m-1)],v=r[Math.min(r.length-1,m+1)];let M=v.x-g.x,w=v.z-g.z;const y=Math.hypot(M,w);y<1e-6?(M=1,w=0):(M/=y,w/=y);const b=s.lateralAt?s.lateralAt(r[m].x,r[m].z,M,w):{offsetM:h,halfM:a},S=b?Math.max(s.minHalfM??.5,b.halfM):a,_=b?.offsetM??h,x=-w*S,A=M*S,I={x:r[m].x+-w*_,z:r[m].z+M*_};u.push(b!==void 0&&b.halfM>0&&!s.skip?.(I.x,I.z)),d.push([{x:I.x+x,z:I.z+A},I,{x:I.x-x,z:I.z-A}]),f.push(S)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const v=d[m][g],M=d[m+1][g],w=i((v.x+M.x)/2,(v.z+M.z)/2)-(p[m][g]+p[m+1][g])/2;w>0&&(p[m][g]+=w,p[m+1][g]+=w)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=l+m*3;n.indices.push(g,g+3,g+1,g+1,g+3,g+4),n.indices.push(g+1,g+4,g+2,g+2,g+4,g+5)}}appendKerb(t,e,i,n,s,r){const a=this.resample(t);if(a.length<2)return;const c=i.positions.length/3,h=[];for(let l=0;l<a.length;l++){const u=a[Math.max(0,l-1)],d=a[Math.min(a.length-1,l+1)];let f=d.x-u.x,p=d.z-u.z;const m=Math.hypot(f,p);m<1e-6?(f=1,p=0):(f/=m,p/=m);const g=n(a[l].x,a[l].z,f,p),v=a[l].x+-p*(g??0),M=a[l].z+f*(g??0);h.push(g!==void 0&&!r(v,M));const w=e(v,M)+Me.LIFT_M;i.positions.push(v,w,M,v,w+Me.SIDEWALK_KERB_M,M)}for(let l=0;l<a.length-1;l++){if(!h[l]||!h[l+1])continue;const u=c+l*2;s?i.indices.push(u,u+1,u+2,u+1,u+3,u+2):i.indices.push(u,u+2,u+1,u+1,u+2,u+3)}}static batchFor(t){return t==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(t,e,i,n,s=!0){if(e.indices.length===0)return;const r=new me;r.setAttribute("position",new fe(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new fe(new Float32Array(e.edges),2)),r.setIndex(new fe(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??Me.ALBEDO[t],h=new er({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?Me.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(h,Me.GRAIN_CONTRAST[t],a);const l=new Mt(r,h);return l.name=`roads ${t}`,l.renderOrder=Me.RENDER_ORDER,l.receiveShadow=!0,l.castShadow=!1,l}addGrain(t,e,i=!1){const n=this.grainOrigin;t.onBeforeCompile=s=>{s.uniforms.uRoadOrigin={value:n},s.uniforms.uRoadContrast={value:e},i&&(s.defines={...s.defines,ROAD_VERGE:""}),s.vertexShader=s.vertexShader.replace("#include <common>",`#include <common>
7541
+ }`)},t.customProgramCacheKey=()=>e?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class Ir{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(t,e,i){const n=i&&i.length>=2?Ir.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=Ir.fill(t,r).filter(l=>!n?.[l]);if(a.length===0)continue;const c=a.map(l=>t.heights[l]).filter(Number.isFinite).sort((l,u)=>l-u);if(c.length===0)continue;const h=c[Math.floor((c.length-1)*Ir.LEVEL_QUANTILE)];for(const l of a)t.heights[l]>h&&(t.heights[l]=h,s++)}return s}static fill(t,e){const{width:i,height:n,bounds:s}=t,r=d=>(d-s.west)/(s.east-s.west)*(i-1),a=d=>(s.north-d)/(s.north-s.south)*(n-1),c=[];for(const d of e.rings)for(let f=0;f<d.length;f++){const p=d[f],m=d[(f+1)%d.length],g={r0:a(p.lat),c0:r(p.lng),r1:a(m.lat),c1:r(m.lng)};g.r0!==g.r1&&c.push(g)}const h=[];if(c.length===0)return h;const l=Math.max(0,Math.ceil(Math.min(...c.map(d=>Math.min(d.r0,d.r1))))),u=Math.min(n-1,Math.floor(Math.max(...c.map(d=>Math.max(d.r0,d.r1)))));for(let d=l;d<=u;d++){const f=[];for(const{r0:p,c0:m,r1:g,c1:v}of c)p<=d!=g<=d&&f.push(m+(v-m)*(d-p)/(g-p));f.sort((p,m)=>p-m);for(let p=0;p+1<f.length;p+=2){const m=Math.max(0,Math.ceil(f[p])),g=Math.min(i-1,Math.floor(f[p+1]));for(let v=m;v<=g;v++)h.push(d*i+v)}}return h}static alongRoute(t,e){const{width:i,height:n,bounds:s}=t,r=(s.east-s.west)*Ir.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*Ir.METRES_PER_DEGREE/(n-1),c=Math.ceil(Ir.ROUTE_CLEARANCE_M/r),h=Math.ceil(Ir.ROUTE_CLEARANCE_M/a),l=new Uint8Array(i*n),u=f=>(f-s.west)/(s.east-s.west)*(i-1),d=f=>(s.north-f)/(s.north-s.south)*(n-1);for(let f=0;f+1<e.length;f++){const[p,m,g,v]=[u(e[f].lng),d(e[f].lat),u(e[f+1].lng),d(e[f+1].lat)];if(Math.max(p,g)<-c||Math.min(p,g)>i-1+c||Math.max(m,v)<-h||Math.min(m,v)>n-1+h)continue;const M=Math.max(1,Math.ceil(Math.hypot(g-p,v-m)*2));for(let w=0;w<=M;w++){const y=Math.round(p+(g-p)*w/M),b=Math.round(m+(v-m)*w/M);for(let S=-h;S<=h;S++)for(let _=-c;_<=c;_++){const x=b+S,A=y+_;x<0||A<0||x>=n||A>=i||Math.hypot(_*r,S*a)<=Ir.ROUTE_CLEARANCE_M&&(l[x*i+A]=1)}}}return l}}const j6=64,K2=j6+1,q2=2048,Q6=900,tO=700/900,eO=0,iO=.01,nO=1500;function ru(o,t,e){return{north:As(0,-e,o,t).lat,south:As(0,e,o,t).lat,east:As(e,0,o,t).lng,west:As(-e,0,o,t).lng}}async function Z2(o,t,e,i=Q6,n,s){const r=i,a=i*tO,c=ru(o,t,r),h={width:K2,height:K2},l=s?void 0:e.water?.getWater(c).catch(N=>(console.warn("Water unavailable, drawing none:",N),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,h,n),e.imagery.getImageryTexture(c,{width:q2,height:q2})]);let f;const p=l?await Promise.race([l,new Promise(N=>{f=setTimeout(()=>N(void 0),nO)})]):void 0;if(clearTimeout(f),u.width!==u.height||u.width<3||u.heights.length!==u.width*u.height)throw new Error("The ground came as a grid that is not square");p0.fill(u.heights,u.width),p&&p.length>0&&Ir.flatten(u,p,n?.route);const m=u.width,g=m-1,v=Math.floor(m/2),M=u.heights[v*m+v],w=s?.referenceElevationM??M,y=new Float32Array(m*m*3),b=new Float32Array(m*m*2),S=new Float32Array(m*m*4);for(let N=0;N<m;N++){const L=N/(m-1),P=c.north+(c.south-c.north)*L;for(let z=0;z<m;z++){const H=z/(m-1),$=c.west+(c.east-c.west)*H,{x:Q,z:Z}=de(P,$,o,t),nt=u.heights[N*m+z],ot=Math.max(Math.abs(Q),Math.abs(Z)),Wt=s&&ot<s.innerM?0:1-sO((ot-a)/(r-a),0,1),qt=eO+iO+(nt-w),Yt=N*m+z;y[Yt*3]=Q,y[Yt*3+1]=qt,y[Yt*3+2]=Z;const q=Ib(d.bounds,$,P);b[Yt*2]=q.x,b[Yt*2+1]=q.y,S[Yt*4]=1,S[Yt*4+1]=1,S[Yt*4+2]=1,S[Yt*4+3]=Wt}}const _=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let x=0;for(let N=0;N<g;N++)for(let L=0;L<g;L++){const P=N*m+L,z=P+1,H=P+m,$=H+1;_[x++]=P,_[x++]=H,_[x++]=z,_[x++]=z,_[x++]=H,_[x++]=$}const A=new me;A.setAttribute("position",new fe(y,3)),A.setAttribute("uv",new fe(b,2)),A.setAttribute("color",new fe(S,4)),A.setIndex(new fe(_,1)),A.computeVertexNormals();const I=new No(d.source);I.flipY=!1,I.colorSpace=An,I.anisotropy=8;const D=new er({map:I,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||Gh.install(D);const C=new Mt(A,D);return C.receiveShadow=!s,C.castShadow=!s,{mesh:C,attribution:e.imagery.attribution,originElevationM:Number.isFinite(M)?M:void 0,...p?{water:p}:l?{waterLater:l}:{}}}class p0{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<p0.LOWEST_GROUND_M;let n=0;for(let s=0;s<t.length;s++)i(t[s])&&n++;for(let s=0;n>0&&s<p0.MAX_PASSES;s++){const r=[];for(let a=0;a<e;a++)for(let c=0;c<e;c++){const h=a*e+c;if(!i(t[h]))continue;let l=0,u=0;for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){const p=a+d,m=c+f;if(p<0||m<0||p>=e||m>=e)continue;const g=t[p*e+m];i(g)||(l+=g,u++)}u>0&&r.push([h,l/u])}for(const[a,c]of r)t[a]=c;if(n-=r.length,r.length===0)break}if(n>0)for(let s=0;s<t.length;s++)i(t[s])&&(t[s]=0)}}function sO(o,t,e){return Math.max(t,Math.min(e,o))}class Me{static STEP_M=8;stepM=Me.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new it;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Be;surveyed=new Be;stated=new Be;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(t){this.stepM=Number.isFinite(t)&&t>0?Math.min(Me.STEP_M,Math.max(1.5,t/2)):Me.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=Me.within(t,e,i,r);Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const h=new Map,l=c.map(f=>f.points.map(p=>de(p.lat,p.lng,e,i))),u=c.map((f,p)=>this.streetOf(f,l[p],a));for(const[f,p]of c.entries()){const m=h.get(p.surface)??Me.batchFor(p.surface);h.set(p.surface,m);const g=u[f];this.appendPath(l[f],p.widthM,n,m,g?{lateralAt:(v,M,w,y)=>g(v,M,w,y).carriageway}:{})}for(const[f,p]of h){const m=this.meshOf(f,p,s);m&&this.surveyed.add(m)}const d=this.sidewalks(c,l,u,n);if(d.indices.length>0){const f=this.meshOf("paved",d,!1,Me.SIDEWALK_ALBEDO,!1);f&&(f.name="roads sidewalks",this.surveyed.add(f))}this.paint(c,e,i,n,s)}paint(t,e,i,n,s){if(!t.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(Me.markingsModule??=Ie(()=>import("./RoadMarkings-DKxgMzE-.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const c={positions:[],indices:[]};if(a.lay(t,e,i,(u,d,f)=>this.appendPath(u,d,n,c,{offsetM:f.offsetM,liftM:Me.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,Me.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=Me.MARKINGS_RENDER_ORDER,u.material.polygonOffsetFactor=-4,u.material.polygonOffsetUnits=-4,this.surveyed.add(u))}const l=a.barrierGeometry(a.barriers(t,e,i),n);if(l.indices.length>0){const u=this.meshOf("paved",l,s,Me.BARRIER_ALBEDO,!1);u&&(u.name="roads barriers",u.material.polygonOffset=!1,u.castShadow=!0,this.surveyed.add(u))}this.onMarkings?.()})}onMarkings;anchorGrain(t,e){if(this.grainReference){const n=de(this.grainReference.lat,this.grainReference.lng,t,e);Math.hypot(n.x,n.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:t,lng:e};const i=de(this.grainReference.lat,this.grainReference.lng,t,e);this.grainOrigin.set(-i.x,-i.z)}static within(t,e,i,n){if(!Number.isFinite(n))return t;const s=n*1.1+100;return t.filter(r=>{let a;for(const c of r.points){const h=de(c.lat,c.lng,e,i);if(Math.hypot(h.x,h.z)<=s||a&&Math.hypot((h.x+a.x)/2,(h.z+a.z)/2)<=s)return!0;a=h}return!1})}streetOf(t,e,i){if(!t.urban||t.surface!=="paved")return;const n=Me.surveyedAcross(t);if(!i||!i.near(e))return()=>n;const s=new Map,r=(f,p,m,g)=>{const v=`${f.toFixed(2)}:${p.toFixed(2)}`;let M=s.get(v);return M||(M=i.across(f,p,m,g),s.set(v,M)),M},a=this.rungsOf(e),c=a.flatMap(f=>{const p=r(f.x,f.z,f.dirX,f.dirZ);return p.leftM!==void 0&&p.rightM!==void 0?[(p.leftM-p.rightM)/2]:[]}).sort((f,p)=>f-p),h=i.lampsAlong(e);if(c.length===0&&h.length===0)return()=>n;const l=c.length>0?c[Math.floor((c.length-1)/2)]:0,u=Me.clearOf(h,t.widthM/2,Math.max(-2.5,Math.min(Me.STREET_MIDDLE_MOST_M,l))),d={rungs:a,across:(f,p,m,g)=>Me.betweenWalls(t,u,r(f,p,m,g).leftM,r(f,p,m,g).rightM)};return this.laidStreets.push(d),(f,p,m,g)=>{const v=r(f,p,m,g);return Me.betweenWalls(t,u,v.leftM,v.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+Me.LAMP_CLEARANCE_M);if(n(i))return i;const s=Me.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*s;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=s&&n(a))return a;return i}atKerb(t,e){let i;for(const d of this.laidStreets)for(const f of d.rungs){const p=Math.hypot(t-f.x,e-f.z);p<=Me.KERB_REACH_M&&(!i||p<i.distance)&&(i={rung:f,across:d.across(f.x,f.z,f.dirX,f.dirZ),distance:p})}if(!i)return{x:t,z:e};const{rung:n,across:s}=i,r=(t-n.x)*-n.dirZ+(e-n.z)*n.dirX,a=(t-n.x)*n.dirX+(e-n.z)*n.dirZ,h=(r>=s.carriageway.offsetM?s.left:s.right)??s.left??s.right;if(!h)return{x:t,z:e};const l=Math.sign(h.outerM-h.kerbM),u=h.kerbM+l*Math.min(Me.LAMP_FROM_KERB_M,Math.abs(h.outerM-h.kerbM)/2);return{x:n.x+n.dirX*a-n.dirZ*u,z:n.z+n.dirZ*a+n.dirX*u}}rungsOf(t){const e=this.resample(t);return e.map((i,n)=>{const s=e[Math.max(0,n-1)],r=e[Math.min(e.length-1,n+1)],a=r.x-s.x,c=r.z-s.z,h=Math.hypot(a,c);return h<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/h,dirZ:c/h}})}static surveyedAcross(t){const e=t.widthM/2,i={offsetM:0,halfM:e};return t.widthM<Me.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+Me.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-Me.SIDEWALK_WIDTH_M}}}static betweenWalls(t,e,i,n){const s=t.widthM/2,r={offsetM:e,halfM:s},a=e+s,c=e-s,h=i??a+Me.SIDEWALK_WIDTH_M,l=-(n??-c+Me.SIDEWALK_WIDTH_M);return{carriageway:r,...h-a>=Me.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:h}}:{},...c-l>=Me.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:l}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new Dr(t,e);return t.forEach((a,c)=>{const h=i[c];if(!h)return;const l=(u,d)=>r.onAnotherCarriageway(u,d,c);for(const u of["left","right"]){const d=(f,p,m,g)=>{const v=h(f,p,m,g)[u];return v&&{offsetM:(v.kerbM+v.outerM)/2,halfM:Math.abs(v.outerM-v.kerbM)/2}};this.appendPath(e[c],0,n,s,{lateralAt:d,liftM:Me.LIFT_M+Me.SIDEWALK_KERB_M,minHalfM:0,skip:l}),this.appendKerb(e[c],n,s,(f,p,m,g)=>h(f,p,m,g)[u]?.kerbM,u==="left",l)}}),s}setStated(t,e){Me.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??Me.batchFor(n.surface);i.set(n.surface,s),this.appendPath(n.path.map(r=>({x:r.eastM,z:-r.northM})),n.widthM,e,s)}for(const[n,s]of i){const r=this.meshOf(n,s,!1);r&&this.stated.add(r)}}clear(){Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(t){for(const e of[...t.children]){t.remove(e);const i=e;i.geometry?.dispose(),i.material?.dispose()}}dispose(){Me.empty(this.surveyed),Me.empty(this.stated)}appendPath(t,e,i,n,s={}){const r=this.resample(t);if(r.length<2)return;const a=Math.max(s.minHalfM??.5,e/2),c=s.liftM??Me.LIFT_M,h=s.offsetM??0,l=n.positions.length/3,u=[],d=[],f=[];for(let m=0;m<r.length;m++){const g=r[Math.max(0,m-1)],v=r[Math.min(r.length-1,m+1)];let M=v.x-g.x,w=v.z-g.z;const y=Math.hypot(M,w);y<1e-6?(M=1,w=0):(M/=y,w/=y);const b=s.lateralAt?s.lateralAt(r[m].x,r[m].z,M,w):{offsetM:h,halfM:a},S=b?Math.max(s.minHalfM??.5,b.halfM):a,_=b?.offsetM??h,x=-w*S,A=M*S,I={x:r[m].x+-w*_,z:r[m].z+M*_};u.push(b!==void 0&&b.halfM>0&&!s.skip?.(I.x,I.z)),d.push([{x:I.x+x,z:I.z+A},I,{x:I.x-x,z:I.z-A}]),f.push(S)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const v=d[m][g],M=d[m+1][g],w=i((v.x+M.x)/2,(v.z+M.z)/2)-(p[m][g]+p[m+1][g])/2;w>0&&(p[m][g]+=w,p[m+1][g]+=w)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=l+m*3;n.indices.push(g,g+3,g+1,g+1,g+3,g+4),n.indices.push(g+1,g+4,g+2,g+2,g+4,g+5)}}appendKerb(t,e,i,n,s,r){const a=this.resample(t);if(a.length<2)return;const c=i.positions.length/3,h=[];for(let l=0;l<a.length;l++){const u=a[Math.max(0,l-1)],d=a[Math.min(a.length-1,l+1)];let f=d.x-u.x,p=d.z-u.z;const m=Math.hypot(f,p);m<1e-6?(f=1,p=0):(f/=m,p/=m);const g=n(a[l].x,a[l].z,f,p),v=a[l].x+-p*(g??0),M=a[l].z+f*(g??0);h.push(g!==void 0&&!r(v,M));const w=e(v,M)+Me.LIFT_M;i.positions.push(v,w,M,v,w+Me.SIDEWALK_KERB_M,M)}for(let l=0;l<a.length-1;l++){if(!h[l]||!h[l+1])continue;const u=c+l*2;s?i.indices.push(u,u+1,u+2,u+1,u+3,u+2):i.indices.push(u,u+2,u+1,u+1,u+2,u+3)}}static batchFor(t){return t==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(t,e,i,n,s=!0){if(e.indices.length===0)return;const r=new me;r.setAttribute("position",new fe(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new fe(new Float32Array(e.edges),2)),r.setIndex(new fe(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??Me.ALBEDO[t],h=new er({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?Me.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(h,Me.GRAIN_CONTRAST[t],a);const l=new Mt(r,h);return l.name=`roads ${t}`,l.renderOrder=Me.RENDER_ORDER,l.receiveShadow=!0,l.castShadow=!1,l}addGrain(t,e,i=!1){const n=this.grainOrigin;t.onBeforeCompile=s=>{s.uniforms.uRoadOrigin={value:n},s.uniforms.uRoadContrast={value:e},i&&(s.defines={...s.defines,ROAD_VERGE:""}),s.vertexShader=s.vertexShader.replace("#include <common>",`#include <common>
7542
7542
  varying vec2 vRoadXZ;
7543
7543
  uniform vec2 uRoadOrigin;
7544
7544
  #ifdef ROAD_VERGE
@@ -7701,7 +7701,7 @@ void main() {
7701
7701
  float blur = max(vNearBlur, vHaze);
7702
7702
  gl_FragColor = vec4(color, tex.a * uOpacity * vNearFade * (1.0 - blur * ${oO.toFixed(2)}));
7703
7703
  }
7704
- `;function dO(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}const fO=.14,J2=2.25;let ef;function pO(){if(ef)return ef;const o=128,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createImageData(o,o),n=o/2,s=o*fO,r=o-s;for(let a=0;a<o;a++)for(let c=0;c<o;c++){const h=c+.5-n,l=a+.5<s?a+.5-s:a+.5>r?a+.5-r:0,u=Math.hypot(h,l),d=Math.exp(-(u*u)/(2*J2*J2)),f=(a*o+c)*4;i.data[f]=255,i.data[f+1]=255,i.data[f+2]=255,i.data[f+3]=Math.round(255*Math.min(1,d))}return e.putImageData(i,0,0),ef=new No(t),ef}function mO(o){const t=dO(o.seed),e=new Float32Array(o.count*3),i=new Float32Array(o.count),n=o.radiusM;for(let h=0;h<o.count;h++){const l=t()*Math.PI*2,u=Math.sqrt(t())*o.radiusM;e[h*3]=Math.cos(l)*u,e[h*3+1]=t()*o.heightM,e[h*3+2]=Math.sin(l)*u,i[h]=.85+t()*.3}const s=new me;s.setAttribute("position",new fe(e,3)),s.setAttribute("aSpeed",new fe(i,1)),s.setDrawRange(0,o.visibleCount);const r={uTime:{value:0},uOverallSpeed:{value:o.overallSpeed},uPixelSize:{value:o.pixelSize},uOpacity:{value:o.opacity},uColor:{value:o.color},uUvSquash:{value:1},uSpeedStreak:{value:o.speedStreak},uWindOffset:{value:new it(0,0)},uDropVelocity:{value:new T(0,-1,0)},uAspect:{value:1},uHeight:{value:o.heightM},uBottomY:{value:o.bottomYM},uHalfWidth:{value:n},uTexture:{value:pO()},uNearFocusDistance:{value:o.nearFocusDistanceM},uHazeDistance:{value:o.hazeDistanceM},uHazeColor:{value:o.hazeColor}},a=new Te({uniforms:r,vertexShader:lO,fragmentShader:uO,transparent:!0,depthWrite:!1,depthTest:!0}),c=new bs(s,a);return c.frustumCulled=!1,{points:c,uniforms:r}}class Ac{static S10_MAG_PER_ARCSEC2=10+2.5*Math.log10(3600*3600);static toMagPerArcsec2(t){return Ac.S10_MAG_PER_ARCSEC2-2.5*Math.log10(Math.max(t,1e-12))}static fromMagPerArcsec2(t){return 10**(.4*(Ac.S10_MAG_PER_ARCSEC2-t))}static latitudeOfRowCoord(t){const e=2*t-1;return 90*Math.sign(e)*e*e}static rowCoordOfLatitude(t){return(Math.sign(t)*Math.sqrt(Math.min(Math.abs(t),90)/90)+1)/2}static angleOfColumnCoord(t){return 180*t*t}static columnCoordOfAngle(t){return Math.sqrt(Math.min(Math.max(t,0),180)/180)}}class Ne{static LONGITUDE_STEPS=256;static LATITUDE_STEPS=128;static SUN_RADIUS_KPC=8.2;static SUN_HEIGHT_KPC=.02;static DISK_SCALE_LENGTH_KPC=2.6;static DISK_SCALE_HEIGHT_KPC=.3;static BULGE_SCALE_KPC=.5;static BULGE_FLATTENING=.6;static BULGE_TO_LOCAL_DISK=20;static DUST_SCALE_LENGTH_KPC=3.5;static DUST_SCALE_HEIGHT_KPC=.1;static EXTINCTION_MAG_PER_KPC=.8;static NEAR_LIMIT_KPC=.01;static FAR_LIMIT_KPC=40;static STEPS=192;static OPAQUE_MAG=15;static PEAK_MAG_PER_ARCSEC2=21;static PEAK_RADIANCE=6.278;static PEAK_LONGITUDE_DEG=0;static PEAK_LATITUDE_DEG=4.5;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*Ne.anchor()}static anchor(){return Ac.fromMagPerArcsec2(Ne.PEAK_MAG_PER_ARCSEC2)/Ne.PEAK_RADIANCE}radianceTowards(t,e){return this.trace(t,e).light}extinctionTowards(t,e){return this.trace(t,e).extinctionMag}trace(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=Math.cos(n)*Math.sin(i),a=Math.sin(n);let c=0,h=0,l=0;const u=Math.log(Ne.NEAR_LIMIT_KPC),d=Math.log(Ne.FAR_LIMIT_KPC)-u;for(let f=0;f<Ne.STEPS;f++){const p=Math.exp(u+d*f/(Ne.STEPS-1)),m=p-l;l=p;const g=p-m/2,v=Ne.SUN_RADIUS_KPC+g*s,M=g*r,w=Ne.SUN_HEIGHT_KPC+g*a,y=Math.hypot(v,M),b=Math.exp(-(y-Ne.SUN_RADIUS_KPC)/Ne.DISK_SCALE_LENGTH_KPC-Math.abs(w)/Ne.DISK_SCALE_HEIGHT_KPC),S=Math.hypot(y,w/Ne.BULGE_FLATTENING),_=Ne.BULGE_TO_LOCAL_DISK*Math.exp(-S/Ne.BULGE_SCALE_KPC);if(c+=(b+_)*m*10**(-.4*h),h+=Ne.EXTINCTION_MAG_PER_KPC*Math.exp(-(y-Ne.SUN_RADIUS_KPC)/Ne.DUST_SCALE_LENGTH_KPC-(Math.abs(w)-Ne.SUN_HEIGHT_KPC)/Ne.DUST_SCALE_HEIGHT_KPC)*m,h>Ne.OPAQUE_MAG)break}return{light:c,extinctionMag:h}}values=new Float32Array(Ne.LONGITUDE_STEPS*Ne.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Ne.LATITUDE_STEPS}walk(t){const e=Ne.LONGITUDE_STEPS,i=Math.min(Ne.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Ac.latitudeOfRowCoord((this.walked+.5)/Ne.LATITUDE_STEPS);for(let s=0;s<e;s++)this.values[this.walked*e+s]=this.radianceTowards(360*(s+.5)/e,n)}}harvest(){let t=Number.POSITIVE_INFINITY;for(const n of this.values)n<t&&(t=n);const e=Ne.anchor(),i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-t)*e;return{width:Ne.LONGITUDE_STEPS,height:Ne.LATITUDE_STEPS,data:i}}}class Ni{static LONGITUDE_STEPS=128;static LATITUDE_STEPS=96;static RADIAL_FALLOFF=1.3;static FAN_EXPONENT=2.6;static SUBLIMATION_AU=.1;static NEAR_LIMIT_AU=.004;static FAR_LIMIT_AU=8;static STEPS=224;static LOBE_ASYMMETRY=[.7,-.2,-.81];static LOBE_WEIGHT=[.665,.33,.00541];static RIGHT_ANGLE_S10=200;static POLE_S10=77;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*this.anchor()}anchored;anchor(){return this.anchored===void 0&&(this.anchored=Ni.RIGHT_ANGLE_S10/this.radianceTowards(90,0)),this.anchored}radianceTowards(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=-Math.cos(n)*Math.sin(i),a=Math.sin(n),c=-s;let h=0,l=0;const u=Math.log(Ni.NEAR_LIMIT_AU),d=Math.log(Ni.FAR_LIMIT_AU)-u;for(let f=0;f<Ni.STEPS;f++){const p=Math.exp(u+d*f/(Ni.STEPS-1)),m=p-l;l=p;const g=p-m/2,v=1+g*s,M=g*r,w=g*a,y=Math.hypot(v,M,w);if(y<Ni.SUBLIMATION_AU)continue;const b=w/y,S=y**-1.3*Math.exp(-2.6*Math.abs(b)),_=(c-g)/y;h+=S*this.scattering(_)*m/(y*y)}return h}scattering(t){let e=0;for(let i=0;i<Ni.LOBE_ASYMMETRY.length;i++){const n=Ni.LOBE_ASYMMETRY[i],s=1+n*n-2*n*t;e+=Ni.LOBE_WEIGHT[i]*(1-n*n)/(4*Math.PI*s**1.5)}return e}values=new Float32Array(Ni.LONGITUDE_STEPS*Ni.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Ni.LATITUDE_STEPS}walk(t){const e=Ni.LONGITUDE_STEPS,i=Math.min(Ni.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Ac.latitudeOfRowCoord((this.walked+.5)/Ni.LATITUDE_STEPS);for(let s=0;s<e;s++){const r=Ac.angleOfColumnCoord((s+.5)/e);this.values[this.walked*e+s]=this.radianceTowards(r,n)}}}harvest(){const t=this.anchor();let e=Number.POSITIVE_INFINITY;for(const n of this.values)n<e&&(e=n);const i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-e)*t;return{width:Ni.LONGITUDE_STEPS,height:Ni.LATITUDE_STEPS,data:i}}}class At{static get NANOLAMBERTS_PER_S10(){return At.toNanolamberts(10+2.5*Math.log10(3600*3600))}static nanolambertsOfS10(t){return t*At.NANOLAMBERTS_PER_S10}static TWILIGHT=[{sunAltitudeDeg:90,magPerArcsec2:3.5},{sunAltitudeDeg:10,magPerArcsec2:4.2},{sunAltitudeDeg:0,magPerArcsec2:7.5},...Array.from({length:15},(t,e)=>{const i=-4-e;return{sunAltitudeDeg:i,magPerArcsec2:At.patatV(i)}}),{sunAltitudeDeg:-24,magPerArcsec2:22}];static patatV(t){const e=90-t-95;return 11.84+1.518*e-.057*e*e}static moonlessMagPerArcsec2(t){const e=At.TWILIGHT;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t<=n.sunAltitudeDeg&&t>=s.sunAltitudeDeg){const r=(n.sunAltitudeDeg-t)/(n.sunAltitudeDeg-s.sunAltitudeDeg);return n.magPerArcsec2+(s.magPerArcsec2-n.magPerArcsec2)*r}}return t>0?e[0].magPerArcsec2:e[e.length-1].magPerArcsec2}static toNanolamberts(t){return 34.08*Math.exp(At.NANOLAMBERT_OFFSET-At.PER_MAGNITUDE*t)}static fromNanolamberts(t){return(At.NANOLAMBERT_OFFSET-Math.log(Math.max(t,1e-6)/34.08))/At.PER_MAGNITUDE}static NANOLAMBERT_OFFSET=20.7233;static PER_MAGNITUDE=Math.LN10/2.5;static airMass(t){const e=Math.cos(Math.max(t,0)*Math.PI/180);return 1/Math.sqrt(Math.max(1-.96*e*e,.001))}static EXTINCTION_PER_AIR_MASS=.172;static scatteringAt(t){const e=Math.min(Math.max(t,0),180)*Math.PI/180;return 10**5.36*(1.06+Math.cos(e)**2)+10**(6.15-Math.min(t,180)/40)}static scatteredFraction(t){return 1-10**(-.4*At.EXTINCTION_PER_AIR_MASS*At.airMass(t))}static AIRGLOW_MAG_PER_ARCSEC2=22;static twilightExcessNanolamberts(t){return Math.max(0,At.toNanolamberts(At.moonlessMagPerArcsec2(t))-At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2))}static twilightOutput(t){const e=At.scatteringAt(90-t)*At.scatteredFraction(90);return At.twilightExcessNanolamberts(t)/e}static moonNanolamberts(t,e,i,n){return At.scatteringAt(i)*At.moonOutput(t,e)*At.scatteredFraction(n)}static moonOutput(t,e){if(e<=0)return 0;const i=Math.min(Math.abs(t),180);return 10**(-.4*(3.84+.026*i+4e-9*i**4))*10**(-.4*At.EXTINCTION_PER_AIR_MASS*At.airMass(e))}static phaseAngleOf(t){return Math.acos(Math.min(Math.max(2*t-1,-1),1))*180/Math.PI}static magPerArcsec2(t,e,i,n){const s=At.scatteredFraction(i),r=At.scatteringAt(t.separationDeg)*At.twilightOutput(t.altitudeDeg)*s,a=At.scatteringAt(e.separationDeg)*At.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*s;return At.fromNanolamberts(At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2)+r+a+At.artificialNanolamberts(n,i))}static artificialZenithNanolamberts(t){return t===void 0||!Number.isFinite(t)?0:Math.max(0,At.toNanolamberts(t)-At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2))}static artificialNanolamberts(t,e){const i=At.artificialZenithNanolamberts(t);return i>0?i*At.artificialShape(e):0}static artificialShape(t){return At.scatteredFraction(t)/At.scatteredFraction(90)}static nakedEyeLimit(t){return 7.93-5*Math.log10(10**(4.316-t/5)+1)}static starLossMagnitudes(t,e,i){const n=At.moonlessMagPerArcsec2(t),s=At.fromNanolamberts(At.toNanolamberts(n)+At.scatteringAt(90-e.altitudeDeg)*At.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*At.scatteredFraction(90)+At.artificialZenithNanolamberts(i));return Math.max(0,At.nakedEyeLimit(n)-At.nakedEyeLimit(s))}}class m0{static HALF_FLOAT_MAX=65504;static fromMap(t,e){const i=Tn.toHalfFloat(1);for(let n=0;n<t.data.length;n++)e[n*4]=Tn.toHalfFloat(Math.min(m0.HALF_FLOAT_MAX,At.nanolambertsOfS10(t.data[n]))),e[n*4+3]=i}}class uo{static pool=typeof Worker>"u"?null:void 0;static with(t,e){const i=uo.pool;if(i===null){e();return}if(i){t(i);return}De(async()=>{const{OffThreadTracer:n}=await import("./OffThreadTracer-ByPLWaYU.js");return{OffThreadTracer:n}},[],import.meta.url).then(({OffThreadTracer:n})=>{uo.pool=n.get(),uo.pool?t(uo.pool):e()},()=>{uo.pool=null,e()})}}class so{static RADIUS=890;static TOO_BRIGHT_MAG_PER_ARCSEC2=16;static MILKY_WAY_TINT=[.9,.94,1];static ZODIACAL_TINT=[1,.97,.9];object;material;maps=au.shared;milkyWayTexture;zodiacalTexture;milkyWayTexels;zodiacalTexels;repaint;constructor(){this.milkyWayTexels=this.maps.milkyWayTexels,this.milkyWayTexture=so.buildTexture(this.milkyWayTexels,Ne.LONGITUDE_STEPS,Ne.LATITUDE_STEPS,Do),this.zodiacalTexels=this.maps.zodiacalTexels,this.zodiacalTexture=so.buildTexture(this.zodiacalTexels,Ni.LONGITUDE_STEPS,Ni.LATITUDE_STEPS,Xi),this.material=new Te({uniforms:{uMilkyWay:{value:this.milkyWayTexture},uZodiacal:{value:this.zodiacalTexture},uGalactic:{value:new le},uEclipticPole:{value:new T(0,1,0)},uSunLongitude:{value:new T(1,0,0)},uMoonDirection:{value:new T(0,-1,0)},uMoonOutput:{value:0},uSunDirection:{value:new T(0,-1,0)},uTwilightOutput:{value:0},uAirglowNanolamberts:{value:At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2)},uArtificialNanolamberts:{value:0},uSkyColor:{value:new T(0,0,0)},uMilkyWayTint:{value:new T(...so.MILKY_WAY_TINT)},uZodiacalTint:{value:new T(...so.ZODIACAL_TINT)},uReady:{value:0},uEncodeDestination:{value:1}},vertexShader:`
7704
+ `;function dO(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}const fO=.14,J2=2.25;let ef;function pO(){if(ef)return ef;const o=128,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createImageData(o,o),n=o/2,s=o*fO,r=o-s;for(let a=0;a<o;a++)for(let c=0;c<o;c++){const h=c+.5-n,l=a+.5<s?a+.5-s:a+.5>r?a+.5-r:0,u=Math.hypot(h,l),d=Math.exp(-(u*u)/(2*J2*J2)),f=(a*o+c)*4;i.data[f]=255,i.data[f+1]=255,i.data[f+2]=255,i.data[f+3]=Math.round(255*Math.min(1,d))}return e.putImageData(i,0,0),ef=new No(t),ef}function mO(o){const t=dO(o.seed),e=new Float32Array(o.count*3),i=new Float32Array(o.count),n=o.radiusM;for(let h=0;h<o.count;h++){const l=t()*Math.PI*2,u=Math.sqrt(t())*o.radiusM;e[h*3]=Math.cos(l)*u,e[h*3+1]=t()*o.heightM,e[h*3+2]=Math.sin(l)*u,i[h]=.85+t()*.3}const s=new me;s.setAttribute("position",new fe(e,3)),s.setAttribute("aSpeed",new fe(i,1)),s.setDrawRange(0,o.visibleCount);const r={uTime:{value:0},uOverallSpeed:{value:o.overallSpeed},uPixelSize:{value:o.pixelSize},uOpacity:{value:o.opacity},uColor:{value:o.color},uUvSquash:{value:1},uSpeedStreak:{value:o.speedStreak},uWindOffset:{value:new it(0,0)},uDropVelocity:{value:new T(0,-1,0)},uAspect:{value:1},uHeight:{value:o.heightM},uBottomY:{value:o.bottomYM},uHalfWidth:{value:n},uTexture:{value:pO()},uNearFocusDistance:{value:o.nearFocusDistanceM},uHazeDistance:{value:o.hazeDistanceM},uHazeColor:{value:o.hazeColor}},a=new Te({uniforms:r,vertexShader:lO,fragmentShader:uO,transparent:!0,depthWrite:!1,depthTest:!0}),c=new bs(s,a);return c.frustumCulled=!1,{points:c,uniforms:r}}class Ac{static S10_MAG_PER_ARCSEC2=10+2.5*Math.log10(3600*3600);static toMagPerArcsec2(t){return Ac.S10_MAG_PER_ARCSEC2-2.5*Math.log10(Math.max(t,1e-12))}static fromMagPerArcsec2(t){return 10**(.4*(Ac.S10_MAG_PER_ARCSEC2-t))}static latitudeOfRowCoord(t){const e=2*t-1;return 90*Math.sign(e)*e*e}static rowCoordOfLatitude(t){return(Math.sign(t)*Math.sqrt(Math.min(Math.abs(t),90)/90)+1)/2}static angleOfColumnCoord(t){return 180*t*t}static columnCoordOfAngle(t){return Math.sqrt(Math.min(Math.max(t,0),180)/180)}}class Ne{static LONGITUDE_STEPS=256;static LATITUDE_STEPS=128;static SUN_RADIUS_KPC=8.2;static SUN_HEIGHT_KPC=.02;static DISK_SCALE_LENGTH_KPC=2.6;static DISK_SCALE_HEIGHT_KPC=.3;static BULGE_SCALE_KPC=.5;static BULGE_FLATTENING=.6;static BULGE_TO_LOCAL_DISK=20;static DUST_SCALE_LENGTH_KPC=3.5;static DUST_SCALE_HEIGHT_KPC=.1;static EXTINCTION_MAG_PER_KPC=.8;static NEAR_LIMIT_KPC=.01;static FAR_LIMIT_KPC=40;static STEPS=192;static OPAQUE_MAG=15;static PEAK_MAG_PER_ARCSEC2=21;static PEAK_RADIANCE=6.278;static PEAK_LONGITUDE_DEG=0;static PEAK_LATITUDE_DEG=4.5;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*Ne.anchor()}static anchor(){return Ac.fromMagPerArcsec2(Ne.PEAK_MAG_PER_ARCSEC2)/Ne.PEAK_RADIANCE}radianceTowards(t,e){return this.trace(t,e).light}extinctionTowards(t,e){return this.trace(t,e).extinctionMag}trace(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=Math.cos(n)*Math.sin(i),a=Math.sin(n);let c=0,h=0,l=0;const u=Math.log(Ne.NEAR_LIMIT_KPC),d=Math.log(Ne.FAR_LIMIT_KPC)-u;for(let f=0;f<Ne.STEPS;f++){const p=Math.exp(u+d*f/(Ne.STEPS-1)),m=p-l;l=p;const g=p-m/2,v=Ne.SUN_RADIUS_KPC+g*s,M=g*r,w=Ne.SUN_HEIGHT_KPC+g*a,y=Math.hypot(v,M),b=Math.exp(-(y-Ne.SUN_RADIUS_KPC)/Ne.DISK_SCALE_LENGTH_KPC-Math.abs(w)/Ne.DISK_SCALE_HEIGHT_KPC),S=Math.hypot(y,w/Ne.BULGE_FLATTENING),_=Ne.BULGE_TO_LOCAL_DISK*Math.exp(-S/Ne.BULGE_SCALE_KPC);if(c+=(b+_)*m*10**(-.4*h),h+=Ne.EXTINCTION_MAG_PER_KPC*Math.exp(-(y-Ne.SUN_RADIUS_KPC)/Ne.DUST_SCALE_LENGTH_KPC-(Math.abs(w)-Ne.SUN_HEIGHT_KPC)/Ne.DUST_SCALE_HEIGHT_KPC)*m,h>Ne.OPAQUE_MAG)break}return{light:c,extinctionMag:h}}values=new Float32Array(Ne.LONGITUDE_STEPS*Ne.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Ne.LATITUDE_STEPS}walk(t){const e=Ne.LONGITUDE_STEPS,i=Math.min(Ne.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Ac.latitudeOfRowCoord((this.walked+.5)/Ne.LATITUDE_STEPS);for(let s=0;s<e;s++)this.values[this.walked*e+s]=this.radianceTowards(360*(s+.5)/e,n)}}harvest(){let t=Number.POSITIVE_INFINITY;for(const n of this.values)n<t&&(t=n);const e=Ne.anchor(),i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-t)*e;return{width:Ne.LONGITUDE_STEPS,height:Ne.LATITUDE_STEPS,data:i}}}class Ni{static LONGITUDE_STEPS=128;static LATITUDE_STEPS=96;static RADIAL_FALLOFF=1.3;static FAN_EXPONENT=2.6;static SUBLIMATION_AU=.1;static NEAR_LIMIT_AU=.004;static FAR_LIMIT_AU=8;static STEPS=224;static LOBE_ASYMMETRY=[.7,-.2,-.81];static LOBE_WEIGHT=[.665,.33,.00541];static RIGHT_ANGLE_S10=200;static POLE_S10=77;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*this.anchor()}anchored;anchor(){return this.anchored===void 0&&(this.anchored=Ni.RIGHT_ANGLE_S10/this.radianceTowards(90,0)),this.anchored}radianceTowards(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=-Math.cos(n)*Math.sin(i),a=Math.sin(n),c=-s;let h=0,l=0;const u=Math.log(Ni.NEAR_LIMIT_AU),d=Math.log(Ni.FAR_LIMIT_AU)-u;for(let f=0;f<Ni.STEPS;f++){const p=Math.exp(u+d*f/(Ni.STEPS-1)),m=p-l;l=p;const g=p-m/2,v=1+g*s,M=g*r,w=g*a,y=Math.hypot(v,M,w);if(y<Ni.SUBLIMATION_AU)continue;const b=w/y,S=y**-1.3*Math.exp(-2.6*Math.abs(b)),_=(c-g)/y;h+=S*this.scattering(_)*m/(y*y)}return h}scattering(t){let e=0;for(let i=0;i<Ni.LOBE_ASYMMETRY.length;i++){const n=Ni.LOBE_ASYMMETRY[i],s=1+n*n-2*n*t;e+=Ni.LOBE_WEIGHT[i]*(1-n*n)/(4*Math.PI*s**1.5)}return e}values=new Float32Array(Ni.LONGITUDE_STEPS*Ni.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Ni.LATITUDE_STEPS}walk(t){const e=Ni.LONGITUDE_STEPS,i=Math.min(Ni.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Ac.latitudeOfRowCoord((this.walked+.5)/Ni.LATITUDE_STEPS);for(let s=0;s<e;s++){const r=Ac.angleOfColumnCoord((s+.5)/e);this.values[this.walked*e+s]=this.radianceTowards(r,n)}}}harvest(){const t=this.anchor();let e=Number.POSITIVE_INFINITY;for(const n of this.values)n<e&&(e=n);const i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-e)*t;return{width:Ni.LONGITUDE_STEPS,height:Ni.LATITUDE_STEPS,data:i}}}class At{static get NANOLAMBERTS_PER_S10(){return At.toNanolamberts(10+2.5*Math.log10(3600*3600))}static nanolambertsOfS10(t){return t*At.NANOLAMBERTS_PER_S10}static TWILIGHT=[{sunAltitudeDeg:90,magPerArcsec2:3.5},{sunAltitudeDeg:10,magPerArcsec2:4.2},{sunAltitudeDeg:0,magPerArcsec2:7.5},...Array.from({length:15},(t,e)=>{const i=-4-e;return{sunAltitudeDeg:i,magPerArcsec2:At.patatV(i)}}),{sunAltitudeDeg:-24,magPerArcsec2:22}];static patatV(t){const e=90-t-95;return 11.84+1.518*e-.057*e*e}static moonlessMagPerArcsec2(t){const e=At.TWILIGHT;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t<=n.sunAltitudeDeg&&t>=s.sunAltitudeDeg){const r=(n.sunAltitudeDeg-t)/(n.sunAltitudeDeg-s.sunAltitudeDeg);return n.magPerArcsec2+(s.magPerArcsec2-n.magPerArcsec2)*r}}return t>0?e[0].magPerArcsec2:e[e.length-1].magPerArcsec2}static toNanolamberts(t){return 34.08*Math.exp(At.NANOLAMBERT_OFFSET-At.PER_MAGNITUDE*t)}static fromNanolamberts(t){return(At.NANOLAMBERT_OFFSET-Math.log(Math.max(t,1e-6)/34.08))/At.PER_MAGNITUDE}static NANOLAMBERT_OFFSET=20.7233;static PER_MAGNITUDE=Math.LN10/2.5;static airMass(t){const e=Math.cos(Math.max(t,0)*Math.PI/180);return 1/Math.sqrt(Math.max(1-.96*e*e,.001))}static EXTINCTION_PER_AIR_MASS=.172;static scatteringAt(t){const e=Math.min(Math.max(t,0),180)*Math.PI/180;return 10**5.36*(1.06+Math.cos(e)**2)+10**(6.15-Math.min(t,180)/40)}static scatteredFraction(t){return 1-10**(-.4*At.EXTINCTION_PER_AIR_MASS*At.airMass(t))}static AIRGLOW_MAG_PER_ARCSEC2=22;static twilightExcessNanolamberts(t){return Math.max(0,At.toNanolamberts(At.moonlessMagPerArcsec2(t))-At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2))}static twilightOutput(t){const e=At.scatteringAt(90-t)*At.scatteredFraction(90);return At.twilightExcessNanolamberts(t)/e}static moonNanolamberts(t,e,i,n){return At.scatteringAt(i)*At.moonOutput(t,e)*At.scatteredFraction(n)}static moonOutput(t,e){if(e<=0)return 0;const i=Math.min(Math.abs(t),180);return 10**(-.4*(3.84+.026*i+4e-9*i**4))*10**(-.4*At.EXTINCTION_PER_AIR_MASS*At.airMass(e))}static phaseAngleOf(t){return Math.acos(Math.min(Math.max(2*t-1,-1),1))*180/Math.PI}static magPerArcsec2(t,e,i,n){const s=At.scatteredFraction(i),r=At.scatteringAt(t.separationDeg)*At.twilightOutput(t.altitudeDeg)*s,a=At.scatteringAt(e.separationDeg)*At.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*s;return At.fromNanolamberts(At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2)+r+a+At.artificialNanolamberts(n,i))}static artificialZenithNanolamberts(t){return t===void 0||!Number.isFinite(t)?0:Math.max(0,At.toNanolamberts(t)-At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2))}static artificialNanolamberts(t,e){const i=At.artificialZenithNanolamberts(t);return i>0?i*At.artificialShape(e):0}static artificialShape(t){return At.scatteredFraction(t)/At.scatteredFraction(90)}static nakedEyeLimit(t){return 7.93-5*Math.log10(10**(4.316-t/5)+1)}static starLossMagnitudes(t,e,i){const n=At.moonlessMagPerArcsec2(t),s=At.fromNanolamberts(At.toNanolamberts(n)+At.scatteringAt(90-e.altitudeDeg)*At.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*At.scatteredFraction(90)+At.artificialZenithNanolamberts(i));return Math.max(0,At.nakedEyeLimit(n)-At.nakedEyeLimit(s))}}class m0{static HALF_FLOAT_MAX=65504;static fromMap(t,e){const i=Tn.toHalfFloat(1);for(let n=0;n<t.data.length;n++)e[n*4]=Tn.toHalfFloat(Math.min(m0.HALF_FLOAT_MAX,At.nanolambertsOfS10(t.data[n]))),e[n*4+3]=i}}class uo{static pool=typeof Worker>"u"?null:void 0;static with(t,e){const i=uo.pool;if(i===null){e();return}if(i){t(i);return}Ie(async()=>{const{OffThreadTracer:n}=await import("./OffThreadTracer-ByPLWaYU.js");return{OffThreadTracer:n}},[],import.meta.url).then(({OffThreadTracer:n})=>{uo.pool=n.get(),uo.pool?t(uo.pool):e()},()=>{uo.pool=null,e()})}}class so{static RADIUS=890;static TOO_BRIGHT_MAG_PER_ARCSEC2=16;static MILKY_WAY_TINT=[.9,.94,1];static ZODIACAL_TINT=[1,.97,.9];object;material;maps=au.shared;milkyWayTexture;zodiacalTexture;milkyWayTexels;zodiacalTexels;repaint;constructor(){this.milkyWayTexels=this.maps.milkyWayTexels,this.milkyWayTexture=so.buildTexture(this.milkyWayTexels,Ne.LONGITUDE_STEPS,Ne.LATITUDE_STEPS,Do),this.zodiacalTexels=this.maps.zodiacalTexels,this.zodiacalTexture=so.buildTexture(this.zodiacalTexels,Ni.LONGITUDE_STEPS,Ni.LATITUDE_STEPS,Xi),this.material=new Te({uniforms:{uMilkyWay:{value:this.milkyWayTexture},uZodiacal:{value:this.zodiacalTexture},uGalactic:{value:new le},uEclipticPole:{value:new T(0,1,0)},uSunLongitude:{value:new T(1,0,0)},uMoonDirection:{value:new T(0,-1,0)},uMoonOutput:{value:0},uSunDirection:{value:new T(0,-1,0)},uTwilightOutput:{value:0},uAirglowNanolamberts:{value:At.toNanolamberts(At.AIRGLOW_MAG_PER_ARCSEC2)},uArtificialNanolamberts:{value:0},uSkyColor:{value:new T(0,0,0)},uMilkyWayTint:{value:new T(...so.MILKY_WAY_TINT)},uZodiacalTint:{value:new T(...so.ZODIACAL_TINT)},uReady:{value:0},uEncodeDestination:{value:1}},vertexShader:`
7705
7705
  varying vec3 vDirection;
7706
7706
  void main() {
7707
7707
  vDirection = normalize((modelMatrix * vec4(position, 1.0)).xyz - cameraPosition);
@@ -8544,7 +8544,7 @@ ${h.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
8544
8544
  gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
8545
8545
  }
8546
8546
  `,transparent:!0,depthWrite:!1,side:_n,fog:!1,blending:Mc,blendSrc:yc,blendDst:Hu})}static wallReflectance(t,e,i){const n=i(t,1,e);return 2*n/(1+n)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return Lt.respond(e*Lt.relativeOfResponse(Math.max(t,1e-5)))}}class ms{static SIZE=64;static MOVE_M=.01;holder=new Di;cameras=[];faces=[];target=new Ke(ms.SIZE,ms.SIZE);white=new ls({color:new rt(1,1,1),side:_n});scene=new Hs;cabin;meshes=0;eye=new T;scratch=new T;constructor(){const t=[[new T(1,0,0),new T(0,1,0)],[new T(-1,0,0),new T(0,1,0)],[new T(0,1,0),new T(0,0,1)],[new T(0,-1,0),new T(0,0,-1)],[new T(0,0,1),new T(0,1,0)],[new T(0,0,-1),new T(0,1,0)]];for(const[e,i]of t){const n=new Nn(90,1,.02,20);n.up.copy(i),n.lookAt(e),this.holder.add(n),this.cameras.push(n),this.faces.push(new Uint8Array(ms.SIZE*ms.SIZE*4))}this.scene.background=new rt(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,i){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const n=this.scratch.copy(i);e.worldToLocal(n);let s=0;e.traverse(r=>{r.isMesh&&s++}),!(e===this.cabin&&s===this.meshes&&n.distanceTo(this.eye)<ms.MOVE_M)&&(this.cabin=e,this.meshes=s,this.eye.copy(n),this.draw(t,e))}hides(t){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let e=0;e<6;e++){const i=this.cameras[e],n=this.scratch.copy(t).transformDirection(i.matrixWorldInverse);if(n.z>=0)continue;const s=n.x/-n.z,r=n.y/-n.z;if(Math.abs(s)>1||Math.abs(r)>1)continue;const a=Math.min(ms.SIZE-1,Math.floor((s+1)/2*ms.SIZE)),c=Math.min(ms.SIZE-1,Math.floor((r+1)/2*ms.SIZE));return this.faces[e][(c*ms.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(t,e){e.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];e.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(l=>l instanceof Oa))return;const h=new Mt(a.geometry,this.white);h.matrixAutoUpdate=!1,h.matrix.copy(a.matrixWorld),h.matrixWorld.copy(a.matrixWorld),i.push(h)});for(const r of i)this.scene.add(r);const n=t.getRenderTarget(),s=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,a),t.readRenderTargetPixels(this.target,0,0,ms.SIZE,ms.SIZE,this.faces[r])}t.setRenderTarget(n),t.shadowMap.autoUpdate=s;for(const r of i)r.removeFromParent()}}const mm="https://ufoathome.org/models/index.json";class hu{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??ZO()}async entries(t){const e=await this.load();return t?e.filter(i=>[i.kind].flat().includes(t)):e}async entry(t){return(await this.load()).find(e=>e.id===t)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const t=this.indexUrls.join(`
8547
- `);let e=hu.shared.get(t);return e||(e=this.fetchFirstAvailable(),hu.shared.set(t,e),e.then(i=>{i.length===0&&hu.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function ZO(){const o=`?v=${encodeURIComponent("0.161.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==mm?[t,mm]:[mm]).map(e=>e+o)}const JO=[{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 hu}];async function gm(o){const{GLTFLoader:t}=await De(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-CWl8CQPI.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const bS=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Fs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new Mt(new Jn(2,2),new Te({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:Fs.VERTEX,fragmentShader:Fs.FRAGMENT,transparent:!0,depthWrite:!1,blending:Mn,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,n){const s=Math.max(t,n*Fs.MIN_ANGLE_RAD),r=Fs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Fs.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(Fs.MAX_SHARE*Fs.FILL*Math.PI))}static VERTEX=`
8547
+ `);let e=hu.shared.get(t);return e||(e=this.fetchFirstAvailable(),hu.shared.set(t,e),e.then(i=>{i.length===0&&hu.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function ZO(){const o=`?v=${encodeURIComponent("0.162.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==mm?[t,mm]:[mm]).map(e=>e+o)}const JO=[{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 hu}];async function gm(o){const{GLTFLoader:t}=await Ie(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-B_T3zy3i.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const bS=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Fs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new Mt(new Jn(2,2),new Te({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:Fs.VERTEX,fragmentShader:Fs.FRAGMENT,transparent:!0,depthWrite:!1,blending:Mn,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,n){const s=Math.max(t,n*Fs.MIN_ANGLE_RAD),r=Fs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Fs.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(Fs.MAX_SHARE*Fs.FILL*Math.PI))}static VERTEX=`
8548
8548
  uniform float uRadius;
8549
8549
  varying vec2 vOffset;
8550
8550
  void main() {
@@ -9153,7 +9153,7 @@ void main() {`).replace("#include <opaque_fragment>",`
9153
9153
  vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
9154
9154
  gl_FragColor = vec4(light, 1.0);
9155
9155
  }
9156
- `,transparent:!0,blending:Mn,depthWrite:!1,side:Pi,fog:!1});this.object=new Mt(new nn(yv.RADIUS,128,32,0,Math.PI*2,0,Ue.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 i=0;i<Ue.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Tn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=Tn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class v0{constructor(t){this.generator=t}static SIZE=128;target=new qu(v0.SIZE,{type:Xe,generateMipmaps:!0,minFilter:Bs,magFilter:ye});camera=new sv(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,n=[]){const s=t.shadowMap.autoUpdate;let r=!1;e.traverse(c=>{const h=c;h.isLight&&h.castShadow&&h.shadow&&!h.shadow.map&&(r=!0)}),t.shadowMap.autoUpdate=r?s:!1;const a=n.map(c=>c.visible);for(const c of n)c.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),n.forEach((c,h)=>{c.visible=a[h]}),t.shadowMap.autoUpdate=s,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class Xn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Xn.install(),this.generator=new Hg(t),this.eye=new v0(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],h,l=Xn.REFRESH_MS){for(const g of[...this.probes.keys()])n.some(v=>v.id===g&&v.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const u=[{probe:this.eye}];for(const g of n){if(!g.shiny)continue;let v=this.probes.get(g.id);v||(v=new v0(this.generator),this.probes.set(g.id,v)),u.push({probe:v,reflector:g})}const d=performance.now(),f=()=>u.filter(({probe:g})=>g.capturedVersion!==a),p=f().filter(({probe:g})=>d-g.capturedAtMs>=l);if(p.length>0){const g=p.reduce((v,M)=>M.probe.capturedAtMs<v.probe.capturedAtMs?M:v);if(g.reflector){const v=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,v,[g.reflector.holder,...s]),Xn.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),h?.(g.probe.sharp),Xn.decor=g.probe.filtered;for(const v of r)Xn.reflectOn(v,g.probe);for(const v of n)v.shiny||Xn.reflectOn(v.holder,g.probe)}g.probe.capturedVersion=a}const m=f();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:g})=>l-(d-g.capturedAtMs))))}scratch=new T;static reflectOn(t,e={filtered:Xn.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Oa?e.sharp&&s.setSurroundings(e.sharp):s instanceof lo&&e.filtered&&s.envMap!==e.filtered&&(s.envMap=e.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(Xn.installed)return;Xn.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!he.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}he.lights_fragment_maps=he.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function tP(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.rareIceCrystals===t.rareIceCrystals&&o.lowerCloudCover===t.lowerCloudCover&&o.relativeHumidity===t.relativeHumidity&&o.precipitationType===t.precipitationType&&o.precipitationIntensity===t.precipitationIntensity&&o.precipitationAmount===t.precipitationAmount&&o.windDirectionDeg===t.windDirectionDeg&&o.windSpeed===t.windSpeed&&o.storm===t.storm}const sf=900,vm=1,mw=4,Mm=5,rf=.5,af=Li.GROUND_RADIUS_M;function gw(o){return Li.groundRadiusFor(o)}const ym=.5,wm=850,of=.03,eP=.015,Qn=850,nh=300,ma=120,iP=700,bm=.03,nP=3.5,cf=20,xm=.04,sP=.26,vw=4,Sm=1.5,Mw=-1,rP=.01,Nf=-4,aP=2,oP=20,hf=2600,cP=.97,hP=.38,Ul=Nf,lP=8,uP=2,yw=1500,dP=.7,fP=.3,pP=.32,mP=.65,ww=2.4,gP=.9,vP=400,MP=[0,45,90,135,180,225,270,315],yP=2,wP=16,bw=4e3,xw=880,lf=40,Sw=60,bP=10,xP=1,SP=Li.REBUILD_DISTANCE_M,Ew=.265,Aw=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*Ew,Math.sin(e)*Ew]})],Em=700,Am=250/b1,EP=12,_w=5,_m=6,Go=[.92,.92,.95],Tm=[.15,.15,.19],Rm={snow:{fallSpeedMPerS:2,size:.3,color:new rt(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new rt(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},oh=0,Im=0,AP=150,Dm=3e3,Fl=20,_P=15,Tw=oh,TP=40,Rw=1,RP=9;function Cm(o){return Rw+(RP-Rw)*o}const Iw=new rt(.75,.82,.92),IP=10,DP=.5;function Dw(o){return Cr(o/IP,DP,1)}const Vo=200,Cw=.18,Ow=.32,CP=.35,Pw=new rt(.85,.9,.98),Nw=5,Lw=.85,kw=.01;function OP(o,t,e=1){return Math.round(o*(kw+(1-kw)*t)*e)}function PP(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.lowerCloudCover===t.lowerCloudCover}const Uw=230,Fw=.7,zw=.05,NP=.6,LP=.7,kP=.15,Bw=.35,UP=3,FP=1/12,zP=.5,Tr=new rt(.82,.86,1),BP=2500,HP=1.6,Om=15,GP={Venus:new rt(1,.96,.85),Mars:new rt(1,.55,.4),Jupiter:new rt(.95,.87,.72),Saturn:new rt(.92,.86,.68)};class lt{renderer;scene=new Hs;phenomena=new lr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Be;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 i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=e===void 0?void 0:setTimeout(n,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(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+bw,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),bw+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new it;decorModelProvider=JO[0].create();decorModelToken=0;decorModelCredits=new Map;emitterLights=new es(this.scene,()=>this.relativeScale,{halfExtentM:ma,depthHalfRangeM:nh,biasM:bm,normalBiasM:xm,mapSize:1024});bodySystem=new se(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??lt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*lt.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new s0(16777215,0);celestialLightTarget=new Di;skyLight=new $T(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new If;weather=A0;observerElevationM=0;siteElevationM=0;air=new Zs;groundRadius=af;terrainRadius=af;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new T;cloudFieldOffset=new T;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new T;rainLastVerticalFacing=-1;rainViewportSize=new it;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new s0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new T;sunVisible=!1;lensFlareScratch=new T;sunOcclusionRaycaster=new If;sunOcclusionDirectionScratch=new T;sunOcclusionRightScratch=new T;sunOcclusionUpScratch=new T;ufoOcclusionRaycaster=new If;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=Si.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;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new Ju;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Pb()){su.install(),this.renderer=new oC({canvas:t,antialias:!0}),this.resolution=new Je(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Zl,this.camera=new Nn(60,t.width/Math.max(t.height,1),.1,sf*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=-ma,this.celestialLight.shadow.camera.right=ma,this.celestialLight.shadow.camera.top=ma,this.celestialLight.shadow.camera.bottom=-ma,this.celestialLight.shadow.camera.near=Qn-nh,this.celestialLight.shadow.camera.far=Qn+nh,this.celestialLight.shadow.bias=-bm/(2*nh),this.celestialLight.shadow.normalBias=xm,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Tr),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new ue(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(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.render()}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*Am,0,t.z*Am);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*ui,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ui;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ui,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(gw(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/af),this.camera.far=Math.max(sf*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.poseElevationM=t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+t.elevationM,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.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=lt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Li.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=de(a.lat,a.lng,t,e);r.position.x=c.x-i,r.position.z=c.z+n};if(this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;s(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),lt.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=de(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<SP*(r/af))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(de(t,e,c.lat,c.lng).x,de(t,e,c.lat,c.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=r;const l=++this.terrainBuildToken;this.awaitArrival(Z2(t,e,this.terrainProviders,r,{route:this.observerRoute}),lt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:m})=>{if(l!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const g=this.terrainMesh,v=this.terrainMeshOrigin,M=v?de(t,e,v.lat,v.lng):void 0;g&&M&&Math.hypot(M.x,M.z)<=a&&(u.position.y=g.position.y+this.groundYOfPatch(g,M.x,M.z)),g&&v&&M&&Math.hypot(M.x,M.z)<=a?this.crossfadeTerrain(u,g,v):this.disposeMesh(this.terrainMesh),u.renderOrder=xP,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,m),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=Li.beamReachFor(this.beams,{lat:t,lng:e});if(!Li.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=de(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*lt.FAR_RING_KEPT_SHARE)return}const h=this.terrainProviders.patches,l=h?.farRingOf?.(t,e);if(h&&!l){this.dropFarRing();return}const u=l?.radiusM??Li.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(Z2(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*lt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),lt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=lt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-lt.FAR_RING_DROP_M;const m=p.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}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,i){if(this.grassReference){const r=de(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const n=de(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/lt.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}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=Li.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(de(t,e,s.lat,s.lng).x,de(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(ru(t,e,i)),lt.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>lt.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),lt.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(de(t,e,a.lat,a.lng).x,de(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(ru(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),Xn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=De(async()=>{const{WaterSystem:t}=await import("./WaterSystem-DSCbpNaj.js");return{WaterSystem:t}},[],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,i){const n=this.terrainProviders.railways;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(de(t,e,s.lat,s.lng).x,de(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(ru(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),Xn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=De(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-YNlv2jnz.js");return{RailwaySystem:t}},[],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,i)=>this.groundYOfPatch(t,e,i)))}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??=De(async()=>{const{TraceSystem:t}=await import("./TraceSystem-Cr68QBMq.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(Mm);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=ut.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?de(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="streetlight"&&!n.lamp?.supposed&&!n.track).map(n=>({x:i.x+n.eastM,z:i.z-n.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const n of this.decorObjects){if(n.kind!=="streetlight"||!n.lamp?.supposed||n.track)continue;const s=i.x+n.eastM,r=i.z-n.northM,a=this.roadSystem.atKerb(s,r);(a.x!==s||a.z!==r)&&this.lampNudges.set(n.id,{eastM:a.x-s,northM:-(a.z-r)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,n)=>{const s=e[n];if(i.id!==s.id||(i.track?.length??-1)!==(s.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(s)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==s[a])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const n=this.wallsOf(t,e.lat,e.lng),s=this.roadWalls;s?.lat===e.lat&&s.lng===e.lng&&s.walls.length===n.length&&s.walls.every((a,c)=>a.what===n[c].what&&Math.hypot(a.x-n[c].x,a.z-n[c].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const n=this.decorOriginInRoads(e,i);return t.filter(s=>s.kind==="building"||s.kind==="streetlight").map(s=>({what:`${s.kind}:${s.lamp?.supposed?"s":""}${s.headingDeg??0}:${s.sizeM?.widthM??""}:${s.sizeM?.lengthM??""}`,x:n.x+s.eastM,z:n.z-s.northM}))}roadWalls;drapeRoads(t,e,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(t,e,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new bi(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),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,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?gn.LENS_K:gn.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(t){this.compassHovered!==t&&(this.compassHovered=t,this.updateCompassVisibility())}setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassHovered||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(tP(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!PP(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=Zs.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:So.steppedOpticalDepth(t.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),n?this.buildPrecipitation():s&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||n||s)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=zP,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(lt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ut.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,lP);for(const i of t){const n=ut.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<uP,i.lamp),i.model&&i.id.startsWith(Pn.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=lt.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(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??=De(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-BqRjqAEx.js");return{ContrailSystem:t}},__vite__mapDeps([2,3]),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),i=this.lastAstronomy?.sun,n=lt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=cs.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),h=Ue.illuminanceOf(i.magnitude)*this.relativeScale;for(let l=0;l<3;l++)r[l]+=n*h*c[l]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(t){t!==this.beams&&(this.beams=t,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(t.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=De(async()=>{const{BeamSystem:t}=await import("./BeamSystem-CVcdt0fc.js");return{BeamSystem:t}},[],import.meta.url).then(({BeamSystem:t})=>{const e=new t;this.scene.add(e.group),this.beamSystem=e})}updateBeams(){const t=this.decorReferencePose;!this.beamSystem||t?.lat===void 0||t.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{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:(e,i,n)=>this.transmittanceTo(e,i,n),groundYAt:(e,i)=>this.groundYUnder(e,i)})}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?Ve(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(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(t+s*n,e-r)-i}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*ui)/Math.cos(t.lat*ui)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,c=this.scatteredSky,h=this.bodyEastScale;Math.abs(h-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*h}))),this.bodySystem.set(t,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},e,c?Object.assign((u,d)=>c.relativeOfLuminance(u,d),{recorded:c.recorded}):void 0,i),this.bodySystem.setSmoke(n,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const l=this.bodySystem.furthestFrom(this.camera.position)*1.2;l>this.camera.far&&(this.camera.far=l,this.camera.updateProjectionMatrix())}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,c,h)=>(a*e+(c+h)/2*s)/Math.PI;return[r(t.r,i.r,n.r),r(t.g,i.g,n.g),r(t.b,i.b,n.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,i=this.modelUrl(t)??e?.url,n=t.credit??e?.credit;if(!(!i||!n))return{scene:await gm(i),credit:n,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify(zf(t))||!ut.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=xS(i.scene);n.traverse(s=>{s instanceof Mt&&(s.userData.sharedModel=!0)}),ut.applyModelParameters(n,t.modelParameters,i.bindings),ut.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new Ms;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?mb[t.kind]:zf(t);if(!(!n||!ut.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await gm(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const h=this.decorGroups.get(t.id);if(!h)return;!i&&t.kind!=="tree"&&(se.glaze(c),Xn.reflectOn(c));const l={ref:JSON.stringify(n),scene:c,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,l),this.applyLoadedDecorModel(t,h,l),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${t.id}":`,s)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=gm(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Xn.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const n=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?de(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&Qh(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,s?0:this.gaitOffset.eastM,s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,c;if(s){const p=vr(s,i),m=ut.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*ui,v=m.x*Math.cos(g)+m.z*Math.sin(g),M=-m.x*Math.sin(g)+m.z*Math.cos(g),w=p.eastM+n.x,y=-p.northM+n.z;r.x=-(w+v),r.z=-(y+M),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ui,-(m.headingDeg+this.indoorLookYawDeg)*ui,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const h=this.findCabin(i,n,r);this.fitShadowToCabin(h.length>0),this.dimCabinSky(h),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const l=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const m=this.decorGroups.get(p.id);if(!m)continue;const g=vr(p,i),v=this.lampNudges.get(p.id),M=g.eastM+(v?.eastM??0)+n.x+r.x,w=-(g.northM+(v?.northM??0))+n.z+r.z,y=this.terrainMesh,b=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${l}`;if(m.userData.footprintKey!==b){if(p.kind==="wire"){const C=ut.wireGround(p,M,w,g.headingDeg,(N,L)=>this.groundYUnder(N,L));m.userData.footprintGroundY=C.startY,ut.shearWire(m,ut.sizeOf(p).lengthM,C.dropM)}else if(p.kind==="crossing"){const C=this.groundYUnder(M,w),N=-(g.headingDeg??0)*ui,L=Math.cos(N),P=Math.sin(N);m.userData.footprintGroundY=C,Ae.drape(ut.bodyOf(m),(z,H)=>this.groundYUnder(M+z*L+H*P,w-z*P+H*L)-C)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,M,w,g.headingDeg,g.altitudeM);m.userData.footprintKey=b}const _=g.altitudeM>lt.AIRBORNE_M&&Math.hypot(M,w)<lt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY;if(m.position.set(M,_+g.altitudeM,w),p.kind==="crop"){const C=Math.hypot(M,w);m.visible=C<=AP}const x=this.decorPresence.get(p.id),A=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(m.visible=!A);const I=this.decorSunlight.get(p.id);I&&!A&&this.lightFromAbove(m,I),g.headingDeg!==void 0&&(m.rotation.y=-g.headingDeg*ui);const D=uA(p,i);if(D!==void 0&&lt.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const C=this.terrainMesh,N=[C?.geometry.uuid,M-(C?.position.x??0),w-(C?.position.z??0),m.position.y-(C?.position.y??0),g.headingDeg,g.altitudeM].map(L=>typeof L=="number"?L.toFixed(4):L).join(":");m.userData.cropGroundKey!==N&&(ut.fitCropToGround(m,(L,P)=>this.groundYUnder(L,P)+g.altitudeM),m.userData.cropGroundKey=N)}if(!A){const C=m.position.distanceTo(this.camera.position);a=Math.max(a,C),C<lt.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateBeams();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.beams?.length&&this.terrainMeshOrigin?Li.beamReachFor(this.beams,this.terrainMeshOrigin):0,f=Math.max(sf*1.2,this.groundRadius*2.5,a*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let n=i;for(const s of this.terraces){const r=t-s.x,a=e-s.z,c=r*s.cos-a*s.sin,h=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(h)<=s.halfLengthM){const l=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=l*l*(3-2*l);n=Math.max(n,u*s.levelY+(1-u)*Math.min(s.levelY,i))}}return n}placeTerraces(t,e,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=vr(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=ut.sizeOf(s),u=-(a.headingDeg??0)*ui,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(h-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${l.widthM}:${l.lengthM}:${l.heightM}`;r.position.set(c,0,h),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=ut.fitTerrace(r,s,(m,g)=>this.terrainYUnder(c+m*d+g*f,h-m*f+g*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:h,cos:d,sin:f,halfWidthM:l.widthM/2,halfLengthM:l.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,l.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):Im}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+lt.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),h=Math.min(Math.max(this.patchSpacingM(e),1),50);let l=Number.NEGATIVE_INFINITY;for(let u=h;u<=c;u=Math.max(u+h,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),m=u*u/(2*lt.SIGHT_EARTH_RADIUS_M);l=Math.max(l,Math.atan2(p-m-i.y,u))}return l*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,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return Im;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),h=n.getZ((s-1)*s),l=Cr((e-r)/(a-r)*(s-1),0,s-1),u=Cr((i-c)/(h-c)*(s-1),0,s-1);if(!Number.isFinite(l)||!Number.isFinite(u))return Im;const d=Math.min(Math.floor(l),s-2),f=Math.min(Math.floor(u),s-2),p=l-d,m=u-f,g=(b,S)=>n.getY(b*s+S),v=g(f,d),M=g(f,d+1),w=g(f+1,d),y=g(f+1,d+1);return p+m<=1?v+(M-v)*p+(w-v)*m:y+(w-y)*(1-p)+(M-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return ut.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;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=Rs.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n,s){const r=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0&&n===void 0,maxIso:t.maxIso,metering:s??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?Rs.NONE:this.perception??Rs.NONE;if(Ii.uColorVision.value.set(...i.colorMatrix),Ii.uContrast.value=i.contrastGain,!t){Ii.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";Ii.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:n?4:3;const s=t.autoExposure?this.frameLight:void 0,r=t.autoExposure||this.skyUnknown?s?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),c=r===void 0?void 0:r+a.mean,h=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let l=c!==void 0&&c>0?1/(e*c):void 0;l!==void 0&&t.metering==="highlights"&&a.brightest>0&&(l=Math.min(l,lt.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),l!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(l=Math.min(l,lt.ZONE_KEPT_AT/(.18*e*s.brightest)));const u=l!==void 0?Math.min(l,t.maxIso!==void 0?h(t.maxIso):1/0):h(t.iso);Ii.uMediumExposure.value=u,Ii.uPhoneStrength.value=n&&c!==void 0&&c>0?cr.strengthFor(cr.MID_GREY*u*e*c):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,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new T;let r=0,a=0;for(const{position:c,luminanceCdM2:h,solidAngleSr:l}of this.bodySystem.metered.values())s.copy(c).project(t),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=h*l,a=Math.max(a,h*Math.min(1,l/(lt.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new it;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&ut.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?gb(n,t):void 0,c=a!==void 0?vc.lamps(a):O0(n,t,this.lastAstronomy?.sun.altitudeDeg);ut.setLit(r,n.kind,c,this.relativeScale,n.lamp);const h=this.streetlightLights.get(n.id);h&&(h.visible=c),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=De(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-xiiaXn1a.js");return{HeadlightSystem:t}},[],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),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new T(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=ut.sizeOf(t).lengthM,r=e.getWorldPosition(new T).addScaledVector(n,s/2-fP);r.y+=dP;const a=ut.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*pP,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?vc.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new T(Math.sin(i),0,-Math.cos(i)),s=new T(n.x*ww,this.camera.position.y-gP,n.z*ww);this.headlightSystem.aim("observer",e,s,n,mP,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=ut.bodyOf(e),r=s.children.find(h=>h.userData.emissive);if(!r)return;const a=yw*ut.lampShare(n),c=new Sx(16764006,a*this.relativeScale,vP);n?.colorTemperatureK&&c.color.setRGB(...ut.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;ut.setLitWindowShare(t?Rn.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 i=r=>{const a=xs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Lt.relativeOfResponse(a)/a;return[r[0]*c,r[1]*c,r[2]*c]},n=i(t.zenith),s=i(t.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=ji.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,vw,new rt(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<Nf){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=vw/Qn*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ve(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ve(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(Cr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?Cr(e.separationDeg*n*ui/a,0,2):0,h=Math.sin(a),[l,u]=a>1e-9?[Math.sin((1-c)*a)/h,Math.sin(c*a)/h]:[1,0],d={x:s.x*l+r.x*u,y:s.y*l+r.y*u,z:s.z*l+r.z*u},f=e.moonRadiusDeg*n;this.eclipseDiscs={sun:new T(s.x,s.y,s.z).normalize(),moon:new T(d.x,d.y,d.z).normalize(),sunRadiusRad:i*ui,moonRadiusRad:f*ui};const p=.01,m=(M,w)=>Ve(t.sun.altitudeDeg+M,t.sun.azimuthDeg+w,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},v={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Eh(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,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.updateBeams());const e=this.scatteredSky?.ambient??lt.relativeSkyOf(Zg(t.sun.altitudeDeg),this.relativeScale),i=e,n=this.lightUnderClouds(t),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Nt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??yw)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.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 i=this.weather.relativeHumidity,n=(i===void 0?$t.DEFAULT_AEROSOL_OPTICAL_DEPTH:So.opticalDepth(i))*$t.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ue.aureoleScale(n,Ue.airMass(t.altitudeDeg))*s,c=Ue.coronaScale(r),h=Ue.illuminanceOf(t.magnitude),l=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),c.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(l===this.lunarDiffractionKey)return;this.lunarDiffractionKey=l,this.lunarDiffraction||(this.lunarDiffraction=new yv,this.celestialGroup.add(this.lunarDiffraction.object));const u=Ue.profile(Ue.HAZE_COARSE_MODE),d=Ue.profile(Ue.CLOUD_DROPLETS),f=DC(t.altitudeDeg),p=new Float32Array(Ue.STEPS*3);let m=0;for(let w=0;w<Ue.STEPS;w++){const y=w*3,b=[0,1,2].map(_=>h*f[_]*(a*u[y+_]+c*d[y+_])),S=xs.shown(b,xs.luminanceOf(b),(_,x)=>e.relativeOfLuminance(_,x));p.set(S,y),m=Math.max(m,xs.response(S))}const{x:g,y:v,z:M}=Ve(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:g,y:v,z:M}:void 0,p)}applyAir(){this.scene.fog instanceof pc||(this.scene.fog=new pc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+e,Math.hypot(t-n.x,e-n.y,i-n.z))}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,lt.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.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:ji.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?ji.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:At.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?wP:yP),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 yO(wm),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Of(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(t){if(t.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new Hn,this.celestialGroup.add(this.reentrySystem.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Of(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(t,e,n=>this.cloudTransmission(n),(n,s)=>this.arrivingIlluminance(n,s,1)),this.emitterLights.set("reentries",[],t.map(n=>this.farEmitterOf(n.head,n.magnitude)).filter(n=>n!==void 0)),this.refreshSkyFlare();const i=new Set;for(const n of t){const s=`reentry:${n.reentryId}:${n.fragmentId}`,{x:r,y:a,z:c}=Ve(n.head.altitudeDeg,n.head.azimuthDeg,Qn);this.setGlare(s,r,a,c,this.arrivingIlluminance(n.head,n.magnitude,this.cloudTransmission(n.head)),0,lt.POINT_VEIL_HOLD_DEG),i.add(s)}for(const n of[...this.glareSprites.keys()])n.startsWith("reentry:")&&!i.has(n)&&this.disposeGlare(n);this.render()}setLaunchPlumes(t){t.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new Mi,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(t,this.relativeScale,e=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),e=>this.cloudTransmission(e)),this.render())}pickPlumeAt(t,e){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=this.plumeSystem.pickAt(i,lt.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return n&&this.groundHides(t,e)?void 0:n}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(of*this.camera.fov*Math.PI/180);let s,r=n;const a=new T;for(const[c,h]of this.decorGroups){if(!h.visible||!c.startsWith(Pn.ID_PREFIX))continue;a.copy(h.position).sub(this.camera.position).normalize();const l=a.dot(i);l>r&&(r=l,s=c)}return s&&!this.groundHides(t,e)?s:void 0}pickReentryAt(t,e){if(!this.reentrySystem?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(of*this.camera.fov*Math.PI/180),n=this.reentrySystem.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(of*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}updateCelestialLight(t,e){const i=this.relativeScale,n=t.sun.altitudeDeg>=Ul,s=!n&&t.moon.altitudeDeg>=Ul,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ui)),h=this.siteElevationM+this.observerElevationM;let l=r,u=n||s?pw.directFraction(r.altitudeDeg,h):0;n&&u<=0&&t.moon.altitudeDeg>=Ul&&(l=t.moon,u=pw.directFraction(l.altitudeDeg,h));const d=Math.max(0,Math.sin(Math.max(l.altitudeDeg,0)*ui)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),m=Math.max(0,1/(1+.1125*p)-f),g=[0,0,0];if(n||s){const S=Ue.illuminanceOf(r.magnitude)*i,_=this.air.transmittanceFromSpace(h,r.altitudeDeg);for(let D=0;D<3;D++)g[D]=S*_[D]*m*c,this.cloudBeam[D]=S*_[D];const{x,y:A,z:I}=Ve(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(x,A,I),u>0){const D=Ue.illuminanceOf(l.magnitude)*i,C=l===r?_:this.air.transmittanceFromSpace(h,l.altitudeDeg),N=l===r?f:this.cloudTransmission(l);for(let L=0;L<3;L++)a[L]=D*C[L]*N*u}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),_=e.skyIrradiance,x=[0,1,2].map(I=>_[I]*S+g[I]);this.skyLight.color.setRGB(x[0],x[1],x[2]);const A=te.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(x[0]+a[0]*d),A*(x[1]+a[1]*d),A*(x[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=l===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:M,y:w,z:y}=Ve(l.altitudeDeg,l.azimuthDeg,1);this.lightDirection.set(M,w,y),this.celestialLight.shadow.normalBias=xm*Cr(w/sP,.1,1),this.placeShadowFrustum();const b=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/b,a[1]/b,a[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 i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=cs.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Ue.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=lt.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let h=0;h<3;h++)n[h]=Math.max(0,a*r[h]*s*c-this.sceneSunBeam[h])}}t.traverse(s=>{const r=s.material;if(!(r instanceof er||r instanceof lo)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=lt.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new T(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=h=>{const l=r.dot(h)/i;return(l-Math.round(l))*i},c=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).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 i=e.camera,n=nP;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=cf+5,i.near=this.shadowLightDistanceM-cf,i.far=this.shadowLightDistanceM+cf,i.updateProjectionMatrix(),e.bias=-.004/(2*cf),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(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==lt.CABIN_SKY_SHARE&&(r.envMapIntensity=lt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(iP,Math.max(ma,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,n=i.camera;n.left=-e,n.right=e,n.top=e,n.bottom=-e;const s=Math.max(nh,e*(nh/ma));this.shadowLightDistanceM=Math.max(Qn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-bm/(2*s);const r=e>2*ma?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=ma;shadowLightDistanceM=Qn;shadowUp=new T(0,1,0);shadowAxisX=new T;shadowAxisY=new T;shadowWorld=new T;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*ui,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new T(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Lt.semiSaturation(Lt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new xn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}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 i=Math.max(this.relativeScale,1e-30),n=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:s,y:r,z:a}=Ve(t.altitudeDeg,t.azimuthDeg,1);return{direction:new T(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],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 i=ki.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=At.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return Of(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const n=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const 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.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),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,i=performance.now()+lt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"&&s.kind!=="vehicle"||s.observerSide!==void 0&&Qh(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=vr(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=ut.sizeOf(s),u=Math.max(l.widthM,l.lengthM)/2;Math.hypot(c,h)<u&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<u&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new Xn(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(c=>c.mesh)],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof bs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object,this.reentrySystem?.object].filter(c=>c!==void 0)],n=this.relativeScale,s=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,c=>this.measureSurroundings(c,n,s,r),t?0:Xn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,lt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new wh,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>Ve(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,r,a=>{const c=p=>p.map(m=>m/e),h=this.surroundings,l={up:c(a.up),down:c(a.down)},u=(p,m)=>p.some((g,v)=>Math.abs(g-m[v])>.03*Math.max(Math.abs(g),Math.abs(m[v]),1e-12)),d=!h||u(h.up,l.up)||u(h.down,l.down);d&&(this.surroundings=l),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(lt.adaptingLuminance(Math.exp(a.logAverage)/e,l.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Ul?t.sun:t.moon.altitudeDeg>=Ul?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new or;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?Ve(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??lt.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,s=>{const r={mean:s.mean/t.scale,brightest:s.brightest/t.scale},a=this.frameLight,c=t.atMs,h=a?c-a.atMs:1/0,l=h<0||h>lt.EXPOSURE_JUMP_MS,u=l||h===0&&a?.jumped?1:1-Math.exp(-h/n),d=(m,g)=>m>0&&g>0?m*(g/m)**u:g,f={mean:d(a?.mean??0,r.mean),brightest:d(a?.brightest??0,r.brightest),atMs:c,jumped:l||h===0&&(a?.jumped??!1)};this.frameLight=f;const p=(m,g)=>Math.abs(m-g)>.01*Math.max(m,g);(!a||p(a.mean,f.mean)||p(a.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Ii.uRetinaOn.value=0,this.medium)return;const t=[];for(const a of this.emitterLights.farEmitters){const c=this.screenPointOf(a.direction);!c||Math.abs(c.ndcX)>1.2||Math.abs(c.ndcY)>1.2||t.push({ndcX:c.ndcX,ndcY:c.ndcY,lux:xs.luminanceOf(a.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.y,1),n={width:this.camera.fov*i,height:this.camera.fov},s=this.retina?.atMs;if((s===void 0||this.recordingTimeMs<s||this.recordingTimeMs-s>ce.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new ce,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),n,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new ce,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(Ii.uRetina.value=this.retina.texture,Ii.uRetinaOn.value=1,Ii.uRetinaViewport.value.copy(e))}retinaSize=new it;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const n=i.pose,s=this.historicQuaternion.setFromEuler(this.historicEuler.set((n?.pitchDeg??0)*ui,-(n?.headingDeg??0)*ui,(n?.rollDeg??0)*ui,"YXZ")).invert(),r=n?.fovDeg??this.camera.fov,a=[];for(const c of i.views){const h=this.farEmitterOf(c.head,c.magnitude);if(!h)continue;const l=this.screenPointIn(this.historicDirection.copy(h.direction).applyQuaternion(s),r,e);!l||Math.abs(l.ndcX)>1.2||Math.abs(l.ndcY)>1.2||a.push({ndcX:l.ndcX,ndcY:l.ndcY,lux:xs.luminanceOf(h.lux)})}return a}historicQuaternion=new qn;historicEuler=new sa;historicDirection=new T;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<lt.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 i of t)i.traverse(n=>{n.userData.emissive===!0&&e.push(n)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,FP);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),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 i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ut.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[y1]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Ms.INTERVAL_MS)),Ii.uRodShare.value=this.scatteredSky?.rodShare??0,Ii.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Ii.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),s,r=>{this.lensFlare&&(this.lensFlare.mesh.visible=r?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof bs&&e.userData.pointSource||e instanceof Mt&&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(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Mm),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(ES),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=i}bodyCutOutMaterial=new ls({blending:Mc,blendSrc:Yr,blendDst:Yr,blendSrcAlpha:Yr,blendDstAlpha:Yr,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=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=i}setReferences(t,e){const i=t.map(n=>{const s=this.documentRelative(n.src);return s===n.src?n:{...n,src:s}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=De(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-By8XvGKa.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s;for(const[a,c]of this.referenceViews)s.setView(a,c);s.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&s.set(r.references,void 0,r.observerAt),this.render(),s})}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new T)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}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 i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const s=e?this.narrowTo(t,e):t,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse)),a=this.phenomena.furthestM;let c=0;for(const h of this.decorObjects){const l=this.decorGroups.get(h.id);if(!l)continue;const u=h.kind!=="crop"&&this.mayHide(l,t,r,a);lt.markDecorDepth(l,u),u&&c++}c>0&&(t.layers.set(vm),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(y1),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new L0;phenomenaViewProjection=new oe;occluderSphere=new yr;localBounds=new WeakMap;mayHide(t,e,i,n){let s=0;t.traverse(()=>s++);let r=this.localBounds.get(t);if(!r||r.objects!==s){t.updateMatrixWorld(!0);const c=new tn().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new yr).applyMatrix4(new oe().copy(t.matrixWorld).invert()),objects:s},this.localBounds.set(t,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(t.matrixWorld);return a.center.distanceTo(e.position)-a.radius>n?!1:i.intersectsSphere(a)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new it),n=lt.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),s=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-n)),r=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-n)),a=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+n)),c=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+n)),h=this.narrowCamera.copy(t);return h.setViewOffset(i.x,i.y,s,i.y-c,Math.max(1,a-s),Math.max(1,c-r)),h.updateMatrixWorld(),h}narrowCamera=new Nn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new ls({colorWrite:!1,side:_n});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(lt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*ui}static isSolidSurface(t){if(!(t instanceof Mt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==Mn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof Mt))return;e&&lt.isSolidSurface(i)?i.layers.enable(vm):i.layers.disable(vm)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new it),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new vC(e,i)),this.exposureAccumulation.resize(e,i),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 i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+lt.EXPOSURE_BUDGET_MS,s=lt.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,h)=>{c.visible=a[h]})}e.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Ii.uRodShare.value=this.scatteredSky?.rodShare??0,Ii.uHasOverlay.value=1,Ii.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(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(a=>a.visible))return;const i=new Hs,n=new Gs(-1,1,1,-1,0,2),s=lf/(xw*Math.tan(Sw*ui/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new T).sub(this.camera.position).normalize(),h=this.screenPointOf(c);if(!h)continue;const l=new Al(a.material);l.position.set(h.ndcX,h.ndcY,-1),l.scale.set(s/this.camera.aspect,s,1),i.add(l)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,n)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new tn,i=new T,n=this.camera.getWorldDirection(new T),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<lt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,h=-1/0,l=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const g=(m.ndcX+1)/2,v=(1-m.ndcY)/2;c=Math.min(c,g),h=Math.max(h,g),l=Math.min(l,v),u=Math.max(u,v)}c=Math.max(c,0),h=Math.min(h,1),l=Math.max(l,0),u=Math.min(u,1),h>=c&&u>=l&&t.push({x:c,y:l,width:h-c,height:u-l})}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())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new it),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new ou(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),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,Ii.uMediumExposure.value)}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 it);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Zi(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new it);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new Mv(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new it);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Ri(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,n=>{const s=lt.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!s||s.distance>=n-.001||this.mirrors.isMirror(s.object)})}aimStraightAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new it(e,i),this.camera);return}const s=n.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(s.x,s.y,s.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 T)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ri.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*ui);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new T;screenPointQuaternion=new qn;screenPointSize=new it;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 i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;t.uniforms.uResolution.value.set(n,s),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(r=>Math.max(0,r-lt.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=t.uniforms.uLensPosition.value;return{x:s.x,y:s.y,radius:i,flux:[e[0]*n,e[1]*n,e[2]*n]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const n=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(n.x,n.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(mw),this.camera.layers.set(mw),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of Aw)this.isSunOccluded(e[0],e[1])||t++;return t/Aw.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const n=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&n.length===0)return!1;const s=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),r=s.length();if(s.normalize(),e!==0||i!==0){const h=Math.PI/180,l=this.sunOcclusionRightScratch.set(s.z,0,-s.x);l.lengthSq()<1e-9&&l.set(1,0,0),l.normalize();const u=this.sunOcclusionUpScratch.crossVectors(l,s).normalize();s.addScaledVector(l,e*h).addScaledVector(u,i*h).normalize()}if(this.groundBlocks(this.camera.position,s,r)||this.cabinMask.hides(s))return!0;const a=this.cabinMask.any?n.filter(h=>!this.cabinGroups.includes(h)):n;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,s);const c=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(h=>!(h.object.material instanceof Oa));return c!==void 0&&c.distance<r}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 i=e.mesh.getWorldPosition(this.veilTargetScratch),n=e.mesh.material.uniforms.uSourceDeg.value,s=n>.05?lt.VEIL_SAMPLES:lt.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,c]of s)this.isOccludedToward(i,a*n,c*n)||r++;e.share=r/s.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new ms;veilTargetScratch=new T;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const v=t.x+e.x*g-s.position.x,M=t.z+e.z*g-s.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const h=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],l=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(h[1]-h[0]),Math.abs(l[1]-l[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[g,v,M]of[[t.x,e.x,h],[t.z,e.z,l]]){const w=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(g<w||g>y)return!1;continue}const b=(w-g)/v,S=(y-g)/v;d=Math.max(d,Math.min(b,S)),f=Math.min(f,Math.max(b,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const v=d+(f-d)*g/m,M=t.x+e.x*v,w=t.y+e.y*v,y=t.z+e.z*v;if(w<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=rf;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const c=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(h=>lt.isSolidSurface(h.object));c&&(r.occludesSourceIds?.includes(i)?n=n===void 0?c.distance:Math.max(n,c.distance):s=s===void 0?c.distance:Math.min(s,c.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=rP*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([l,u])=>{const d=u.getWorldPosition(new T).sub(i);return{key:l,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),a=this.eclipseDiscs,c=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],h=lt.nearestBody(n,[...r.filter(l=>!a||l.key!=="sun"&&l.key!=="moon"),...c],s);if(h)return this.groundHides(t,e)?void 0:h}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let n,s=1/0,r=1/0,a=!1;for(const c of e){const h=Math.acos(Cr(c.direction.dot(t),-1,1))-c.radiusRad;if(h>i)continue;const l=h<=0,u=s<=0,d=c.inFront===!0;(l!==u?l:l?d!==a?d:c.radiusRad<r:h<s)&&(n=c.key,s=h,r=c.radiusRad,a=d)}return n}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=eP*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?lt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let h,l=1/0;const u=new tn,d=new T;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new T).length()/2,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const v=Math.acos(Math.min(1,m.normalize().dot(n))),M=Math.atan(p/g);if(M>r){const w=this.raycaster.intersectObject(f,!0)[0];if(!w||c!==void 0&&c<w.distance)continue}else if(v>r)continue;M<l&&(l=M,h=f.name.slice(5))}return h}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(of*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const c=a.direction.dot(i);c>r&&(r=c,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(t,e)?void 0:s}groundHides(t,e){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,1/0,rf)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const c=this.bodyCornerScratch.set(a&1?e.max.x:e.min.x,a&2?e.max.y:e.min.y,a&4?e.max.z:e.min.z),h=this.screenPointOf(c.sub(this.camera.position).normalize());if(!h)return;i=Math.min(i,h.ndcX),s=Math.max(s,h.ndcX),n=Math.min(n,h.ndcY),r=Math.max(r,h.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new tn;bodyCornerScratch=new T;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;const i=this.bodyBoxScratch.setFromObject(e);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-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),l=this.screenPointOf(h.sub(this.camera.position).normalize());if(!l)return;n=Math.min(n,l.ndcX),r=Math.max(r,l.ndcX),s=Math.min(s,l.ndcY),a=Math.max(a,l.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,n=0){const s=this.decorGroups.get(t);if(!s)return;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(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*ui/2):0}decorGrabHeightAt(t,e,i){const n=this.decorGroups.get(t);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),c=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return c?Math.min(Math.max(c.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new wa;decorHitScratch=new T;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&(s.transparent&&s.opacity<lt.SEE_THROUGH_BELOW||s instanceof Oa))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=lt.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new ll().copy(n).applyMatrix4(new oe().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new T(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,lt.RAILWAY_PICK_ABOVE_M))return;const c=lt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-lt.RAILWAY_GROUND_MARGIN_M,rf))return;const h=i.group.worldToLocal(c.point.clone()),l=i.lineAt(h.x,h.z);if(!l)return;const u=i.contactHeightM(l);return{line:l,distanceM:c.distance,...u!==void 0?{contactM:u}:{}}}pickBeamAt(t,e){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,s=i.pickAt(n.origin,n.direction,lt.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,rf))return;const r=lt.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<s.distanceM))return s}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const 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())ut.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 i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new T;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<lt.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 nn(sf,32,16),i=e.attributes.position,n=e.getAttribute("color")??new pe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=Gx(i.getX(r),i.getY(r),i.getZ(r)),h=TC(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,h[0],h[1],h[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new ls({vertexColors:!0,side:Pi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Mt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=gw(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new Z1(this.groundRadius,48),i=new er({color:new rt(ym,ym,ym),fog:!0});pc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Mt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${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(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=Ve(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-Pe.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*cP);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Pe.iceAlphaAt(i,hf,r,this.cloudFieldOffset)*hP),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<Nf){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:c}=Ve(e.altitudeDeg,e.azimuthDeg,Qn),h=this.cloudTransmission(e),l=this.arrivingIlluminance(e,s,h),u=lt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/Qn)**2,p=[0,1,2].map(g=>u[g]*l[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(lt.BRIGHTEST_RELATIVE,g));d instanceof Mt||(this.disposeMesh(d),d=new Mt(new nn(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(m[0],m[1],m[2]),d.scale.setScalar(i)}else{if(!(d instanceof bs)){this.disposeMesh(d);const m=new me;m.setAttribute("position",new fe(new Float32Array(3),3)),m.setAttribute("color",new fe(new Float32Array(3),3)),d=new bs(m,Nt.material(uc[uc.length-1].size,!1)),Nt.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),p=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*l[0]*p,u[1]*l[1]*p,u[2]*l[2]*p),f.needsUpdate=!0}if(d.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=l),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,l,i/Qn*(180/Math.PI),lt.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,c*f),this.lensFlare||(this.lensFlare=MO(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<Nf){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ve(t.altitudeDeg,t.azimuthDeg,Qn),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),h=t.radiusDeg??Gr.MEAN_RADIUS_DEG,l=Qn*Math.tan(h*ui),u=Math.max(Cr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(l/Qn)**2,d=new rt(...c.map(m=>Math.min(lt.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(Cr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Al?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=Gw(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Al(new Rf({map:Gw(t.phase),color:d,fog:!1,blending:Mn,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(l*2,l*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,l),this.setGlare(i,n,s,r,c,h)}bentLight(t,e,i=aP){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return lt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new rt;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,Nt.CONE_SOLID_ANGLE/e)}pointScratch=new it;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=Ue.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=xs.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,i,n,s){let r=this.hitAreas.get(t);if(!r){const c=new Rf({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Al(c),this.celestialGroup.add(r),this.hitAreas.set(t,r)}r.position.set(e,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,n,s,r,a=0){if(gn.radiusDeg(gn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new gn(`veil:${t}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(t,c)),c.shine({x:e,y:i,z:n},s,r,a)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=sc(t.magnitude,e),s=am(n);this.cometKey=i,this.setBodyMesh(i,t.position,Sm*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new Ls(Qn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Gi,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:hf},0);return}const s=this.lowerCloudCover(),r=be.deckLitUntilDeg(be.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?ue.SUN_MAGNITUDE:e.magnitude),h=be.strength(i,s,a.altitudeDeg,r)*c.scale,{x:l,y:u,z:d}=Ve(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:l,y:u,z:d},a.altitudeDeg,h,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??hf},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??XS,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new nc,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=t.altitudeDeg>0,s=n?t:e,r=this.lowerCloudCover(),a=this.bentLight(s,n?ue.SUN_MAGNITUDE:e.magnitude,oP),c=Ns.strength(i,r,s.altitudeDeg)*a.scale;if(c<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:h,y:l,z:u}=Ve(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:h,y:l,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new so,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=hr.galactic(i,n),r=lt.directionOf(s.centre),a=lt.directionOf(s.rotation),c=lt.directionOf(s.pole),h=new le().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),l=lt.directionOf(hr.eclipticPole(i,n)),u=lt.directionOf(t.sun),d=u.clone().addScaledVector(l,-u.dot(l)).normalize();this.skyGlow.update({galactic:h,eclipticPole:l,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:lt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new T(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ve(t.altitudeDeg,t.azimuthDeg,1);return new T(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=sc(n.magnitude,e),a=am(r);this.setBodyMesh(s,n.position,Sm*(.5+.5*r),new rt(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=sc(n.magnitude,e),r=am(s),a=GP[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),h=Sm*(.5+.5*s);this.setBodyMesh(n.body,n.position,h,c,n.magnitude)}for(const n of[...this.bodyMeshes.keys()])i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=t,r=new fr(n,s),a=Pm(1337),c=[],h=this.siteElevationM+this.observerElevationM;for(let l=0;l<i.count;l++){const u=i.mag[l];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[l],i.dec[l]);if(d<Mw)continue;const{x:p,y:m,z:g}=Ve(d,f,wm);c.push({x:p,y:m,z:g,brightness:sc(u,e),illuminance:this.air.transmittanceFromSpace(h,d).map(v=>v*Ue.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const l of J6){if(l.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(l.raHours,l.decDeg);if(u<Mw)continue;const{x:f,y:p,z:m}=Ve(u,d,wm);this.namedStars.push({star:l,direction:new T(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=uc.map((l,u)=>{const d=c.filter(b=>H0(b.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),m=new Float32Array(d.length*3),g=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((b,S)=>{f[S*3]=b.x,f[S*3+1]=b.y,f[S*3+2]=b.z,p[S]=b.brightness,m.set(b.illuminance,S*3),g[S]=b.phase,v[S]=b.speedFactor});const M=new me;M.setAttribute("position",new fe(f,3)),M.setAttribute("seed",new fe(g.map(b=>b/(2*Math.PI)),1));const w=new fe(new Float32Array(d.length*3),3);M.setAttribute("color",w);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new bs(M,Nt.material(l.size)),Nt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:p,illuminance:m,phase:g,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Nt.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const i of this.starTiers){const n=i.colorAttribute.array;for(let s=0;s<i.brightness.length;s++)n[s*3]=i.illuminance[s*3]*e,n[s*3+1]=i.illuminance[s*3+1]*e,n[s*3+2]=i.illuminance[s*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Fh(this.celestialGroup,Em,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new rt(Go[0]+(Tm[0]-Go[0])*e,Go[1]+(Tm[1]-Go[1])*e,Go[2]+(Tm[2]-Go[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Xg(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=$g(Em);this.cloudMesh=new Mt(r,n),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:i}=Xg(new rt(...Go),t,hf,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Mt($g(Em*1.04),e),this.cirrusMesh.renderOrder=_w-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 i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?Fh.deckOrder(!0,0,1):_w}cloudLayerOffset(){const e=((this.weather.cloudBaseM??b1)-this.observerElevationM)*Am;return Math.sign(e||1)*Math.max(Math.abs(e),EP)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*Om*this.relativeScale/Math.PI,h=new rt(e[0]+Tr.r*c,e[1]+Tr.g*c,e[2]+Tr.b*c);this.layeredClouds?.setLighting(n.clone(),new rt(s,r,a),h,h);const l=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*l,r*l,a*l),u.ambientColor.value.copy(h)}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 OP(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,Dm],[this.rainSplashSystem?.points,Vo],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Rm[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=Dw(Cm(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=Rm[t],i=e.poolSize,n=Pm(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),l=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let w=0;w<i;w++){const y=n()*Math.PI*2,b=n()*e.radiusM;s[w*3]=Math.cos(y)*b,s[w*3+1]=oh+n()*(e.topYM-oh),s[w*3+2]=Math.sin(y)*b,r[w]=n()*Math.PI*2,a[w]=.7+n()*.6,c[w]=.6+n()*.8,h[w]=.4+n()*1.2}const m=new me;m.setAttribute("position",new fe(s,3)),m.setDrawRange(0,this.precipitationCount(i));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 rt(...this.baseFogColor)},uTexture:{value:VP(t)},uNearFocusDistance:{value:Nw},uHazeDistance:{value:e.radiusM*Lw}},v=new Te({uniforms:g,vertexShader:qP,fragmentShader:ZP,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const M=new bs(m,v);M.renderOrder=_m,this.scene.add(M),this.precipitationPoints=M,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=h,this.precipitationBounceRemaining=l,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const n=Rm[i];if(this.precipitationUniforms?.uColor.value.copy(lt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*ui,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,h=this.precipitationPhase,l=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,m=this.precipitationBounceDuration,g=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,M=i==="snow"&&u&&d,w=i==="hail"&&f&&p&&m&&g&&v;for(let y=0,b=0;y<c.length;y+=3,b++){if(w&&f[b]>0){if(f[b]-=e,f[b]<=0){const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(x)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(x)*A,f[b]=0}else{const x=1-f[b]/m[b];c[y+1]=oh+Math.sin(Math.PI*x)*p[b],c[y]=uf(c[y]+(r+g[b])*e,n.radiusM),c[y+2]=uf(c[y+2]+(a+v[b])*e,n.radiusM)}continue}let S=0,_=0;if(M){const x=NP*u[b],A=LP*d[b];S=Math.sin(t*x*Math.PI*2+h[b])*A,_=Math.sin(t*x*Math.PI*2+h[b]+Math.PI/2)*A}if(c[y]+=(r+S)*e,c[y+1]-=n.fallSpeedMPerS*l[b]*e,c[y+2]+=(a+_)*e,c[y]=uf(c[y],n.radiusM),c[y+2]=uf(c[y+2],n.radiusM),c[y+1]<oh){if(w){p[b]=Bw*(.2+Math.random()*1.6),m[b]=kP*(.5+Math.random()),f[b]=m[b];const I=Math.random()*Math.PI*2,D=UP*(p[b]/Bw);g[b]=Math.cos(I)*D,v[b]=Math.sin(I)*D,c[y+1]=oh;continue}const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(x)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(x)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=Cm(this.weather.precipitationIntensity);this.rainSystem=mO({count:Dm,radiusM:Fl,heightM:_P,bottomYM:Tw,overallSpeed:TP,color:Iw.clone(),opacity:.85,visibleCount:this.precipitationCount(Dm),speedStreak:Dw(t),pixelSize:Uw,seed:9001,nearFocusDistanceM:Nw,hazeDistanceM:Fl*Lw,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=_m,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=Pm(4242),e=new Float32Array(Vo*3),i=new Float32Array(Vo),n=new Float32Array(Vo),s=new Float32Array(Vo);for(let l=0;l<Vo;l++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Fl;e[l*3]=Math.cos(u)*d,e[l*3+1]=Tw,e[l*3+2]=Math.sin(u)*d,n[l]=Hw(Cw,Ow),i[l]=t()*n[l],s[l]=i[l]/n[l]}const r=new me;r.setAttribute("position",new fe(e,3));const a=new fe(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Vo));const c=new Te({uniforms:{uMaxSize:{value:CP},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Pw.clone()},uTexture:{value:$P()}},vertexShader:YP,fragmentShader:KP,transparent:!0,depthWrite:!1}),h=new bs(r,c);h.renderOrder=_m,this.scene.add(h),this.rainSplashSystem={points:h,positions:e,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*ui;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-Cm(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.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(lt.litBySky(Iw,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(lt.litBySky(Pw,this.baseFogColor));const n=this.weather.windDirectionDeg*ui,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Fl,c=l=>(l%(a*2)+a*3)%(a*2)-a;e.uniforms.uWindOffset.value.set(c(e.uniforms.uWindOffset.value.x+s*t),c(e.uniforms.uWindOffset.value.y+r*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const h=Math.abs(this.rainCameraDirection.y);if(Math.abs(h-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=h;const l=Fw+(1-Fw)*(1-h),u=zw+(1-zw)*(1-h);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=Uw*l*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=e,a=r.array;for(let c=0,h=0;c<i.length;c+=3,h++){if(n[h]+=t,n[h]>=s[h]){const l=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Fl;i[c]=Math.cos(l)*u,i[c+2]=Math.sin(l)*u,s[h]=Hw(Cw,Ow),n[h]=0}a[h]=n[h]/s[h]}e.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>t)break;const h=dn.brightnessAt(c,t);h>i&&(e=c,i=h)}const n=e?Math.min(1,Math.max(.1,(BP/e.distanceM)**2)):0,s=i*n*(e?.cloudToGround?1:.6);if(s===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,h=s*Om*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Tr.r*h,this.airlight[1]+Tr.g*h,this.airlight[2]+Tr.b*h)}const r=this.skyMesh?.material?.color;if(r){const c=s*HP;r.setRGB(1+c*Tr.r,1+c*Tr.g,1+c*Tr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Om*this.relativeScale,e){const{x:c,y:h,z:l}=Ve(25,e.azimuthDeg,Qn);this.lightningLight.position.set(c,h,l)}this.lightningBolt||(this.lightningBolt=new ro(Qn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=MP.map(t=>{const e=fc.point(t,this.compassPoints),i=new Rf({map:JP(e),depthTest:!1,fog:!1}),n=new Al(i),{x:s,y:r,z:a}=Ve(0,t,xw);return n.position.set(s,r,a),n.scale.set(lf,lf,1),n.renderOrder=bP,n.layers.set(Mm),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=Sw*Math.PI/360,i=lf*Math.tan(t)/Math.tan(e);for(const n of this.compassSprites)n.scale.set(i,i,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 i of Array.isArray(e)?e:[e]){const n=i.map;n&&n.dispose(),i.dispose()}}}const ui=Math.PI/180;function Cr(o,t,e){return Math.max(t,Math.min(e,o))}function Hw(o,t){return o+Math.random()*(t-o)}function uf(o,t){return(o%(t*2)+t*3)%(t*2)-t}let df,ff;function VP(o){switch(o){case"snow":return WP();case"hail":return XP()}}function WP(){if(df)return df;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),df=new No(t),df}function XP(){if(ff)return ff;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),ff=new No(t),ff}let pf;function $P(){if(pf)return pf;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),pf=new No(t),pf}const YP=`
9156
+ `,transparent:!0,blending:Mn,depthWrite:!1,side:Pi,fog:!1});this.object=new Mt(new nn(yv.RADIUS,128,32,0,Math.PI*2,0,Ue.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 i=0;i<Ue.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Tn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=Tn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class v0{constructor(t){this.generator=t}static SIZE=128;target=new qu(v0.SIZE,{type:Xe,generateMipmaps:!0,minFilter:Bs,magFilter:ye});camera=new sv(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,n=[]){const s=t.shadowMap.autoUpdate;let r=!1;e.traverse(c=>{const h=c;h.isLight&&h.castShadow&&h.shadow&&!h.shadow.map&&(r=!0)}),t.shadowMap.autoUpdate=r?s:!1;const a=n.map(c=>c.visible);for(const c of n)c.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),n.forEach((c,h)=>{c.visible=a[h]}),t.shadowMap.autoUpdate=s,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class Xn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Xn.install(),this.generator=new Hg(t),this.eye=new v0(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],h,l=Xn.REFRESH_MS){for(const g of[...this.probes.keys()])n.some(v=>v.id===g&&v.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const u=[{probe:this.eye}];for(const g of n){if(!g.shiny)continue;let v=this.probes.get(g.id);v||(v=new v0(this.generator),this.probes.set(g.id,v)),u.push({probe:v,reflector:g})}const d=performance.now(),f=()=>u.filter(({probe:g})=>g.capturedVersion!==a),p=f().filter(({probe:g})=>d-g.capturedAtMs>=l);if(p.length>0){const g=p.reduce((v,M)=>M.probe.capturedAtMs<v.probe.capturedAtMs?M:v);if(g.reflector){const v=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,v,[g.reflector.holder,...s]),Xn.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),h?.(g.probe.sharp),Xn.decor=g.probe.filtered;for(const v of r)Xn.reflectOn(v,g.probe);for(const v of n)v.shiny||Xn.reflectOn(v.holder,g.probe)}g.probe.capturedVersion=a}const m=f();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:g})=>l-(d-g.capturedAtMs))))}scratch=new T;static reflectOn(t,e={filtered:Xn.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Oa?e.sharp&&s.setSurroundings(e.sharp):s instanceof lo&&e.filtered&&s.envMap!==e.filtered&&(s.envMap=e.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(Xn.installed)return;Xn.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!he.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}he.lights_fragment_maps=he.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function tP(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.rareIceCrystals===t.rareIceCrystals&&o.lowerCloudCover===t.lowerCloudCover&&o.relativeHumidity===t.relativeHumidity&&o.precipitationType===t.precipitationType&&o.precipitationIntensity===t.precipitationIntensity&&o.precipitationAmount===t.precipitationAmount&&o.windDirectionDeg===t.windDirectionDeg&&o.windSpeed===t.windSpeed&&o.storm===t.storm}const sf=900,vm=1,mw=4,Mm=5,rf=.5,af=Li.GROUND_RADIUS_M;function gw(o){return Li.groundRadiusFor(o)}const ym=.5,wm=850,of=.03,eP=.015,Qn=850,nh=300,ma=120,iP=700,bm=.03,nP=3.5,cf=20,xm=.04,sP=.26,vw=4,Sm=1.5,Mw=-1,rP=.01,Nf=-4,aP=2,oP=20,hf=2600,cP=.97,hP=.38,Ul=Nf,lP=8,uP=2,yw=1500,dP=.7,fP=.3,pP=.32,mP=.65,ww=2.4,gP=.9,vP=400,MP=[0,45,90,135,180,225,270,315],yP=2,wP=16,bw=4e3,xw=880,lf=40,Sw=60,bP=10,xP=1,SP=Li.REBUILD_DISTANCE_M,Ew=.265,Aw=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*Ew,Math.sin(e)*Ew]})],Em=700,Am=250/b1,EP=12,_w=5,_m=6,Go=[.92,.92,.95],Tm=[.15,.15,.19],Rm={snow:{fallSpeedMPerS:2,size:.3,color:new rt(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new rt(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},oh=0,Im=0,AP=150,Dm=3e3,Fl=20,_P=15,Tw=oh,TP=40,Rw=1,RP=9;function Cm(o){return Rw+(RP-Rw)*o}const Iw=new rt(.75,.82,.92),IP=10,DP=.5;function Dw(o){return Cr(o/IP,DP,1)}const Vo=200,Cw=.18,Ow=.32,CP=.35,Pw=new rt(.85,.9,.98),Nw=5,Lw=.85,kw=.01;function OP(o,t,e=1){return Math.round(o*(kw+(1-kw)*t)*e)}function PP(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.lowerCloudCover===t.lowerCloudCover}const Uw=230,Fw=.7,zw=.05,NP=.6,LP=.7,kP=.15,Bw=.35,UP=3,FP=1/12,zP=.5,Tr=new rt(.82,.86,1),BP=2500,HP=1.6,Om=15,GP={Venus:new rt(1,.96,.85),Mars:new rt(1,.55,.4),Jupiter:new rt(.95,.87,.72),Saturn:new rt(.92,.86,.68)};class lt{renderer;scene=new Hs;phenomena=new lr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Be;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 i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=e===void 0?void 0:setTimeout(n,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(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+bw,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),bw+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new it;decorModelProvider=JO[0].create();decorModelToken=0;decorModelCredits=new Map;emitterLights=new es(this.scene,()=>this.relativeScale,{halfExtentM:ma,depthHalfRangeM:nh,biasM:bm,normalBiasM:xm,mapSize:1024});bodySystem=new se(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??lt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*lt.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new s0(16777215,0);celestialLightTarget=new Di;skyLight=new $T(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new If;weather=A0;observerElevationM=0;siteElevationM=0;air=new Zs;groundRadius=af;terrainRadius=af;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new T;cloudFieldOffset=new T;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new T;rainLastVerticalFacing=-1;rainViewportSize=new it;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new s0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new T;sunVisible=!1;lensFlareScratch=new T;sunOcclusionRaycaster=new If;sunOcclusionDirectionScratch=new T;sunOcclusionRightScratch=new T;sunOcclusionUpScratch=new T;ufoOcclusionRaycaster=new If;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=Si.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;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new Ju;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Pb()){su.install(),this.renderer=new oC({canvas:t,antialias:!0}),this.resolution=new Je(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Zl,this.camera=new Nn(60,t.width/Math.max(t.height,1),.1,sf*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=-ma,this.celestialLight.shadow.camera.right=ma,this.celestialLight.shadow.camera.top=ma,this.celestialLight.shadow.camera.bottom=-ma,this.celestialLight.shadow.camera.near=Qn-nh,this.celestialLight.shadow.camera.far=Qn+nh,this.celestialLight.shadow.bias=-bm/(2*nh),this.celestialLight.shadow.normalBias=xm,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Tr),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new ue(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(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.render()}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*Am,0,t.z*Am);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*ui,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ui;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ui,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(gw(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/af),this.camera.far=Math.max(sf*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.poseElevationM=t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+t.elevationM,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.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=lt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Li.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=de(a.lat,a.lng,t,e);r.position.x=c.x-i,r.position.z=c.z+n};if(this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;s(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),lt.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=de(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<SP*(r/af))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(de(t,e,c.lat,c.lng).x,de(t,e,c.lat,c.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=r;const l=++this.terrainBuildToken;this.awaitArrival(Z2(t,e,this.terrainProviders,r,{route:this.observerRoute}),lt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:m})=>{if(l!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const g=this.terrainMesh,v=this.terrainMeshOrigin,M=v?de(t,e,v.lat,v.lng):void 0;g&&M&&Math.hypot(M.x,M.z)<=a&&(u.position.y=g.position.y+this.groundYOfPatch(g,M.x,M.z)),g&&v&&M&&Math.hypot(M.x,M.z)<=a?this.crossfadeTerrain(u,g,v):this.disposeMesh(this.terrainMesh),u.renderOrder=xP,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,m),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=Li.beamReachFor(this.beams,{lat:t,lng:e});if(!Li.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=de(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*lt.FAR_RING_KEPT_SHARE)return}const h=this.terrainProviders.patches,l=h?.farRingOf?.(t,e);if(h&&!l){this.dropFarRing();return}const u=l?.radiusM??Li.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(Z2(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*lt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),lt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=lt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-lt.FAR_RING_DROP_M;const m=p.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}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,i){if(this.grassReference){const r=de(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const n=de(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/lt.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}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=Li.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(de(t,e,s.lat,s.lng).x,de(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(ru(t,e,i)),lt.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>lt.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),lt.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(de(t,e,a.lat,a.lng).x,de(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(ru(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),Xn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Ie(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BulddAwi.js");return{WaterSystem:t}},[],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,i){const n=this.terrainProviders.railways;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(de(t,e,s.lat,s.lng).x,de(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(ru(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),Xn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Ie(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-9blFcIdg.js");return{RailwaySystem:t}},[],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,i)=>this.groundYOfPatch(t,e,i)))}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??=Ie(async()=>{const{TraceSystem:t}=await import("./TraceSystem-CLYZFxAf.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(Mm);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=ut.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?de(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="streetlight"&&!n.lamp?.supposed&&!n.track).map(n=>({x:i.x+n.eastM,z:i.z-n.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const n of this.decorObjects){if(n.kind!=="streetlight"||!n.lamp?.supposed||n.track)continue;const s=i.x+n.eastM,r=i.z-n.northM,a=this.roadSystem.atKerb(s,r);(a.x!==s||a.z!==r)&&this.lampNudges.set(n.id,{eastM:a.x-s,northM:-(a.z-r)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,n)=>{const s=e[n];if(i.id!==s.id||(i.track?.length??-1)!==(s.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(s)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==s[a])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const n=this.wallsOf(t,e.lat,e.lng),s=this.roadWalls;s?.lat===e.lat&&s.lng===e.lng&&s.walls.length===n.length&&s.walls.every((a,c)=>a.what===n[c].what&&Math.hypot(a.x-n[c].x,a.z-n[c].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const n=this.decorOriginInRoads(e,i);return t.filter(s=>s.kind==="building"||s.kind==="streetlight").map(s=>({what:`${s.kind}:${s.lamp?.supposed?"s":""}${s.headingDeg??0}:${s.sizeM?.widthM??""}:${s.sizeM?.lengthM??""}`,x:n.x+s.eastM,z:n.z-s.northM}))}roadWalls;drapeRoads(t,e,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(t,e,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new bi(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),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,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?gn.LENS_K:gn.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(t){this.compassHovered!==t&&(this.compassHovered=t,this.updateCompassVisibility())}setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassHovered||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(tP(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!PP(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=Zs.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:So.steppedOpticalDepth(t.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),n?this.buildPrecipitation():s&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||n||s)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=zP,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(lt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ut.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,lP);for(const i of t){const n=ut.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<uP,i.lamp),i.model&&i.id.startsWith(Pn.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=lt.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(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??=Ie(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-BeK11Jxe.js");return{ContrailSystem:t}},__vite__mapDeps([4,5]),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),i=this.lastAstronomy?.sun,n=lt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=cs.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),h=Ue.illuminanceOf(i.magnitude)*this.relativeScale;for(let l=0;l<3;l++)r[l]+=n*h*c[l]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(t){t!==this.beams&&(this.beams=t,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(t.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=Ie(async()=>{const{BeamSystem:t}=await import("./BeamSystem-B0H346X_.js");return{BeamSystem:t}},[],import.meta.url).then(({BeamSystem:t})=>{const e=new t;this.scene.add(e.group),this.beamSystem=e})}updateBeams(){const t=this.decorReferencePose;!this.beamSystem||t?.lat===void 0||t.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{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:(e,i,n)=>this.transmittanceTo(e,i,n),groundYAt:(e,i)=>this.groundYUnder(e,i)})}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?Ve(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(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(t+s*n,e-r)-i}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*ui)/Math.cos(t.lat*ui)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,c=this.scatteredSky,h=this.bodyEastScale;Math.abs(h-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*h}))),this.bodySystem.set(t,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},e,c?Object.assign((u,d)=>c.relativeOfLuminance(u,d),{recorded:c.recorded}):void 0,i),this.bodySystem.setSmoke(n,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const l=this.bodySystem.furthestFrom(this.camera.position)*1.2;l>this.camera.far&&(this.camera.far=l,this.camera.updateProjectionMatrix())}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,c,h)=>(a*e+(c+h)/2*s)/Math.PI;return[r(t.r,i.r,n.r),r(t.g,i.g,n.g),r(t.b,i.b,n.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,i=this.modelUrl(t)??e?.url,n=t.credit??e?.credit;if(!(!i||!n))return{scene:await gm(i),credit:n,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify(zf(t))||!ut.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=xS(i.scene);n.traverse(s=>{s instanceof Mt&&(s.userData.sharedModel=!0)}),ut.applyModelParameters(n,t.modelParameters,i.bindings),ut.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new Ms;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?mb[t.kind]:zf(t);if(!(!n||!ut.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await gm(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const h=this.decorGroups.get(t.id);if(!h)return;!i&&t.kind!=="tree"&&(se.glaze(c),Xn.reflectOn(c));const l={ref:JSON.stringify(n),scene:c,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,l),this.applyLoadedDecorModel(t,h,l),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${t.id}":`,s)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=gm(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Xn.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const n=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?de(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&Qh(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,s?0:this.gaitOffset.eastM,s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,c;if(s){const p=vr(s,i),m=ut.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*ui,v=m.x*Math.cos(g)+m.z*Math.sin(g),M=-m.x*Math.sin(g)+m.z*Math.cos(g),w=p.eastM+n.x,y=-p.northM+n.z;r.x=-(w+v),r.z=-(y+M),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ui,-(m.headingDeg+this.indoorLookYawDeg)*ui,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const h=this.findCabin(i,n,r);this.fitShadowToCabin(h.length>0),this.dimCabinSky(h),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const l=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const m=this.decorGroups.get(p.id);if(!m)continue;const g=vr(p,i),v=this.lampNudges.get(p.id),M=g.eastM+(v?.eastM??0)+n.x+r.x,w=-(g.northM+(v?.northM??0))+n.z+r.z,y=this.terrainMesh,b=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${l}`;if(m.userData.footprintKey!==b){if(p.kind==="wire"){const C=ut.wireGround(p,M,w,g.headingDeg,(N,L)=>this.groundYUnder(N,L));m.userData.footprintGroundY=C.startY,ut.shearWire(m,ut.sizeOf(p).lengthM,C.dropM)}else if(p.kind==="crossing"){const C=this.groundYUnder(M,w),N=-(g.headingDeg??0)*ui,L=Math.cos(N),P=Math.sin(N);m.userData.footprintGroundY=C,Ae.drape(ut.bodyOf(m),(z,H)=>this.groundYUnder(M+z*L+H*P,w-z*P+H*L)-C)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,M,w,g.headingDeg,g.altitudeM);m.userData.footprintKey=b}const _=g.altitudeM>lt.AIRBORNE_M&&Math.hypot(M,w)<lt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY;if(m.position.set(M,_+g.altitudeM,w),p.kind==="crop"){const C=Math.hypot(M,w);m.visible=C<=AP}const x=this.decorPresence.get(p.id),A=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(m.visible=!A);const I=this.decorSunlight.get(p.id);I&&!A&&this.lightFromAbove(m,I),g.headingDeg!==void 0&&(m.rotation.y=-g.headingDeg*ui);const D=uA(p,i);if(D!==void 0&&lt.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const C=this.terrainMesh,N=[C?.geometry.uuid,M-(C?.position.x??0),w-(C?.position.z??0),m.position.y-(C?.position.y??0),g.headingDeg,g.altitudeM].map(L=>typeof L=="number"?L.toFixed(4):L).join(":");m.userData.cropGroundKey!==N&&(ut.fitCropToGround(m,(L,P)=>this.groundYUnder(L,P)+g.altitudeM),m.userData.cropGroundKey=N)}if(!A){const C=m.position.distanceTo(this.camera.position);a=Math.max(a,C),C<lt.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateBeams();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.beams?.length&&this.terrainMeshOrigin?Li.beamReachFor(this.beams,this.terrainMeshOrigin):0,f=Math.max(sf*1.2,this.groundRadius*2.5,a*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let n=i;for(const s of this.terraces){const r=t-s.x,a=e-s.z,c=r*s.cos-a*s.sin,h=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(h)<=s.halfLengthM){const l=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=l*l*(3-2*l);n=Math.max(n,u*s.levelY+(1-u)*Math.min(s.levelY,i))}}return n}placeTerraces(t,e,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=vr(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=ut.sizeOf(s),u=-(a.headingDeg??0)*ui,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(h-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${l.widthM}:${l.lengthM}:${l.heightM}`;r.position.set(c,0,h),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=ut.fitTerrace(r,s,(m,g)=>this.terrainYUnder(c+m*d+g*f,h-m*f+g*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:h,cos:d,sin:f,halfWidthM:l.widthM/2,halfLengthM:l.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,l.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):Im}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+lt.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),h=Math.min(Math.max(this.patchSpacingM(e),1),50);let l=Number.NEGATIVE_INFINITY;for(let u=h;u<=c;u=Math.max(u+h,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),m=u*u/(2*lt.SIGHT_EARTH_RADIUS_M);l=Math.max(l,Math.atan2(p-m-i.y,u))}return l*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,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return Im;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),h=n.getZ((s-1)*s),l=Cr((e-r)/(a-r)*(s-1),0,s-1),u=Cr((i-c)/(h-c)*(s-1),0,s-1);if(!Number.isFinite(l)||!Number.isFinite(u))return Im;const d=Math.min(Math.floor(l),s-2),f=Math.min(Math.floor(u),s-2),p=l-d,m=u-f,g=(b,S)=>n.getY(b*s+S),v=g(f,d),M=g(f,d+1),w=g(f+1,d),y=g(f+1,d+1);return p+m<=1?v+(M-v)*p+(w-v)*m:y+(w-y)*(1-p)+(M-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return ut.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;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=Rs.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n,s){const r=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0&&n===void 0,maxIso:t.maxIso,metering:s??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?Rs.NONE:this.perception??Rs.NONE;if(Ii.uColorVision.value.set(...i.colorMatrix),Ii.uContrast.value=i.contrastGain,!t){Ii.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";Ii.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:n?4:3;const s=t.autoExposure?this.frameLight:void 0,r=t.autoExposure||this.skyUnknown?s?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),c=r===void 0?void 0:r+a.mean,h=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let l=c!==void 0&&c>0?1/(e*c):void 0;l!==void 0&&t.metering==="highlights"&&a.brightest>0&&(l=Math.min(l,lt.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),l!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(l=Math.min(l,lt.ZONE_KEPT_AT/(.18*e*s.brightest)));const u=l!==void 0?Math.min(l,t.maxIso!==void 0?h(t.maxIso):1/0):h(t.iso);Ii.uMediumExposure.value=u,Ii.uPhoneStrength.value=n&&c!==void 0&&c>0?cr.strengthFor(cr.MID_GREY*u*e*c):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,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new T;let r=0,a=0;for(const{position:c,luminanceCdM2:h,solidAngleSr:l}of this.bodySystem.metered.values())s.copy(c).project(t),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=h*l,a=Math.max(a,h*Math.min(1,l/(lt.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new it;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&ut.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?gb(n,t):void 0,c=a!==void 0?vc.lamps(a):O0(n,t,this.lastAstronomy?.sun.altitudeDeg);ut.setLit(r,n.kind,c,this.relativeScale,n.lamp);const h=this.streetlightLights.get(n.id);h&&(h.visible=c),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=Ie(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-DjtbpwEp.js");return{HeadlightSystem:t}},[],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),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new T(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=ut.sizeOf(t).lengthM,r=e.getWorldPosition(new T).addScaledVector(n,s/2-fP);r.y+=dP;const a=ut.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*pP,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?vc.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new T(Math.sin(i),0,-Math.cos(i)),s=new T(n.x*ww,this.camera.position.y-gP,n.z*ww);this.headlightSystem.aim("observer",e,s,n,mP,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=ut.bodyOf(e),r=s.children.find(h=>h.userData.emissive);if(!r)return;const a=yw*ut.lampShare(n),c=new Sx(16764006,a*this.relativeScale,vP);n?.colorTemperatureK&&c.color.setRGB(...ut.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;ut.setLitWindowShare(t?Rn.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 i=r=>{const a=xs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Lt.relativeOfResponse(a)/a;return[r[0]*c,r[1]*c,r[2]*c]},n=i(t.zenith),s=i(t.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=ji.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,vw,new rt(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<Nf){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=vw/Qn*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ve(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ve(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(Cr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?Cr(e.separationDeg*n*ui/a,0,2):0,h=Math.sin(a),[l,u]=a>1e-9?[Math.sin((1-c)*a)/h,Math.sin(c*a)/h]:[1,0],d={x:s.x*l+r.x*u,y:s.y*l+r.y*u,z:s.z*l+r.z*u},f=e.moonRadiusDeg*n;this.eclipseDiscs={sun:new T(s.x,s.y,s.z).normalize(),moon:new T(d.x,d.y,d.z).normalize(),sunRadiusRad:i*ui,moonRadiusRad:f*ui};const p=.01,m=(M,w)=>Ve(t.sun.altitudeDeg+M,t.sun.azimuthDeg+w,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},v={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Eh(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,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.updateBeams());const e=this.scatteredSky?.ambient??lt.relativeSkyOf(Zg(t.sun.altitudeDeg),this.relativeScale),i=e,n=this.lightUnderClouds(t),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Nt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??yw)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.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 i=this.weather.relativeHumidity,n=(i===void 0?$t.DEFAULT_AEROSOL_OPTICAL_DEPTH:So.opticalDepth(i))*$t.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ue.aureoleScale(n,Ue.airMass(t.altitudeDeg))*s,c=Ue.coronaScale(r),h=Ue.illuminanceOf(t.magnitude),l=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),c.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(l===this.lunarDiffractionKey)return;this.lunarDiffractionKey=l,this.lunarDiffraction||(this.lunarDiffraction=new yv,this.celestialGroup.add(this.lunarDiffraction.object));const u=Ue.profile(Ue.HAZE_COARSE_MODE),d=Ue.profile(Ue.CLOUD_DROPLETS),f=DC(t.altitudeDeg),p=new Float32Array(Ue.STEPS*3);let m=0;for(let w=0;w<Ue.STEPS;w++){const y=w*3,b=[0,1,2].map(_=>h*f[_]*(a*u[y+_]+c*d[y+_])),S=xs.shown(b,xs.luminanceOf(b),(_,x)=>e.relativeOfLuminance(_,x));p.set(S,y),m=Math.max(m,xs.response(S))}const{x:g,y:v,z:M}=Ve(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:g,y:v,z:M}:void 0,p)}applyAir(){this.scene.fog instanceof pc||(this.scene.fog=new pc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+e,Math.hypot(t-n.x,e-n.y,i-n.z))}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,lt.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.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:ji.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?ji.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:At.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?wP:yP),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 yO(wm),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Of(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(t){if(t.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new Hn,this.celestialGroup.add(this.reentrySystem.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Of(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(t,e,n=>this.cloudTransmission(n),(n,s)=>this.arrivingIlluminance(n,s,1)),this.emitterLights.set("reentries",[],t.map(n=>this.farEmitterOf(n.head,n.magnitude)).filter(n=>n!==void 0)),this.refreshSkyFlare();const i=new Set;for(const n of t){const s=`reentry:${n.reentryId}:${n.fragmentId}`,{x:r,y:a,z:c}=Ve(n.head.altitudeDeg,n.head.azimuthDeg,Qn);this.setGlare(s,r,a,c,this.arrivingIlluminance(n.head,n.magnitude,this.cloudTransmission(n.head)),0,lt.POINT_VEIL_HOLD_DEG),i.add(s)}for(const n of[...this.glareSprites.keys()])n.startsWith("reentry:")&&!i.has(n)&&this.disposeGlare(n);this.render()}setLaunchPlumes(t){t.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new Mi,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(t,this.relativeScale,e=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),e=>this.cloudTransmission(e)),this.render())}pickPlumeAt(t,e){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=this.plumeSystem.pickAt(i,lt.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return n&&this.groundHides(t,e)?void 0:n}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(of*this.camera.fov*Math.PI/180);let s,r=n;const a=new T;for(const[c,h]of this.decorGroups){if(!h.visible||!c.startsWith(Pn.ID_PREFIX))continue;a.copy(h.position).sub(this.camera.position).normalize();const l=a.dot(i);l>r&&(r=l,s=c)}return s&&!this.groundHides(t,e)?s:void 0}pickReentryAt(t,e){if(!this.reentrySystem?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(of*this.camera.fov*Math.PI/180),n=this.reentrySystem.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(of*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}updateCelestialLight(t,e){const i=this.relativeScale,n=t.sun.altitudeDeg>=Ul,s=!n&&t.moon.altitudeDeg>=Ul,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ui)),h=this.siteElevationM+this.observerElevationM;let l=r,u=n||s?pw.directFraction(r.altitudeDeg,h):0;n&&u<=0&&t.moon.altitudeDeg>=Ul&&(l=t.moon,u=pw.directFraction(l.altitudeDeg,h));const d=Math.max(0,Math.sin(Math.max(l.altitudeDeg,0)*ui)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),m=Math.max(0,1/(1+.1125*p)-f),g=[0,0,0];if(n||s){const S=Ue.illuminanceOf(r.magnitude)*i,_=this.air.transmittanceFromSpace(h,r.altitudeDeg);for(let D=0;D<3;D++)g[D]=S*_[D]*m*c,this.cloudBeam[D]=S*_[D];const{x,y:A,z:I}=Ve(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(x,A,I),u>0){const D=Ue.illuminanceOf(l.magnitude)*i,C=l===r?_:this.air.transmittanceFromSpace(h,l.altitudeDeg),N=l===r?f:this.cloudTransmission(l);for(let L=0;L<3;L++)a[L]=D*C[L]*N*u}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),_=e.skyIrradiance,x=[0,1,2].map(I=>_[I]*S+g[I]);this.skyLight.color.setRGB(x[0],x[1],x[2]);const A=te.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(x[0]+a[0]*d),A*(x[1]+a[1]*d),A*(x[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=l===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:M,y:w,z:y}=Ve(l.altitudeDeg,l.azimuthDeg,1);this.lightDirection.set(M,w,y),this.celestialLight.shadow.normalBias=xm*Cr(w/sP,.1,1),this.placeShadowFrustum();const b=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/b,a[1]/b,a[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 i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=cs.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Ue.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=lt.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let h=0;h<3;h++)n[h]=Math.max(0,a*r[h]*s*c-this.sceneSunBeam[h])}}t.traverse(s=>{const r=s.material;if(!(r instanceof er||r instanceof lo)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=lt.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new T(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=h=>{const l=r.dot(h)/i;return(l-Math.round(l))*i},c=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).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 i=e.camera,n=nP;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=cf+5,i.near=this.shadowLightDistanceM-cf,i.far=this.shadowLightDistanceM+cf,i.updateProjectionMatrix(),e.bias=-.004/(2*cf),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(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==lt.CABIN_SKY_SHARE&&(r.envMapIntensity=lt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(iP,Math.max(ma,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,n=i.camera;n.left=-e,n.right=e,n.top=e,n.bottom=-e;const s=Math.max(nh,e*(nh/ma));this.shadowLightDistanceM=Math.max(Qn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-bm/(2*s);const r=e>2*ma?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=ma;shadowLightDistanceM=Qn;shadowUp=new T(0,1,0);shadowAxisX=new T;shadowAxisY=new T;shadowWorld=new T;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*ui,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new T(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Lt.semiSaturation(Lt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new xn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}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 i=Math.max(this.relativeScale,1e-30),n=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:s,y:r,z:a}=Ve(t.altitudeDeg,t.azimuthDeg,1);return{direction:new T(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],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 i=ki.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=At.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return Of(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const n=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const 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.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),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,i=performance.now()+lt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"&&s.kind!=="vehicle"||s.observerSide!==void 0&&Qh(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=vr(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=ut.sizeOf(s),u=Math.max(l.widthM,l.lengthM)/2;Math.hypot(c,h)<u&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<u&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new Xn(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(c=>c.mesh)],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof bs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object,this.reentrySystem?.object].filter(c=>c!==void 0)],n=this.relativeScale,s=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,c=>this.measureSurroundings(c,n,s,r),t?0:Xn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,lt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new wh,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>Ve(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,r,a=>{const c=p=>p.map(m=>m/e),h=this.surroundings,l={up:c(a.up),down:c(a.down)},u=(p,m)=>p.some((g,v)=>Math.abs(g-m[v])>.03*Math.max(Math.abs(g),Math.abs(m[v]),1e-12)),d=!h||u(h.up,l.up)||u(h.down,l.down);d&&(this.surroundings=l),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(lt.adaptingLuminance(Math.exp(a.logAverage)/e,l.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Ul?t.sun:t.moon.altitudeDeg>=Ul?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new or;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?Ve(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??lt.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,s=>{const r={mean:s.mean/t.scale,brightest:s.brightest/t.scale},a=this.frameLight,c=t.atMs,h=a?c-a.atMs:1/0,l=h<0||h>lt.EXPOSURE_JUMP_MS,u=l||h===0&&a?.jumped?1:1-Math.exp(-h/n),d=(m,g)=>m>0&&g>0?m*(g/m)**u:g,f={mean:d(a?.mean??0,r.mean),brightest:d(a?.brightest??0,r.brightest),atMs:c,jumped:l||h===0&&(a?.jumped??!1)};this.frameLight=f;const p=(m,g)=>Math.abs(m-g)>.01*Math.max(m,g);(!a||p(a.mean,f.mean)||p(a.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Ii.uRetinaOn.value=0,this.medium)return;const t=[];for(const a of this.emitterLights.farEmitters){const c=this.screenPointOf(a.direction);!c||Math.abs(c.ndcX)>1.2||Math.abs(c.ndcY)>1.2||t.push({ndcX:c.ndcX,ndcY:c.ndcY,lux:xs.luminanceOf(a.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.y,1),n={width:this.camera.fov*i,height:this.camera.fov},s=this.retina?.atMs;if((s===void 0||this.recordingTimeMs<s||this.recordingTimeMs-s>ce.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new ce,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),n,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new ce,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(Ii.uRetina.value=this.retina.texture,Ii.uRetinaOn.value=1,Ii.uRetinaViewport.value.copy(e))}retinaSize=new it;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const n=i.pose,s=this.historicQuaternion.setFromEuler(this.historicEuler.set((n?.pitchDeg??0)*ui,-(n?.headingDeg??0)*ui,(n?.rollDeg??0)*ui,"YXZ")).invert(),r=n?.fovDeg??this.camera.fov,a=[];for(const c of i.views){const h=this.farEmitterOf(c.head,c.magnitude);if(!h)continue;const l=this.screenPointIn(this.historicDirection.copy(h.direction).applyQuaternion(s),r,e);!l||Math.abs(l.ndcX)>1.2||Math.abs(l.ndcY)>1.2||a.push({ndcX:l.ndcX,ndcY:l.ndcY,lux:xs.luminanceOf(h.lux)})}return a}historicQuaternion=new qn;historicEuler=new sa;historicDirection=new T;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<lt.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 i of t)i.traverse(n=>{n.userData.emissive===!0&&e.push(n)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,FP);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),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 i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ut.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[y1]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Ms.INTERVAL_MS)),Ii.uRodShare.value=this.scatteredSky?.rodShare??0,Ii.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Ii.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),s,r=>{this.lensFlare&&(this.lensFlare.mesh.visible=r?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof bs&&e.userData.pointSource||e instanceof Mt&&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(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Mm),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(ES),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=i}bodyCutOutMaterial=new ls({blending:Mc,blendSrc:Yr,blendDst:Yr,blendSrcAlpha:Yr,blendDstAlpha:Yr,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=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=i}setReferences(t,e){const i=t.map(n=>{const s=this.documentRelative(n.src);return s===n.src?n:{...n,src:s}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=Ie(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-DFM_jZ-Q.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s;for(const[a,c]of this.referenceViews)s.setView(a,c);s.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&s.set(r.references,void 0,r.observerAt),this.render(),s})}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new T)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}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 i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const s=e?this.narrowTo(t,e):t,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse)),a=this.phenomena.furthestM;let c=0;for(const h of this.decorObjects){const l=this.decorGroups.get(h.id);if(!l)continue;const u=h.kind!=="crop"&&this.mayHide(l,t,r,a);lt.markDecorDepth(l,u),u&&c++}c>0&&(t.layers.set(vm),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(y1),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new L0;phenomenaViewProjection=new oe;occluderSphere=new yr;localBounds=new WeakMap;mayHide(t,e,i,n){let s=0;t.traverse(()=>s++);let r=this.localBounds.get(t);if(!r||r.objects!==s){t.updateMatrixWorld(!0);const c=new tn().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new yr).applyMatrix4(new oe().copy(t.matrixWorld).invert()),objects:s},this.localBounds.set(t,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(t.matrixWorld);return a.center.distanceTo(e.position)-a.radius>n?!1:i.intersectsSphere(a)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new it),n=lt.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),s=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-n)),r=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-n)),a=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+n)),c=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+n)),h=this.narrowCamera.copy(t);return h.setViewOffset(i.x,i.y,s,i.y-c,Math.max(1,a-s),Math.max(1,c-r)),h.updateMatrixWorld(),h}narrowCamera=new Nn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new ls({colorWrite:!1,side:_n});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(lt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*ui}static isSolidSurface(t){if(!(t instanceof Mt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==Mn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof Mt))return;e&&lt.isSolidSurface(i)?i.layers.enable(vm):i.layers.disable(vm)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new it),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new vC(e,i)),this.exposureAccumulation.resize(e,i),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 i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+lt.EXPOSURE_BUDGET_MS,s=lt.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,h)=>{c.visible=a[h]})}e.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Ii.uRodShare.value=this.scatteredSky?.rodShare??0,Ii.uHasOverlay.value=1,Ii.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(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(a=>a.visible))return;const i=new Hs,n=new Gs(-1,1,1,-1,0,2),s=lf/(xw*Math.tan(Sw*ui/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new T).sub(this.camera.position).normalize(),h=this.screenPointOf(c);if(!h)continue;const l=new Al(a.material);l.position.set(h.ndcX,h.ndcY,-1),l.scale.set(s/this.camera.aspect,s,1),i.add(l)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,n)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new tn,i=new T,n=this.camera.getWorldDirection(new T),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<lt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,h=-1/0,l=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const g=(m.ndcX+1)/2,v=(1-m.ndcY)/2;c=Math.min(c,g),h=Math.max(h,g),l=Math.min(l,v),u=Math.max(u,v)}c=Math.max(c,0),h=Math.min(h,1),l=Math.max(l,0),u=Math.min(u,1),h>=c&&u>=l&&t.push({x:c,y:l,width:h-c,height:u-l})}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())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new it),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new ou(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),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,Ii.uMediumExposure.value)}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 it);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Zi(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new it);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new Mv(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new it);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Ri(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,n=>{const s=lt.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!s||s.distance>=n-.001||this.mirrors.isMirror(s.object)})}aimStraightAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new it(e,i),this.camera);return}const s=n.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(s.x,s.y,s.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 T)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ri.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*ui);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new T;screenPointQuaternion=new qn;screenPointSize=new it;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 i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;t.uniforms.uResolution.value.set(n,s),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(r=>Math.max(0,r-lt.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=t.uniforms.uLensPosition.value;return{x:s.x,y:s.y,radius:i,flux:[e[0]*n,e[1]*n,e[2]*n]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const n=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(n.x,n.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(mw),this.camera.layers.set(mw),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of Aw)this.isSunOccluded(e[0],e[1])||t++;return t/Aw.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const n=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&n.length===0)return!1;const s=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),r=s.length();if(s.normalize(),e!==0||i!==0){const h=Math.PI/180,l=this.sunOcclusionRightScratch.set(s.z,0,-s.x);l.lengthSq()<1e-9&&l.set(1,0,0),l.normalize();const u=this.sunOcclusionUpScratch.crossVectors(l,s).normalize();s.addScaledVector(l,e*h).addScaledVector(u,i*h).normalize()}if(this.groundBlocks(this.camera.position,s,r)||this.cabinMask.hides(s))return!0;const a=this.cabinMask.any?n.filter(h=>!this.cabinGroups.includes(h)):n;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,s);const c=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(h=>!(h.object.material instanceof Oa));return c!==void 0&&c.distance<r}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 i=e.mesh.getWorldPosition(this.veilTargetScratch),n=e.mesh.material.uniforms.uSourceDeg.value,s=n>.05?lt.VEIL_SAMPLES:lt.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,c]of s)this.isOccludedToward(i,a*n,c*n)||r++;e.share=r/s.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new ms;veilTargetScratch=new T;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const v=t.x+e.x*g-s.position.x,M=t.z+e.z*g-s.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const h=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],l=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(h[1]-h[0]),Math.abs(l[1]-l[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[g,v,M]of[[t.x,e.x,h],[t.z,e.z,l]]){const w=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(g<w||g>y)return!1;continue}const b=(w-g)/v,S=(y-g)/v;d=Math.max(d,Math.min(b,S)),f=Math.min(f,Math.max(b,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const v=d+(f-d)*g/m,M=t.x+e.x*v,w=t.y+e.y*v,y=t.z+e.z*v;if(w<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=rf;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const c=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(h=>lt.isSolidSurface(h.object));c&&(r.occludesSourceIds?.includes(i)?n=n===void 0?c.distance:Math.max(n,c.distance):s=s===void 0?c.distance:Math.min(s,c.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=rP*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([l,u])=>{const d=u.getWorldPosition(new T).sub(i);return{key:l,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),a=this.eclipseDiscs,c=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],h=lt.nearestBody(n,[...r.filter(l=>!a||l.key!=="sun"&&l.key!=="moon"),...c],s);if(h)return this.groundHides(t,e)?void 0:h}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let n,s=1/0,r=1/0,a=!1;for(const c of e){const h=Math.acos(Cr(c.direction.dot(t),-1,1))-c.radiusRad;if(h>i)continue;const l=h<=0,u=s<=0,d=c.inFront===!0;(l!==u?l:l?d!==a?d:c.radiusRad<r:h<s)&&(n=c.key,s=h,r=c.radiusRad,a=d)}return n}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=eP*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?lt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let h,l=1/0;const u=new tn,d=new T;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new T).length()/2,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const v=Math.acos(Math.min(1,m.normalize().dot(n))),M=Math.atan(p/g);if(M>r){const w=this.raycaster.intersectObject(f,!0)[0];if(!w||c!==void 0&&c<w.distance)continue}else if(v>r)continue;M<l&&(l=M,h=f.name.slice(5))}return h}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(of*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const c=a.direction.dot(i);c>r&&(r=c,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(t,e)?void 0:s}groundHides(t,e){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,1/0,rf)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const c=this.bodyCornerScratch.set(a&1?e.max.x:e.min.x,a&2?e.max.y:e.min.y,a&4?e.max.z:e.min.z),h=this.screenPointOf(c.sub(this.camera.position).normalize());if(!h)return;i=Math.min(i,h.ndcX),s=Math.max(s,h.ndcX),n=Math.min(n,h.ndcY),r=Math.max(r,h.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new tn;bodyCornerScratch=new T;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;const i=this.bodyBoxScratch.setFromObject(e);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-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),l=this.screenPointOf(h.sub(this.camera.position).normalize());if(!l)return;n=Math.min(n,l.ndcX),r=Math.max(r,l.ndcX),s=Math.min(s,l.ndcY),a=Math.max(a,l.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,n=0){const s=this.decorGroups.get(t);if(!s)return;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(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*ui/2):0}decorGrabHeightAt(t,e,i){const n=this.decorGroups.get(t);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),c=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return c?Math.min(Math.max(c.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new wa;decorHitScratch=new T;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&(s.transparent&&s.opacity<lt.SEE_THROUGH_BELOW||s instanceof Oa))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=lt.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new ll().copy(n).applyMatrix4(new oe().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new T(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,lt.RAILWAY_PICK_ABOVE_M))return;const c=lt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-lt.RAILWAY_GROUND_MARGIN_M,rf))return;const h=i.group.worldToLocal(c.point.clone()),l=i.lineAt(h.x,h.z);if(!l)return;const u=i.contactHeightM(l);return{line:l,distanceM:c.distance,...u!==void 0?{contactM:u}:{}}}pickBeamAt(t,e){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,s=i.pickAt(n.origin,n.direction,lt.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,rf))return;const r=lt.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<s.distanceM))return s}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const 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())ut.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 i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new T;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<lt.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 nn(sf,32,16),i=e.attributes.position,n=e.getAttribute("color")??new pe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=Gx(i.getX(r),i.getY(r),i.getZ(r)),h=TC(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,h[0],h[1],h[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new ls({vertexColors:!0,side:Pi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Mt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=gw(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new Z1(this.groundRadius,48),i=new er({color:new rt(ym,ym,ym),fog:!0});pc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Mt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${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(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=Ve(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-Pe.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*cP);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Pe.iceAlphaAt(i,hf,r,this.cloudFieldOffset)*hP),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<Nf){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:c}=Ve(e.altitudeDeg,e.azimuthDeg,Qn),h=this.cloudTransmission(e),l=this.arrivingIlluminance(e,s,h),u=lt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/Qn)**2,p=[0,1,2].map(g=>u[g]*l[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(lt.BRIGHTEST_RELATIVE,g));d instanceof Mt||(this.disposeMesh(d),d=new Mt(new nn(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(m[0],m[1],m[2]),d.scale.setScalar(i)}else{if(!(d instanceof bs)){this.disposeMesh(d);const m=new me;m.setAttribute("position",new fe(new Float32Array(3),3)),m.setAttribute("color",new fe(new Float32Array(3),3)),d=new bs(m,Nt.material(uc[uc.length-1].size,!1)),Nt.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),p=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*l[0]*p,u[1]*l[1]*p,u[2]*l[2]*p),f.needsUpdate=!0}if(d.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=l),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,l,i/Qn*(180/Math.PI),lt.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,c*f),this.lensFlare||(this.lensFlare=MO(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<Nf){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ve(t.altitudeDeg,t.azimuthDeg,Qn),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),h=t.radiusDeg??Gr.MEAN_RADIUS_DEG,l=Qn*Math.tan(h*ui),u=Math.max(Cr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(l/Qn)**2,d=new rt(...c.map(m=>Math.min(lt.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(Cr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Al?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=Gw(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Al(new Rf({map:Gw(t.phase),color:d,fog:!1,blending:Mn,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(l*2,l*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,l),this.setGlare(i,n,s,r,c,h)}bentLight(t,e,i=aP){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return lt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new rt;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,Nt.CONE_SOLID_ANGLE/e)}pointScratch=new it;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=Ue.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=xs.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,i,n,s){let r=this.hitAreas.get(t);if(!r){const c=new Rf({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Al(c),this.celestialGroup.add(r),this.hitAreas.set(t,r)}r.position.set(e,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,n,s,r,a=0){if(gn.radiusDeg(gn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new gn(`veil:${t}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(t,c)),c.shine({x:e,y:i,z:n},s,r,a)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=sc(t.magnitude,e),s=am(n);this.cometKey=i,this.setBodyMesh(i,t.position,Sm*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new Ls(Qn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Gi,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:hf},0);return}const s=this.lowerCloudCover(),r=be.deckLitUntilDeg(be.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?ue.SUN_MAGNITUDE:e.magnitude),h=be.strength(i,s,a.altitudeDeg,r)*c.scale,{x:l,y:u,z:d}=Ve(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:l,y:u,z:d},a.altitudeDeg,h,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??hf},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??XS,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new nc,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=t.altitudeDeg>0,s=n?t:e,r=this.lowerCloudCover(),a=this.bentLight(s,n?ue.SUN_MAGNITUDE:e.magnitude,oP),c=Ns.strength(i,r,s.altitudeDeg)*a.scale;if(c<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:h,y:l,z:u}=Ve(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:h,y:l,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new so,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=hr.galactic(i,n),r=lt.directionOf(s.centre),a=lt.directionOf(s.rotation),c=lt.directionOf(s.pole),h=new le().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),l=lt.directionOf(hr.eclipticPole(i,n)),u=lt.directionOf(t.sun),d=u.clone().addScaledVector(l,-u.dot(l)).normalize();this.skyGlow.update({galactic:h,eclipticPole:l,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:lt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new T(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ve(t.altitudeDeg,t.azimuthDeg,1);return new T(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=sc(n.magnitude,e),a=am(r);this.setBodyMesh(s,n.position,Sm*(.5+.5*r),new rt(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=sc(n.magnitude,e),r=am(s),a=GP[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),h=Sm*(.5+.5*s);this.setBodyMesh(n.body,n.position,h,c,n.magnitude)}for(const n of[...this.bodyMeshes.keys()])i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=t,r=new fr(n,s),a=Pm(1337),c=[],h=this.siteElevationM+this.observerElevationM;for(let l=0;l<i.count;l++){const u=i.mag[l];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[l],i.dec[l]);if(d<Mw)continue;const{x:p,y:m,z:g}=Ve(d,f,wm);c.push({x:p,y:m,z:g,brightness:sc(u,e),illuminance:this.air.transmittanceFromSpace(h,d).map(v=>v*Ue.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const l of J6){if(l.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(l.raHours,l.decDeg);if(u<Mw)continue;const{x:f,y:p,z:m}=Ve(u,d,wm);this.namedStars.push({star:l,direction:new T(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=uc.map((l,u)=>{const d=c.filter(b=>H0(b.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),m=new Float32Array(d.length*3),g=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((b,S)=>{f[S*3]=b.x,f[S*3+1]=b.y,f[S*3+2]=b.z,p[S]=b.brightness,m.set(b.illuminance,S*3),g[S]=b.phase,v[S]=b.speedFactor});const M=new me;M.setAttribute("position",new fe(f,3)),M.setAttribute("seed",new fe(g.map(b=>b/(2*Math.PI)),1));const w=new fe(new Float32Array(d.length*3),3);M.setAttribute("color",w);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new bs(M,Nt.material(l.size)),Nt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:p,illuminance:m,phase:g,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Nt.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const i of this.starTiers){const n=i.colorAttribute.array;for(let s=0;s<i.brightness.length;s++)n[s*3]=i.illuminance[s*3]*e,n[s*3+1]=i.illuminance[s*3+1]*e,n[s*3+2]=i.illuminance[s*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Fh(this.celestialGroup,Em,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new rt(Go[0]+(Tm[0]-Go[0])*e,Go[1]+(Tm[1]-Go[1])*e,Go[2]+(Tm[2]-Go[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Xg(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=$g(Em);this.cloudMesh=new Mt(r,n),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:i}=Xg(new rt(...Go),t,hf,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Mt($g(Em*1.04),e),this.cirrusMesh.renderOrder=_w-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 i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?Fh.deckOrder(!0,0,1):_w}cloudLayerOffset(){const e=((this.weather.cloudBaseM??b1)-this.observerElevationM)*Am;return Math.sign(e||1)*Math.max(Math.abs(e),EP)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*Om*this.relativeScale/Math.PI,h=new rt(e[0]+Tr.r*c,e[1]+Tr.g*c,e[2]+Tr.b*c);this.layeredClouds?.setLighting(n.clone(),new rt(s,r,a),h,h);const l=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*l,r*l,a*l),u.ambientColor.value.copy(h)}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 OP(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,Dm],[this.rainSplashSystem?.points,Vo],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Rm[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=Dw(Cm(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=Rm[t],i=e.poolSize,n=Pm(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),l=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let w=0;w<i;w++){const y=n()*Math.PI*2,b=n()*e.radiusM;s[w*3]=Math.cos(y)*b,s[w*3+1]=oh+n()*(e.topYM-oh),s[w*3+2]=Math.sin(y)*b,r[w]=n()*Math.PI*2,a[w]=.7+n()*.6,c[w]=.6+n()*.8,h[w]=.4+n()*1.2}const m=new me;m.setAttribute("position",new fe(s,3)),m.setDrawRange(0,this.precipitationCount(i));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 rt(...this.baseFogColor)},uTexture:{value:VP(t)},uNearFocusDistance:{value:Nw},uHazeDistance:{value:e.radiusM*Lw}},v=new Te({uniforms:g,vertexShader:qP,fragmentShader:ZP,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const M=new bs(m,v);M.renderOrder=_m,this.scene.add(M),this.precipitationPoints=M,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=h,this.precipitationBounceRemaining=l,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const n=Rm[i];if(this.precipitationUniforms?.uColor.value.copy(lt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*ui,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,h=this.precipitationPhase,l=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,m=this.precipitationBounceDuration,g=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,M=i==="snow"&&u&&d,w=i==="hail"&&f&&p&&m&&g&&v;for(let y=0,b=0;y<c.length;y+=3,b++){if(w&&f[b]>0){if(f[b]-=e,f[b]<=0){const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(x)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(x)*A,f[b]=0}else{const x=1-f[b]/m[b];c[y+1]=oh+Math.sin(Math.PI*x)*p[b],c[y]=uf(c[y]+(r+g[b])*e,n.radiusM),c[y+2]=uf(c[y+2]+(a+v[b])*e,n.radiusM)}continue}let S=0,_=0;if(M){const x=NP*u[b],A=LP*d[b];S=Math.sin(t*x*Math.PI*2+h[b])*A,_=Math.sin(t*x*Math.PI*2+h[b]+Math.PI/2)*A}if(c[y]+=(r+S)*e,c[y+1]-=n.fallSpeedMPerS*l[b]*e,c[y+2]+=(a+_)*e,c[y]=uf(c[y],n.radiusM),c[y+2]=uf(c[y+2],n.radiusM),c[y+1]<oh){if(w){p[b]=Bw*(.2+Math.random()*1.6),m[b]=kP*(.5+Math.random()),f[b]=m[b];const I=Math.random()*Math.PI*2,D=UP*(p[b]/Bw);g[b]=Math.cos(I)*D,v[b]=Math.sin(I)*D,c[y+1]=oh;continue}const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(x)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(x)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=Cm(this.weather.precipitationIntensity);this.rainSystem=mO({count:Dm,radiusM:Fl,heightM:_P,bottomYM:Tw,overallSpeed:TP,color:Iw.clone(),opacity:.85,visibleCount:this.precipitationCount(Dm),speedStreak:Dw(t),pixelSize:Uw,seed:9001,nearFocusDistanceM:Nw,hazeDistanceM:Fl*Lw,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=_m,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=Pm(4242),e=new Float32Array(Vo*3),i=new Float32Array(Vo),n=new Float32Array(Vo),s=new Float32Array(Vo);for(let l=0;l<Vo;l++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Fl;e[l*3]=Math.cos(u)*d,e[l*3+1]=Tw,e[l*3+2]=Math.sin(u)*d,n[l]=Hw(Cw,Ow),i[l]=t()*n[l],s[l]=i[l]/n[l]}const r=new me;r.setAttribute("position",new fe(e,3));const a=new fe(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Vo));const c=new Te({uniforms:{uMaxSize:{value:CP},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Pw.clone()},uTexture:{value:$P()}},vertexShader:YP,fragmentShader:KP,transparent:!0,depthWrite:!1}),h=new bs(r,c);h.renderOrder=_m,this.scene.add(h),this.rainSplashSystem={points:h,positions:e,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*ui;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-Cm(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.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(lt.litBySky(Iw,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(lt.litBySky(Pw,this.baseFogColor));const n=this.weather.windDirectionDeg*ui,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Fl,c=l=>(l%(a*2)+a*3)%(a*2)-a;e.uniforms.uWindOffset.value.set(c(e.uniforms.uWindOffset.value.x+s*t),c(e.uniforms.uWindOffset.value.y+r*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const h=Math.abs(this.rainCameraDirection.y);if(Math.abs(h-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=h;const l=Fw+(1-Fw)*(1-h),u=zw+(1-zw)*(1-h);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=Uw*l*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=e,a=r.array;for(let c=0,h=0;c<i.length;c+=3,h++){if(n[h]+=t,n[h]>=s[h]){const l=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Fl;i[c]=Math.cos(l)*u,i[c+2]=Math.sin(l)*u,s[h]=Hw(Cw,Ow),n[h]=0}a[h]=n[h]/s[h]}e.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>t)break;const h=dn.brightnessAt(c,t);h>i&&(e=c,i=h)}const n=e?Math.min(1,Math.max(.1,(BP/e.distanceM)**2)):0,s=i*n*(e?.cloudToGround?1:.6);if(s===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,h=s*Om*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Tr.r*h,this.airlight[1]+Tr.g*h,this.airlight[2]+Tr.b*h)}const r=this.skyMesh?.material?.color;if(r){const c=s*HP;r.setRGB(1+c*Tr.r,1+c*Tr.g,1+c*Tr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Om*this.relativeScale,e){const{x:c,y:h,z:l}=Ve(25,e.azimuthDeg,Qn);this.lightningLight.position.set(c,h,l)}this.lightningBolt||(this.lightningBolt=new ro(Qn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=MP.map(t=>{const e=fc.point(t,this.compassPoints),i=new Rf({map:JP(e),depthTest:!1,fog:!1}),n=new Al(i),{x:s,y:r,z:a}=Ve(0,t,xw);return n.position.set(s,r,a),n.scale.set(lf,lf,1),n.renderOrder=bP,n.layers.set(Mm),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=Sw*Math.PI/360,i=lf*Math.tan(t)/Math.tan(e);for(const n of this.compassSprites)n.scale.set(i,i,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 i of Array.isArray(e)?e:[e]){const n=i.map;n&&n.dispose(),i.dispose()}}}const ui=Math.PI/180;function Cr(o,t,e){return Math.max(t,Math.min(e,o))}function Hw(o,t){return o+Math.random()*(t-o)}function uf(o,t){return(o%(t*2)+t*3)%(t*2)-t}let df,ff;function VP(o){switch(o){case"snow":return WP();case"hail":return XP()}}function WP(){if(df)return df;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),df=new No(t),df}function XP(){if(ff)return ff;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),ff=new No(t),ff}let pf;function $P(){if(pf)return pf;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),pf=new No(t),pf}const YP=`
9157
9157
  uniform float uMaxSize;
9158
9158
  uniform float uScale;
9159
9159
  attribute float aLife;
@@ -9218,11 +9218,11 @@ void main() {
9218
9218
  float blur = max(vNearBlur, vHaze);
9219
9219
  gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
9220
9220
  }
9221
- `;function Gw(o){const e=document.createElement("canvas");e.width=128,e.height=128;const i=e.getContext("2d"),n=128/2-2,s=128/2,r=128/2,a="#010101",c="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const h=Cr(o.illuminatedFraction,0,1),l=o.phaseFraction<.5,u=n*Math.abs(1-2*h),d=h<.5;return i.save(),i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.clip(),i.fillStyle=c,i.beginPath(),l?(i.arc(s,r,n,-Math.PI/2,Math.PI/2,!1),i.ellipse(s,r,u,n,0,Math.PI/2,-Math.PI/2,d)):(i.arc(s,r,n,Math.PI/2,-Math.PI/2,!1),i.ellipse(s,r,u,n,0,-Math.PI/2,Math.PI/2,d)),i.fill(),i.restore(),new No(e)}function JP(o){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(o,64,68),new No(t)}function Pm(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}class M0{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:`${M0.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 i=this.ensureScene();i.interpretation!==this.source.interpretation&&(i.interpretation=this.source.interpretation),i.compareAccount!==this.source.compareAccount&&(i.compareAccount=this.source.compareAccount),i.showAt(t);for(let n=0;n<M0.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(s=>requestAnimationFrame(()=>s())),!this.wanted);n++)if(i.snapshotTo(e)){e.dataset.ready="true";break}}}finally{this.pumping=!1}}}class fi{static held=new Map;static loaded=new Map;static generation=0;static address(t,e){const i=e??(typeof location>"u"?"http://localhost/":location.href);return new URL(t,i).href}static hold(t,e){fi.held.set(t,e),fi.loaded.delete(t),fi.generation++}static release(){if(fi.held.size!==0){for(const t of fi.held.keys())fi.loaded.delete(t);fi.held.clear(),fi.generation++}}static bytes(t,e=fetch.bind(globalThis)){const i=fi.held.get(t);if(i)return Promise.resolve(i);let n=fi.loaded.get(t);return n||(n=e(t).then(async s=>{if(!s.ok)throw new Error(`Frozen data not found (${s.status}): ${t}`);return new Uint8Array(await s.arrayBuffer())}),fi.loaded.set(t,n),n.catch(()=>fi.loaded.delete(t))),n}static async json(t){return JSON.parse(new TextDecoder().decode(await fi.bytes(t)))}static async zip(t){const e=await fi.bytes(t),{unzipSync:i}=await De(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);return i(e)}}class ia{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 i,n=1/0;for(const s of this.list){if(s.far)continue;const{x:r,z:a}=de(s.lat,s.lng,t,e),c=Math.hypot(r,a);c<n&&(n=c,i=s)}return i}farRingOf(t,e){return this.list.find(i=>i.far&&Math.abs(i.lat-t)<=ia.SAME_BOUNDS_DEG&&Math.abs(i.lng-e)<=ia.SAME_BOUNDS_DEG)}static boundsOf(t){return ru(t.lat,t.lng,t.radiusM)}static sameBounds(t,e){const i=(n,s)=>Math.abs(n-s)<=ia.SAME_BOUNDS_DEG;return i(t.north,e.north)&&i(t.south,e.south)&&i(t.east,e.east)&&i(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((i,n)=>i.lat===e[n].lat&&i.lng===e[n].lng&&i.radiusM===e[n].radiusM&&i.far===e[n].far)}}class y0{static async encode(t){const{zipSync:e,strToU8:i}=await De(async()=>{const{zipSync:r,strToU8:a}=await import("./browser-_Ncw3Jhn.js");return{zipSync:r,strToU8:a}},[],import.meta.url),n={},s={version:1,takenOn:t.takenOn,attribution:t.attribution,patches:t.patches.map((r,a)=>{const c=`${a}.f32`;return n[c]=y0.byPlane(r.grid.heights),{lat:r.lat,lng:r.lng,radiusM:r.radiusM,...r.far?{far:r.far}:{},bounds:r.grid.bounds,width:r.grid.width,height:r.grid.height,file:c}})};return n["index.json"]=i(JSON.stringify(s,null,1)),e(n,{level:9})}static decode(t){const e=t["index.json"];if(!e)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(e));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(n=>{const s=t[n.file];if(!s||s.length!==n.width*n.height*4)return[];const r={heights:y0.fromPlanes(s),width:n.width,height:n.height,bounds:n.bounds};return[{lat:n.lat,lng:n.lng,radiusM:n.radiusM,...n.far?{far:n.far}:{},grid:r}]})}}static byPlane(t){const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=t.length,n=new Uint8Array(e.length);for(let s=0;s<i;s++)for(let r=0;r<4;r++)n[r*i+s]=e[s*4+r];return n}static fromPlanes(t){const e=t.length/4,i=new Uint8Array(t.length);for(let n=0;n<e;n++)for(let s=0;s<4;s++)i[n*4+s]=t[s*e+n];return new Float32Array(i.buffer)}}class wv{constructor(t){this.annex=t}async getElevationGrid(t,e,i){const{patches:n}=await this.annex,s=n.find(a=>ia.sameBounds(ia.boundsOf(a),t));if(s)return{...s.grid,heights:new Float32Array(s.grid.heights)};const r=n.find(a=>ia.contains(a.grid.bounds,t));if(r)return wv.resample(r.grid,t,e);throw new Error("The frozen relief does not hold this ground")}static resample(t,e,i){const{width:n,height:s}=i,r=new Float32Array(n*s),a=t.bounds.east-t.bounds.west,c=t.bounds.north-t.bounds.south;for(let h=0;h<s;h++){const l=e.north-(e.north-e.south)*(s>1?h/(s-1):0),u=Math.min(t.height-1,Math.max(0,(t.bounds.north-l)/c*(t.height-1))),d=Math.floor(u),f=Math.min(t.height-1,d+1),p=u-d;for(let m=0;m<n;m++){const g=e.west+(e.east-e.west)*(n>1?m/(n-1):0),v=Math.min(t.width-1,Math.max(0,(g-t.bounds.west)/a*(t.width-1))),M=Math.floor(v),w=Math.min(t.width-1,M+1),y=v-M,b=(x,A)=>t.heights[x*t.width+A],S=b(d,M)*(1-y)+b(d,w)*y,_=b(f,M)*(1-y)+b(f,w)*y;r[h*n+m]=S*(1-p)+_*p}}return{heights:r,width:n,height:s,bounds:e}}}function AS(o,t){return o.find(e=>e.id===t)??o[0]}class jP{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 Cb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const _S=[{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:o=>new Ob({fetchImpl:o})},{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:o=>new jP({fetchImpl:o})}];class Vw{static async encode(t){const{zipSync:e,strToU8:i}=await De(async()=>{const{zipSync:c,strToU8:h}=await import("./browser-_Ncw3Jhn.js");return{zipSync:c,strToU8:h}},[],import.meta.url),n={},s={};let r=0;for(const[c,h]of t.tiles){const l=`tiles/${r++}`;n[l]=h.bytes,s[c]={file:l,type:h.type}}const a={version:1,takenOn:t.takenOn,source:t.source,attribution:t.attribution,patches:t.patches,map:t.map,tiles:s};return n["index.json"]=i(JSON.stringify(a,null,1)),e(n,{level:0})}static decode(t){const e=t["index.json"];if(!e)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(e)),n=new Map;for(const[s,{file:r,type:a}]of Object.entries(i.tiles)){const c=t[r];c&&n.set(s,{bytes:c,type:a})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:n}}}class q0{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(n=>(this.attributionRead=n.attribution,AS(_S,n.source).create(q0.fetchFrom(n.tiles)))))).getImageryTexture(t,e)}static fetchFrom(t){return async e=>{const i=typeof e=="string"?e:e instanceof URL?e.href:e.url,n=t.get(i);return n?new Response(n.bytes,{status:200,headers:{"content-type":n.type}}):new Response(null,{status:404})}}}class QP{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,AS(_S,t.source).create(q0.fetchFrom(t.tiles)).getImageryTexture(t.map.bounds,{width:t.map.pixels,height:t.map.pixels})})}}class bv{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(i=>ia.sameBounds(ia.boundsOf(i),t))?.items??[]}}class tN{constructor(t,e=""){this.attributionStated=e,this.reader=new bv(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 eN{constructor(t,e=""){this.attributionStated=e,this.reader=new bv(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(t){return this.reader.itemsFor(t)}}class iN{constructor(t,e=""){this.attributionStated=e,this.reader=new bv(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 w0{static providers(t,e,i){const n=f=>Ch.held(t,f),s=n("relief"),r=n("imagery"),a=n("roads"),c=n("water"),h=n("railways");if(!s&&!r&&!a&&!c&&!h)return i;const l=f=>fi.address(f.src,e),u=[],d={...i};if(s){const f=fi.zip(l(s)).then(p=>y0.decode(p));d.elevation=new wv(f),u.push(f.then(p=>p.patches))}if(r){const f=fi.zip(l(r)).then(p=>Vw.decode(p));d.imagery=new q0(f,r.attribution),u.push(f.then(p=>p.patches))}if(a){const f=fi.json(l(a));d.roads=new tN(f,a.attribution),u.push(f.then(p=>p.patches))}if(c){const f=fi.json(l(c));d.water=new eN(f,c.attribution),u.push(f.then(p=>p.patches))}if(h){const f=fi.json(l(h));d.railways=new iN(f,h.attribution),u.push(f.then(p=>p.patches))}return d.patches=new ia(w0.firstRead(u)),d}static map(t,e){const i=fi.zip(fi.address(t.src,e)).then(n=>Vw.decode(n));return new QP(i,t.attribution)}static async firstRead(t){for(const e of t)try{const i=await e;if(i.length>0)return i.map(({lat:n,lng:s,radiusM:r,far:a})=>({lat:n,lng:s,radiusM:r,...a?{far:a}:{}}))}catch{}return[]}}class Ah{constructor(t){this.annex=t}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(t,e,i){let n;try{n=await this.annex}catch{return{status:"failed"}}const s=c=>Math.abs(c.lat-t.lat)<=Ah.SAME_PLACE_DEG&&Math.abs(c.lng-t.lng)<=Ah.SAME_PLACE_DEG,a=n.answers.find(c=>s(c)&&Math.abs(c.startMs-e)<=Ah.SAME_TIME_MS&&Math.abs(c.endMs-i)<=Ah.SAME_TIME_MS)??n.answers.find(c=>c.startMs<=e&&c.endMs>=i);return a?a.answer:{status:"failed"}}}const Nm=7.5,Lm=9;class Or{static cache=new Map;static load(t){let e=Or.cache.get(t);return e||(e=fetch(t).then(i=>i.arrayBuffer()).then(i=>Or.parse(i)),Or.cache.set(t,e)),e}static upTo(t,e){const i=t.filter((r,a)=>a===0||t[a-1].magnitudeLimit<e);if(i.length<=1)return Or.load(t[0].url);const n=i.map(r=>r.url).join(`
9222
- `);let s=Or.cache.get(n);return s||(s=Promise.all(i.map(r=>Or.load(r.url))).then(r=>r.reduce((a,c)=>Or.concat(a,c))),Or.cache.set(n,s)),s}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(n,s)=>{const r=new Float32Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),r};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class ii{constructor(t){if(this.heights=t,t.length!==ii.WIDTH*ii.HEIGHT)throw new Error(`a lunar relief has ${ii.WIDTH*ii.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*ii.SAMPLES_PER_DEGREE;static HEIGHT=180*ii.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=ii.SAMPLES_PER_DEGREE,n=(e%360+360)%360*i-.5,s=(90-t)*i-.5,r=Math.floor(n),a=Math.floor(s),c=n-r,h=s-a,l=(f,p)=>{const m=(f%ii.WIDTH+ii.WIDTH)%ii.WIDTH,g=Math.min(ii.HEIGHT-1,Math.max(0,p));return this.heights[g*ii.WIDTH+m]},u=l(r,a)*(1-c)+l(r+1,a)*c,d=l(r,a+1)*(1-c)+l(r+1,a+1)*c;return(u*(1-h)+d*h)*ii.UNIT_KM}static inBand(t,e){const i=Math.PI/180,n=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return n>=ii.BAND_FROM_DEG&&n<=ii.BAND_TO_DEG}static withBump(t,e,i,n=.4){const s=new Int8Array(ii.WIDTH*ii.HEIGHT),r=ii.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),c=Math.floor(e*r),h=Math.floor((90-t)*r);for(let l=-a;l<=a;l++)for(let u=-a;u<=a;u++)Math.hypot(u,l)<=a&&(s[(h+l)*ii.WIDTH+(c+u+ii.WIDTH)%ii.WIDTH]=Math.round(i/ii.UNIT_KM));return new ii(s)}static smooth(){return new ii(new Int8Array(ii.WIDTH*ii.HEIGHT))}}class qs{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,n=qs.SAMPLES){const{s,u:r,w:a,distanceKm:c}=qs.frame(t,e),h=Math.PI/180,l=new Float32Array(n),u=ii.REFERENCE_RADIUS_KM;for(let d=0;d<n;d++){const f=d/n*2*Math.PI,p=Math.cos(f),m=Math.sin(f),g=p*r[0]+m*a[0],v=p*r[1]+m*a[1],M=p*r[2]+m*a[2];let w=0;for(let y=qs.SEARCH_FROM_DEG;y<=qs.SEARCH_TO_DEG;y+=qs.SEARCH_STEP_DEG){const b=Math.cos(y*h),S=Math.sin(y*h),_=b*s[0]+S*g,x=b*s[1]+S*v,A=b*s[2]+S*M,I=Math.asin(Math.max(-1,Math.min(1,A)))/h,D=Math.atan2(x,_)/h,C=u+i.heightKm(I,D),N=Math.atan2(C*S,c-C*b);N>w&&(w=N)}l[d]=w/h}return{radiusDeg:l,meanRadiusDeg:Math.asin(u/c)/h}}static frame(t,e){const i=new Na(e.lat,e.lng,e.elevationM),n=La(t),s=s1(t,i,!1),r=new ze(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*qs.AU_KM,c=qs.bodyFixed(t),h=c(r),l=Math.hypot(h[0],h[1],h[2]),u=[h[0]/l,h[1]/l,h[2]/l],d=I6(t,i),f=pv(d),p=Ca(d,new ze(-r.x,-r.y,-r.z,n.t)),m=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),g=Math.atan2(-p.y,p.x),v=new ze(-Math.sin(m)*Math.cos(g),Math.sin(m)*Math.sin(g),Math.cos(m),n.t),M=new ze(-Math.sin(g),-Math.cos(g),0,n.t);return{s:u,u:c(Ca(f,v)),w:c(Ca(f,M)),distanceKm:a}}static surfacePoint(t,e,i,n){const{s,u:r,w:a}=qs.frame(t,e),c=Math.PI/180,h=[0,1,2].map(u=>Math.cos(i*c)*r[u]+Math.sin(i*c)*a[u]),l=[0,1,2].map(u=>Math.cos(n*c)*s[u]+Math.sin(n*c)*h[u]);return{latDeg:Math.asin(l[2])/c,lonDeg:Math.atan2(l[1],l[0])/c}}static radiusAt(t,e){const i=t.radiusDeg.length,n=(e/360*i%i+i)%i,s=Math.floor(n),r=n-s;return t.radiusDeg[s]*(1-r)+t.radiusDeg[(s+1)%i]*r}static uncoveredFraction(t,e,i){const n=t.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const c=a/n*2*Math.PI,h=Math.cos(c),l=Math.sin(c),u=h*i.upDeg+l*i.rightDeg,d=u*u-s+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const m=Math.max(0,u-f),g=Math.max(m,t.radiusDeg[a]);p>g&&(r+=.5*(p*p-g*g))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=X6(ft.Moon,t),i=Math.PI/180,n=e.ra*15*i,s=e.dec*i,r=e.spin*i,a=(h,[l,u,d])=>[Math.cos(h)*l+Math.sin(h)*u,-Math.sin(h)*l+Math.cos(h)*u,d],c=(h,[l,u,d])=>[l,Math.cos(h)*u+Math.sin(h)*d,-Math.sin(h)*u+Math.cos(h)*d];return h=>a(r,c(Math.PI/2-s,a(Math.PI/2+n,[h.x,h.y,h.z])))}static subObserverPoint(t,e){const i=new Na(e.lat,e.lng,e.elevationM),n=La(t),s=s1(t,i,!1),r=qs.bodyFixed(t)(new ze(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class uu{static cache=new Map;static load(t){let e=uu.cache.get(t);return e||(e=uu.fetchRelief(t).catch(()=>{}),uu.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new ii(new Int8Array(i.buffer,i.byteOffset,i.length))}}class b0{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=b0.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=b0.MATRICES[String(t.type)];if(!e)return Rs.NONE;const i=Number(t.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((r,a)=>Rs.IDENTITY[a]+(r-Rs.IDENTITY[a])*n),contrastGain:1}}}class xv{static ID="fatigue";id=xv.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return Rs.NONE}}class qo{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=qo.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:qo.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(qo.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return Rs.NONE;const n=i/qo.MEASURED_LEVEL*qo.MEASURED_LOSS_DB;return{colorMatrix:Rs.IDENTITY,contrastGain:10**(-n/20)}}}class du{static ALL=[new b0,new qo,new xv];static byId(t){return du.ALL.find(e=>e.id===t)}static perceptionOf(t){return du.ALL.reduce((e,i)=>Rs.combine(e,i.perceive(t?.[i.id]??{})),Rs.NONE)}static compact(t){const e={};for(const i of du.ALL){const n=t[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(e[i.id]=s)}return Object.keys(e).length>0?e:void 0}}class x0{constructor(t){this.names=t}body(t,e){return this.names?.bodies[t]??e}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,e){return this.names?.decorKinds[t]??e}point(t){return fc.point(t,this.names?.compassPoints)}towards(t){return fc.towards(t,this.names)}}class dr{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??dr.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,n){const{line:s}=t,r=[];s.name&&r.push(dr.kind(s,e).toLocaleLowerCase(n)),r.push(s.tracks>1?e.tracks.replace("{count}",String(s.tracks)):e.singleTrack);const a=s.voltageV?dr.voltage(s.voltageV,n):void 0;if(t.contactM!==void 0){const c=t.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?e.overheadVoltage.replace("{voltage}",a):e.overhead).replace("{height}",c))}else s.electrification==="third_rail"?r.push(a?e.thirdRailVoltage.replace("{voltage}",a):e.thirdRail):s.electrification==="none"&&r.push(e.notElectrified);return s.gaugeMm===dr.METRE_GAUGE_MM?r.push(e.metreGauge):s.gaugeMm!==dr.STANDARD_GAUGE_MM&&r.push(e.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(e.distance.replace("{distance}",i(t.distanceM))),s.services?.length?`${dr.name(s,e)}; ${r.join(", ")}`:`${dr.name(s,e)} — ${r.join(", ")}`}}class fu{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,i=!0){const n=fu.resolve(t,e);if(this.url=n,!n||!i){this.release();return}this.element.src=n,this.element.hidden=!1;const s=this.shown;this.shown=!0,s||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===fu.PUBLISHED_ORIGIN&&fu.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.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")}}const nN={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},sN=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,rN=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Ww=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,aN=20,oN=1;class _h{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(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("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}hc.unlock(this.context)}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const n=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=n==="hail"?Math.min(1,e*1.3+.2):n==="rain"?e:0,n!==this.ambientKey){this.ambientKey=n;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,n!=="none"&&this.startLoop(sN,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,c=>{this.ambientSource=c?.source,this.ambientGain=c?.gain,c&&(c.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/aN,1);const s=i>oN;if(s!==this.windActive){this.windActive=s;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(rN,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,c=>{this.windSource=c?.source,this.windGain=c?.gain,c&&(c.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:i,windSpeed:n}=this.requested;this.setAmbient(e,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(Ww,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const i=Math.min(1,Math.max(0,t)),n=e.createBufferSource();n.buffer=this.crackBuffer(e);const s=e.createBiquadFilter();s.type="lowpass",s.frequency.value=_h.CRACK_CUTOFF_HZ;const r=e.createGain();r.gain.value=i,n.connect(s).connect(r).connect(this.output(e)),n.start(),this.playOneShot(Ww,i,_h.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*_h.CRACK_DECAY_S*6),i=t.createBuffer(1,e,t.sampleRate),n=i.getChannelData(0);for(let s=0;s<e;s++){const r=s/t.sampleRate;n[s]=(Math.random()*2-1)*Math.min(1,r/.005)*Math.exp(-r/_h.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,n){if(e!==i()){t?.source.stop();return}n(t)}async startLoop(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=e,s.connect(r).connect(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(t,e,i=1){const n=this.context;if(n)try{const s=await this.getBuffer(t),r=n.createBufferSource();r.buffer=s,r.playbackRate.value=i;const a=n.createGain();a.gain.value=e,r.connect(a).connect(this.output(n)),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}class ya{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[n,s]=this.perifocalAxes(),r=Math.sqrt(ya.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*ya.stumpffC(n),a=e-i*i*i/Math.sqrt(ya.SUN_GM_AU3_PER_DAY2)*ya.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(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),i=Math.sqrt(ya.SUN_GM_AU3_PER_DAY2)*Math.abs(t),n=a=>{const c=this.inverseSemiMajorAxis*a*a,h=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*h)*a*a*a*ya.stumpffS(c)+h*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<ya.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const c=(r+s)/2;n(c)<i?r=c:s=c}return e*(r+s)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(t),s=Math.sin(t),r=Math.cos(e),a=Math.sin(e),c=Math.cos(i),h=Math.sin(i);return[{x:n*r-s*a*c,y:s*r+n*a*c,z:a*h},{x:-n*a-s*r*c,y:-s*a+n*r*c,z:r*h}]}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 i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const TS=[{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 cN{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 TS.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(t,e,i){const n=hi(e),s=this.earthPositionAt(n),r=this.apparentPositionOf(t,2451545+n.tt,s),a=this.subtract(r,s),c=this.length(r),h=this.length(a),l=this.tailEndAt(t,r,s,c,n,e,i),u=this.horizontalOf(a,n,e,i);return{apparition:t,position:u,...l,heliocentricDistanceAu:c,earthDistanceAu:h,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(t,c,h)}}static magnitudeAt(t,e,i){const n=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(n,t.peakMagnitude)}static tailEndAt(t,e,i,n,s,r,a){if(t.tailLengthAu===void 0)return{};const c=1+t.tailLengthAu/n,h=this.subtract({x:e.x*c,y:e.y*c,z:e.z*c},i),l=this.subtract(e,i);return{tailEnd:this.horizontalOf(h,s,r,a),tailLengthDeg:this.angleBetween(l,h)}}static apparentPositionOf(t,e,i){const n=this.orbitOf(t);let s=n.positionAt(e);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(e-a)}return s}static horizontalOf(t,e,i,n){const s=Ca(A6(),new ze(t.x,t.y,t.z,e)),r=Ca(hS(e),s),a=s1(e,new Na(n.lat,n.lng,n.elevationM),!0),c=new ze(r.x-a.x,r.y-a.y,r.z-a.z,e),h=Y0(c);return vv(h.ra,h.dec,i,n)}static earthPositionAt(t){return Ca(E6(),To(ft.Earth,t))}static julianDayOf(t){return 2451545+hi(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new ya(t.orbit);return this.orbits.set(t.id,i),i}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 i=(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,i)))*180/Math.PI}}const km=[{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 Xw{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return km.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),n=[];for(const s of km){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:fr.ofJ2000(s.raHours,s.decDeg,t,e),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return km.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,n=e-t.startJd;if(i.length===0||n<i[0][0]||n>i[i.length-1][0])return;let s=1;for(;s<i.length-1&&i[s][0]<n;)s++;const[r,a]=i[s-1]??i[0],[c,h]=i[s]??i[0];if(c===r)return a;const l=Math.min(1,Math.max(0,(n-r)/(c-r)));return a+l*(h-a)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const hN=[{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}],S0=6.5;class Um{static activeAt(t){return hN.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),n=this.dayOfYear(this.asDate(t.start)),s=this.dayOfYear(this.asDate(t.peak)),r=this.dayOfYear(this.asDate(t.end)),a=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),h=this.wrappedDelta(r,s);return a<0?a<-c?0:1+a/c:a>0?a>h?0:1-a/h:1}static observedRatePerHour(t,e,i,n=S0){if(e<=0)return 0;const s=S0-n;return t*Math.sin(e*Math.PI/180)/Math.pow(i,s)}static radiantPosition(t,e,i){return fr.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}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 i=t-e;return i>182?i-365:i<-182?i+365:i}}class Vi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=hi(t),n=new V0(0,i6(t).elon-90,1),s=Ca(D6(i),gv(n,i)),r=Y0(s);return vv(r.ra,r.dec,t,e)}static observedRatePerHour(t,e=S0){const i=Vi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),n=S0-e;return(Vi.QUIET_RATE_PER_HOUR+i)/Math.pow(Vi.POPULATION_INDEX,n)}static schedule(t){const e=new K0(t.seed^1542469173);return Js.schedule(t).map(i=>{const n=Vi.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Vi.turnAround(n,e.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:Vi.toHorizontal(a),bearingDeg:Vi.bearingFrom(a,n)}})}static turnAround(t,e){const[i,n]=Vi.basisAround(t),s=e*Math.PI/180;return{x:i.x*Math.cos(s)+n.x*Math.sin(s),y:i.y*Math.cos(s)+n.y*Math.sin(s),z:i.z*Math.cos(s)+n.z*Math.sin(s)}}static bearingFrom(t,e){const[i,n]=Vi.basisAround(t),s=t.x*e.x+t.y*e.y+t.z*e.z,r=Vi.normalise({x:e.x-t.x*s,y:e.y-t.y*s,z:e.z-t.z*s});return(Math.atan2(r.x*n.x+r.y*n.y+r.z*n.z,r.x*i.x+r.y*i.y+r.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Vi.normalise(Vi.cross(t,e));return[i,Vi.normalise(Vi.cross(t,i))]}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=Vi.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Vi.turnAround(e,t.bearingDeg),n=t.fromRadiantDeg*Math.PI/180;return Vi.toHorizontal({x:e.x*Math.cos(n)+i.x*Math.sin(n),y:e.y*Math.cos(n)+i.y*Math.sin(n),z:e.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,n=Math.cos(e);return{x:n*Math.sin(i),y:Math.sin(e),z:-n*Math.cos(i)}}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 $w="https://ufoathome.org/tle/index.json";class Gn{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??Gn.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($w)||t.push($w),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${Gn.FIRST_SNAPSHOT}T00:00:00Z`)-Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>t.getTime()>=Date.parse(n.from)-Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS&&t.getTime()<=Date.parse(n.to)+Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:n}=e,s=[],r=[];for(const a of Object.keys(i.kinds)){const c=await this.kindAt(a,t,i,n);s.push(...c),r.push(this.coverageOf(a,t,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,n){const s=e.getTime(),r=i.binDays*Gn.DAY_MS,a=Math.floor(s/r),c=s-a*r<r/2?a-1:a+1,h=new Set(i.kinds[t].bins),l=[a,c].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>h.has(m));if(l.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,n).href),...l.map(m=>this.binary(new URL(`${t}/${m}.bin`,n).href))]),f=new Map;for(const m of d)for(const g of Gn.decode(m,i.recordBytes)){const v=f.get(g.norad);(!v||Math.abs(g.epochMs-s)<Math.abs(v.epochMs-s))&&f.set(g.norad,g)}const p=[];for(const m of f.values()){const g=Math.abs(m.epochMs-s)/Gn.DAY_MS;if(g>Gn.MAX_ELEMENT_AGE_DAYS)continue;const v=u[m.norad]??{name:String(m.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||p.push({norad:m.norad,name:v.name,kind:t,launch:v.launch,stdMag:v.stdMag,elements:m,ageDays:g})}return p}coverageOf(t,e,i,n){const{from:s,to:r}=i.kinds[t],a=e.getTime(),c=Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS,h=n?"covered":a<Date.parse(s)-c?"before":a>Date.parse(r)+c?"after":"gap";return{kind:t,status:h,from:s,to:r}}static decode(t,e){const i=new DataView(t),n=[];for(let s=0;s+e<=t.byteLength;s+=e)n.push({norad:i.getUint32(s,!0),epochMs:i.getFloat64(s+4,!0),bstar:i.getFloat32(s+12,!0),inclinationDeg:i.getFloat32(s+16,!0),raanDeg:i.getFloat32(s+20,!0),eccentricity:i.getFloat32(s+24,!0),argOfPerigeeDeg:i.getFloat32(s+28,!0),meanAnomalyDeg:i.getFloat32(s+32,!0),meanMotion:i.getFloat64(s+36,!0)});return n}loadIndex(){return this.index??=(async()=>{for(const 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 i=this.files.get(t);return i||(i=this.fetchImpl(t).then(n=>{if(!n.ok)throw new Error(`${t}: ${n.status}`);return e(n)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class lN{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=ci.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=ci.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:ci.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:ci.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class mc{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*mc.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=mc.degOver(t)/e;return i<1?1:Math.min(mc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Dn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return mc.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return Dn.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,n=e.fNumber??t.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return Dn.EYE;const s=e.focalLengthMm??t.frame?.focalLengthMm??Dn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=Dn.resolutionArcsec(t,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Dn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(t,e){const i=t.visualAid,n=Dn.EYE,s=e??t.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(t,e,i){const s=(t.detailUm??Dn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*Dn.ARCSEC_PER_RADIAN,r=1.22*Dn.WAVELENGTH_M/(i/1e3)*Dn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(t){return t/Dn.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=Dn.graspOf(t,e),n=Dn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:ki.focalLengthMmFor(t,e.fieldOfViewDeg);return Dn.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const Yw=111320,zl=Math.PI/180,uN=1.02,dN=1;class pu{static of(t,e){const i=pu.sightings(t,e);if(i.length<2)return;const n=pu.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,c=Math.tan(r.widthDeg/2*zl)===0?0:Math.tan(s.widthDeg/2*zl)/Math.tan(r.widthDeg/2*zl);if(c<uN)return;const h=a/(c-1),l=ci.sizeMAt(h,s.widthDeg),u=i.map(d=>({t:d.t,m:ci.distanceMAt(l,d.widthDeg)}));return{widthM:l,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===e)?.shape,s=n?.angular?.widthDeg,r=Le(t,i.t);return s===void 0||s<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:s,lat:r.lat,lng:r.lng,sightAzimuthDeg:n?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,n)=>i.t-n.t)}static baseline(t){let e;for(const i of t)for(const n of t){if(i.t>=n.t)continue;const s=pu.closedAlongSight(i,n),[r,a,c]=s>=0?[n,i,s]:[i,n,-s];c<dN||r.widthDeg<=a.widthDeg||(!e||c>e.closedM)&&(e={near:r,far:a,closedM:c})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*Yw,n=(e.lng-t.lng)*Yw*Math.cos(t.lat*zl),s=(t.sightAzimuthDeg??0)*zl;return i*Math.cos(s)+n*Math.sin(s)}}class is{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:is.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:is.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:is.atLeastNearest(t.derivedM),basis:"derived"};const e=is.largest(t.range?.minM,t.crossing?.behindM),i=is.smallest(t.range?.maxM,t.crossing?.inFrontM),n=e===void 0?void 0:e*is.MARGIN,s=i===void 0?void 0:i/is.MARGIN;return n!==void 0&&s!==void 0?{distanceM:is.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:is.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<is.CONVENTIONAL_M?{distanceM:is.atLeastNearest(s),basis:"bounded"}:{distanceM:is.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(is.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}class ss{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(t){const e=t?.flares;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>ss.bodiesOf(i))]}}static bodiesOf(t){const e={...ss.MJU_7,...t.flare},i=[],n=t.aircraft;if(n.model||n.sound){const s=t.releases.map(l=>l.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,c=n.model?{color:"#30333a",albedo:.15}:{transparency:1},h=l=>{const u=ss.aircraftAt(n,l);return{t:l,eastM:u.x,northM:u.y,altitudeM:u.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:c}};i.push({id:`${t.id}-aircraft`,title:t.title,model:n.model??{id:"sphere"},track:[h(r),h(a)],sound:n.sound})}return n.glow&&i.push(ss.glowBody(t,n.glow)),t.releases.forEach((s,r)=>i.push(ss.flareBody(t,e,s,r))),i}static aircraftAt(t,e){const i=t.headingDeg*Math.PI/180,n=(e-t.t)/1e3*t.speedMS;return{x:t.eastM+Math.sin(i)*n,y:t.northM+Math.cos(i)*n,z:t.altitudeM}}static burnShare(t,e){if(e<0||e>=t.burnS)return 0;if(e<.2)return e/.2;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static trajectory(t,e,i,n=ss.SAMPLE_MS){const s=t.aircraft,r=s.headingDeg*Math.PI/180,c={...ss.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-e.ejectionMS},h=(t.wind?.towardDeg??0)*Math.PI/180,l=t.wind?.speedMS??0,u=Math.sin(h)*l,d=Math.cos(h)*l,f=s.originElevationM??1e3,p=[{t:i,x:c.x,y:c.y,z:c.z}],m=ss.STEP_S,g=Math.round(n/1e3/m),v=Math.ceil(e.burnS/m);for(let M=1;M<=v;M++){const w=M*m,y=e.massKg-e.burnedKg*Math.min(1,w/e.burnS),b=1.225*Math.exp(-(c.z+f)/8500),S=c.vx-u,_=c.vy-d,x=c.vz,A=Math.hypot(S,_,x),I=.5*b*e.dragAreaM2*A/y;c.vx=(c.vx+I*m*u)/(1+I*m),c.vy=(c.vy+I*m*d)/(1+I*m),c.vz=(c.vz-ss.G*m)/(1+I*m),c.x+=c.vx*m,c.y+=c.vy*m,c.z+=c.vz*m,(M%g===0||M===v)&&p.push({t:i+Math.round(w*1e3),x:c.x,y:c.y,z:c.z})}return p}static glowBody(t,e){const i=e.sizeM/2,n=e.luminousIntensityCd/(Math.PI*i*i),s=[{t:e.fromT,lit:!0}];if(e.onS&&e.offS)for(let h=e.fromT,l=!0;h<e.untilT;l=!l)h+=(l?e.onS:e.offS)*1e3,h<e.untilT&&s.push({t:h,lit:!l});const r=(h,l)=>{const u=ss.aircraftAt(t.aircraft,h);return{t:h,eastM:u.x,northM:u.y,altitudeM:u.z,appearance:{color:e.color,luminanceCdM2:l?n:0}}},a=[];s.forEach(({t:h,lit:l},u)=>{u>0&&a.push(r(h-1,!l)),a.push(r(h,l))}),a[0]={...a[0],sizeM:{widthM:e.sizeM,lengthM:e.sizeM,heightM:e.sizeM},present:!0};const c=s[s.length-1];return a.push(r(e.untilT,c.lit),{t:e.untilT+1,present:!1}),{id:`${t.id}-glow`,title:t.title,explains:e.explains,model:{id:"sphere"},track:a}}static flareBody(t,e,i,n){const s=e.flameSizeM,r=s/2,a=e.luminousIntensityCd/(Math.PI*r*r),c=ss.trajectory(t,e,i.t),h=c.map((l,u)=>({t:l.t,eastM:l.x,northM:l.y,altitudeM:l.z,...u===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:e.color,luminanceCdM2:a*ss.burnShare(e,(l.t-i.t)/1e3),...u===0?{haloScale:1}:{}}}));return h.push({t:c[c.length-1].t+1,present:!1}),{id:`${t.id}-flare-${n+1}`,title:t.title,explains:i.explains,model:{id:"sphere"},track:h}}}class Re{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ff8a24",shape:"classic",paperColor:"#ffffff"};static FLAME_CDM2=5e3;static TITLE={en:"Sky lantern",fr:"Lanterne céleste",es:"Farolillo volador",it:"Lanterna volante"};static FLICKER=.15;static INSIDE_SHARE=2;static PAPER_FULL_CDM2=Re.COMMON.luminousIntensityCd/(Math.PI*Re.COMMON.widthM/2*Re.COMMON.heightM/2);static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static TURBULENCE={horizontalMS:.8,verticalMS:.3,timescaleS:30};static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(t){const e=t?.lanterns;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>Re.bodiesOf(i))]}}static bodiesOf(t){return Re.releasesOf(t).map((e,i)=>Re.lanternBody(t,e,i))}static releasesOf(t){const e=[...t.releases??[]],i=t.group;if(!i||!(i.count>0))return e;const n=Re.randomFrom(i.seed??1),s=c=>c.min+(c.max-c.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let c=0;c<i.count;c++){const h=i.fromT+r*c+(n()-.5)*r,l=a*Math.sqrt(n()),u=2*Math.PI*n();e.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,h))),explains:i.explains,eastM:Math.round(l*Math.sin(u)*10)/10,northM:Math.round(l*Math.cos(u)*10)/10,burnedS:i.burnedS,seed:Math.floor(n()*4294967296),lantern:{burnS:Math.round(s(i.burnS??{min:480,max:900})),insideExcessK:Math.round(s(i.insideExcessK??{min:125,max:175}))}})}return e}static randomFrom(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(t,e){return{...Re.COMMON,...t.lantern,...e.lantern}}static heatShare(t,e){if(e<0||e>=t.burnS)return 0;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static windAt(t,e){const i=Re.componentsOf(t.wind),n=t.windAloft;if(!n)return i;const s=Re.componentsOf(n),r=Math.max(0,Math.min(1,e/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(t,e,i=Re.SAMPLE_MS){const n=Re.typeOf(t,e),s=t.site,r=s.altitudeM??0,a=Math.max(0,e.burnedS??0),c=s.originElevationM??0,h=(t.airTemperatureC??10)+273.15,l={x:s.eastM+(e.eastM??0),y:s.northM+(e.northM??0),z:e.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*Re.heatShare(n,a)},u=Re.STEP_S,d=Math.max(1,Math.round(i/1e3/u)),f=Math.ceil(Math.max(0,n.burnS-a)/u),p=[{t:e.t,x:l.x,y:l.y,z:l.z,light:Re.heatShare(n,a),tiltDeg:0,tiltTowardDeg:0}],m=Re.gusts(t.turbulence??Re.TURBULENCE,Re.seedOf(e),u);for(let g=1;g<=f;g++){const v=g*u,M=a+v,w=Re.heatShare(n,M);l.excessK+=(n.insideExcessK*w-l.excessK)*Math.min(1,u/Re.COOLING_S);const y=l.z-r,b=h-Re.LAPSE*Math.max(0,y),S=101325*Math.exp(-(l.z+c)/8400),_=S/(Re.R_AIR*b),x=S/(Re.R_AIR*(b+l.excessK)),A=n.massKg-n.fuelKg*Math.min(1,M/n.burnS),I=(_-x)*n.envelopeVolumeM3*Re.G,D=A+x*n.envelopeVolumeM3+.5*_*n.envelopeVolumeM3,C=Re.windAt(t,y),N=m(),L={x:C.x+N.x,y:C.y+N.y,z:N.z},P=l.vx-L.x,z=l.vy-L.y,H=l.vz-L.z,$=.5*_*n.dragAreaM2*Math.hypot(P,z,H)/D;l.vx=(l.vx+$*u*L.x)/(1+$*u),l.vy=(l.vy+$*u*L.y)/(1+$*u),l.vz=(l.vz+$*u*L.z+(I-A*Re.G)/D*u)/(1+$*u);const Q=l.z<=r&&l.vz<=0;if(Q&&(l.vx=0,l.vy=0,l.vz=0),l.x+=l.vx*u,l.y+=l.vy*u,l.z=Math.max(r,l.z+l.vz*u),g%d===0||g===f){const Z=L.x-l.vx,nt=L.y-l.vy,ot=.5*_*n.dragAreaM2*Math.hypot(Z,nt,L.z-l.vz)*Math.hypot(Z,nt);p.push({t:e.t+Math.round(v*1e3),x:l.x,y:l.y,z:l.z,light:w,tiltDeg:Q?0:Math.atan2(ot,A*Re.G)*180/Math.PI,tiltTowardDeg:(Math.atan2(Z,nt)*180/Math.PI+360)%360})}}return p}static seedOf(t){return t.seed!==void 0?t.seed:Math.round(t.t)*2654435761+Math.round((t.eastM??0)*100)*40503+Math.round((t.northM??0)*100)>>>0}static gusts(t,e,i){const n=Re.randomFrom(e),s=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,n())))*Math.cos(2*Math.PI*n()),r=t.timescaleS>0?Math.exp(-i/t.timescaleS):0,a=Math.sqrt(1-r*r),c={x:t.horizontalMS*s(),y:t.horizontalMS*s(),z:t.verticalMS*s()};return()=>(c.x=r*c.x+a*t.horizontalMS*s(),c.y=r*c.y+a*t.horizontalMS*s(),c.z=r*c.z+a*t.verticalMS*s(),c)}static componentsOf(t){if(!t)return{x:0,y:0};const e=t.towardDeg*Math.PI/180;return{x:Math.sin(e)*t.speedMS,y:Math.cos(e)*t.speedMS}}static lanternBody(t,e,i){const n=Re.typeOf(t,e),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=Re.trajectory(t,e),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},c=Re.through(n.color,n.paperColor),h=r.map((l,u)=>({t:l.t,eastM:l.x,northM:l.y,altitudeM:l.z,...u===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(l.tiltTowardDeg),pitchDeg:-Math.round(l.tiltDeg*10)/10},appearance:{color:c,luminanceCdM2:s*l.light,...u===0?{albedo:.6,haloScale:1}:{}},lights:Re.lightsOf(s*l.light)}));return h.push({t:r[r.length-1].t+1,present:!1}),{id:`${t.id}-lantern-${i+1}`,title:Re.TITLE,explains:e.explains,model:{id:`ufoathome-sky-lantern-${n.shape}`},modelParameters:{paperColor:n.paperColor},flicker:Re.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:h}}static lightsOf(t){return{paper:t,"paper-inside":t*Re.INSIDE_SHARE,flame:t>0?Re.FLAME_CDM2*t/Re.PAPER_FULL_CDM2:0}}static through(t,e){const i=c=>[1,3,5].map(h=>parseInt(c.slice(h,h+2),16)/255),n=i(t),s=i(e),r=n.map((c,h)=>c*s[h]),a=Math.max(...n)/(Math.max(...r)||1);return"#"+r.map(c=>Math.round(Math.min(1,c*a)*255).toString(16).padStart(2,"0")).join("")}}class Sv{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=Sv.FIRST_DAY}}class fN{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,n){try{return await(await this.provider()).between(t,e,i,n)}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 pN="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",mN=[{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 fN(pN,o=>Sv.mayCover(o),async()=>new(await De(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-CQ9jtd4F.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)}];class rs{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const n=rs.positionAt(t,i);if(!n)return;const s=_t.seenFrom(e,n.geo);if(!(s.altitudeDeg<0))return{track:t,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:rs.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(n=>rs.seenFrom(n,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,n=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*rs.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=e;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>rs.MAX_GAP_S*1e3)return;const c=a>0?(e-s.t)/a:0,h=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*c,l=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*c,lng:rs.wrapLongitude(s.lng+l*c),heightM:h*rs.FT_TO_M},altitudeFt:h,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(t,e,i){const n=rs.positionAt(t,i-500),s=rs.positionAt(t,i+500);if(!n||!s)return;const r=rs.unit(_t.seenFrom(e,n.geo)),a=rs.unit(_t.seenFrom(e,s.geo)),c=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(c)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const Kw="https://ufoathome.org/fireballs/index.json";class Vr{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??Vr.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(Kw)||t.push(Kw),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Vr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Vr.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=t&&r.t<=e):void 0}static seenFrom(t,e){const i=Vr.peakFraction(t),n={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},s=_t.seenFrom(e,n);if(!(s.altitudeDeg<0))return{record:t,peak:s,magnitude:t.peakMagnitude+5*Math.log10(s.distanceKm/_t.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,n=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:n,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Vr.COLOR,trainS:Vr.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 i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(t,i)),i}}const sh=Math.PI/180,Bl=180/Math.PI;class _i{constructor(t,e){this.timeline=t,this.tolerance=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),h=Math.max(_i.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+h||n.altitudeDeg>(c.high??i.altitudeDeg)+h||n.altitudeDeg<(c.low??i.altitudeDeg)-h},size(i,n){const s=t.law({kind:"angularSize",value:i},e);return n<(s.low??i)/_i.SIZE_TOLERANCE||n>(s.high??i)*_i.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[];for(const r of e){const a=_i.projectionOf(r,i,n?.(r));if(a)for(const c of r.explains){const h=this.timeline.getInterpolatedShapeAt(t,c);!h||h.transparency>=1||s.push({..._i.compare(c,r.id,{aim:h.aim,angular:h.angular},a,this.tolerance),title:h.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?_i.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(_i.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,h=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,l=(u,d)=>s?s.size(d,d*u):!_i.withinSize(u);return c!==void 0&&l(c,i.angular.widthDeg)&&r.push("width"),h!==void 0&&l(h,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:h,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:_i.outlineOf(t),s=i&&i.length>0?_i.centreOf(i):t,r=_i.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=_i.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=_i.cross(a,r);let h=1/0,l=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},m=_i.dot(p,r);if(m<=0)return;const g=Math.atan2(_i.dot(p,a),m),v=Math.atan2(_i.dot(p,c),m);h=Math.min(h,g),l=Math.max(l,g),u=Math.min(u,v),d=Math.max(d,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*Bl+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*Bl},angular:{widthDeg:(l-h)*Bl,heightDeg:(d-u)*Bl}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*sh,n=e.altitudeDeg*sh,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*sh);return Math.acos(Math.max(-1,Math.min(1,s)))*Bl}static withinSize(t){return t<=_i.SIZE_TOLERANCE&&t>=1/_i.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&bS.includes(r))for(let u=0;u<=_i.RINGS;u++){const d=u/_i.RINGS*Math.PI;for(let f=0;f<_i.SEGMENTS;f++){const p=f/_i.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*sh,h=t.attitude.pitchDeg*sh,l=t.attitude.rollDeg*sh;return s.map(([u,d,f])=>{const p=u*Math.cos(l)+f*Math.sin(l),m=-u*Math.sin(l)+f*Math.cos(l),g=d*Math.cos(h)-m*Math.sin(h),v=d*Math.sin(h)+m*Math.cos(h);return{eastM:t.eastM+p*Math.cos(c)+g*Math.sin(c),northM:t.northM-p*Math.sin(c)+g*Math.cos(c),upM:t.upM+v}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}Lb();const gN={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},vN="{name} — mag {mag}, {alt}° above the horizon",MN="{name} — {size}, {distance} away",yN="{name} — satellite, mag {mag}, {height} km up",wN={name:"Re-entry",piece:"{name} — mag {mag}, {height} km up, {distance} km away",fragment:"{name}, a fragment — mag {mag}, {height} km up, {distance} km away"},qw={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},bN={name:"Afterimage, in the eye",detail:"{name}: where the image of a light brighter than the Sun fell, the retina's pigment is bleached: for a few seconds it goes on glowing, white then coloured, and then what is seen there looks darker. It stays where it is in the field of view whichever way the eye turns, and takes minutes to fade."},xN={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},SN="satellites-change",EN="fireballs-change",AN="references-change",_N="aircraft-change",RS="rr0-confrontation",TN="{name} — mag {mag}, {alt}° below the horizontal",Fm="Credits",Zw="comet:",Jw="nova:",zm={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},RN=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,IN=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,DN=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,CN=-18,ON={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},mf={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Ee 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",Jr,jr,ec]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new T;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Gn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Vr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=mN[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Ee.trafficRuntimeLoading??=De(()=>import("./trafficRuntime-CfPqH9j0.js"),__vite__mapDeps([4,3]),import.meta.url).then(t=>Ee.trafficRuntime=t),Ee.trafficRuntimeLoading.catch(()=>{Ee.trafficRuntimeLoading=void 0}),Ee.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new _h;vehicleAudio=new EA;aircraftAudio;vehicleHearing=new Gf;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();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 i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const n=(t.clientX-i.left)/i.width*2-1,s=1-(t.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(n,s)?this.sceneRenderer.pickGhostAt(n,s)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>Ee.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(t){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(t.clientX-i.left)/i.width*e.width,s=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(t.clientX-i.left)/i.width*2-1,a=-((t.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const c=this.pickAt(r,a,!0,t.altKey);c?this.showHoverTooltip(t,t.altKey&&c.detail?c.detail():c.name):this.hoverTooltip.hidden=!0,this.showGhostPath(c?.path,i)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),s=n(t.from),r=n(t.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[c,h,l,u]=Array.from(this.ghostPath.children);for(const d of[c,h])d.setAttribute("x1",String(s.x)),d.setAttribute("y1",String(s.y)),d.setAttribute("x2",String(r.x)),d.setAttribute("y2",String(r.y));l.setAttribute("cx",String(a.x)),l.setAttribute("cy",String(a.y)),u.setAttribute("cx",String(r.x)),u.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(t,e)){const x=r?.ghostTooltip??qw,A=x.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:A,detail:()=>x.dropDetail.replace("{name}",A)}}const a=this.sceneRenderer.pickBodyAt(t,e);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const c=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,h=c?this.interpretationShown?.bodies.find(x=>x.id===c):void 0,l=h?this.said.read(h.title)||(h.model.id==="figure"?s.decorKind("entity",zm.entity):void 0):void 0;if(c!==void 0&&l)return{kind:"body",id:c,name:l};const u=this.ufoElement.sighting.skyEvents?.beams,d=u?.length?this.sceneRenderer.pickBeamAt(t,e):void 0,f=d?u?.find(x=>x.id===d.id):void 0;if(d&&f){const x=this.said.read(f.title)||"Laser";return{kind:"beam",id:f.id,name:x,detail:()=>`${x} (${f.wavelengthNm} nm, ${f.powerW.toLocaleString()} W), ${this.distanceText(d.distanceM)}`}}const p=i?this.ghostPick(t,e):void 0;if(p)return p;if(this.sceneRenderer.pickAfterimageAt(t,e)){const x=this.naming.names?.afterimageTooltip??bN;return{kind:"afterimage",name:x.name,detail:()=>x.detail.replace("{name}",x.name)}}const m=this.pickDecorAt(t,e),g=m?this.ufoElement.sighting.decor.find(x=>x.id===m):void 0;if(g){const x=this.said.read(g.title)||s.decorKind(g.kind,zm[g.kind]);return{kind:"decor",id:g.id,name:x,detail:()=>this.decorTooltip(g,x)}}const v=this.sceneRenderer.pickRailwayAt(t,e);if(v){const x=r?.railwayTooltip??dr.ENGLISH;return{kind:"railway",id:v.line.id,name:dr.name(v.line,x),detail:()=>dr.detail(v,x,A=>this.distanceText(A))}}const M=this.trafficTooltipAt(t,e);if(M)return{kind:"traffic",name:M};const w=this.plumePickAt(t,e);if(w)return w;const y=this.sceneRenderer.pickSatelliteAt(t,e);if(y)return{kind:"satellite",name:(r?.satelliteTooltip??yN).replace("{name}",y.name).replace("{mag}",y.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(y.heightKm).toLocaleString())};const b=this.reentryPickAt(t,e);if(b)return b;const S=this.sceneRenderer.pickOpticsAt(t,e);if(S){const x=(r?.opticsTooltips??nN)[S.id].replace("{angle}",String(Math.round(S.angleDeg??0)));return{kind:"optics",id:S.id,name:x.split(" — ")[0],detail:()=>x}}const _=this.sceneRenderer.pickStarAt(t,e);if(_){const x=_.star.mag,A=_.altitudeDeg,I=A<0?r?.starTooltipBelow??TN:r?.starTooltip??vN,D=s.star(_.star);return{kind:"star",name:D,detail:()=>I.replace("{name}",D).replace("{mag}",x.toLocaleString(void 0,{maximumFractionDigits:Math.abs(x)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(A))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const i=this.ufoElement.canvasElement,n={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},s=`${Math.round(t/n.x)}:${Math.round(e/n.y)}`,r=performance.now(),a=this.ghostLights.get(s);if(a&&r-a.atMs<Ee.GHOST_LIGHT_KEPT_MS)return a.light;let c=this.shiningDecorNear(t,e,2*Math.max(n.x,n.y)),h;if(!c)for(const[l,u]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+l*n.x,e+u*n.y,!1);if(d?.kind==="star")h??=d;else if(d){c=d;break}}return c??=this.shiningDecorNear(t,e,6*Math.max(n.x,n.y)),c??=h,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(s,{light:c??null,atMs:r}),c??null}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const n=this.naming.names?.ghostTooltip??qw,s=this.lightOfGhost(i.source.x,i.source.y)??void 0,r=(s?.kind==="star"?s.name.split(" — ")[0]:s?.name)??n.unnamed,a=i.ghost,h=(Si.scatters(a)?n.halo:a.cause==="glass"?n.double:n.ghost).replace("{name}",r),l=a.scale<0?n.opposite:a.scale===1?n.around:n.sameSide;return{kind:"ghost",id:s?.id,name:h,detail:()=>n.detail.replace("{name}",h).replace("{cause}",n.causes[a.cause??"lens"]).replace("{where}",l),path:{from:{x:a.scale*i.source.x,y:a.scale*i.source.y},to:i.source}}}shiningDecorNear(t,e,i){let n;for(const s of this.ufoElement.sighting.decor){if(!(s.kind==="streetlight"||s.kind==="trafficlight"||(s.lights?.length??0)>0||s.kind==="vehicle"&&s.lit))continue;const a=this.sceneRenderer.decorScreenBox(s.id);if(!a)continue;const c=Math.hypot(Math.max(a.minX-t,0,t-a.maxX),Math.max(a.minY-e,0,e-a.maxY));if(c>i||n&&c>=n.distance)continue;const h=this.said.read(s.title)||this.naming.decorKind(s.kind,zm[s.kind]);n={distance:c,pick:{kind:"decor",id:s.id,name:h}}}return n?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new ac(n=>{if(!Si.records(t.instrument)||!Si.falling(t.lens))return 0;const s=gl(t,n*1e3),r=Le(t,n*1e3);return(s.precipitationAmount??1)*Si.impactRate(s,t.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(t,e){const i=this.ufoElement.sighting.skyEvents?.launches,n=i?.length?this.sceneRenderer.pickPlumeAt(t,e):void 0,s=n?i?.find(h=>h.id===n.launchId):void 0;if(!n||!s)return;const r=this.naming.names?.plumeTooltip??xN,a=this.said.read(s.title)||s.vehicle?.mission||r.name,c=()=>n.release===void 0||n.release==="burn"?r.ascent:s.jets?.find((l,u)=>`jet:${l.id??u}`===n.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:s.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",c()).replace("{distance}",this.distanceText(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}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 i=h=>h.toLocaleString(void 0,{maximumFractionDigits:h<10?1:0}),n=ut.sizeOf(t),s=this.sceneRenderer.decorDistanceM(t.id),r=s===void 0?"":this.distanceText(s);return(this.naming.names?.decorTooltip??MN).replace("{name}",e).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(t){const e=t.startsWith(Zw)?t.slice(Zw.length):void 0,i=e?TS.find(r=>r.id===e):void 0;if(i)return this.naming.comet(i);const n=t.startsWith(Jw)?Xw.byId(t.slice(Jw.length)):void 0;if(n)return this.naming.nova(n);const s=gN[t];return s===void 0?t:this.naming.body(t,s)}get naming(){return this.sceneNaming}sceneNaming=new x0;namesLanguage="en";async loadSceneNames(){const t=C1(Ao.preferencesFor(this),P1);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await bb(t);t===this.namesLanguage&&this.applySceneNaming(new x0(e))}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 i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,c)=>{c>0&&s.append(" ");const h=document.createElement("span");h.className="scene-loader-word",h.setAttribute("aria-hidden","true");for(const l of a){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=l,h.append(u)}s.append(h),i++})};n(this.loaderNotVideo,t),i+=6,n(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t;const e=t.names?.credits??Fm;this.creditsButton.title=e,this.creditsButton.setAttribute("aria-label",e),t.names&&this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names?.compassPoints)}showHoverTooltip(t,e){this.hoverTooltip.textContent=e,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect(),n=t.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${t.clientY-i.top+12}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};hearDetonations(t,e,i,n){const s=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,r=this.detonationsFor;(!r||s!==r.key||t.length!==r.reentries.length||t.some((h,l)=>h!==r.reentries[l]))&&(this.detonationsFor={reentries:[...t],key:s,detonations:t.length?_t.detonationsOf(t,i):[]});const a=this.detonationsFor.detonations;if(n)return;const c=this.lastDetonationT;if(this.lastDetonationT=e,!(c===void 0||e<c||e-c>Ee.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const h of a)h.t>c&&h.t<=e&&this.weatherAudio.playDetonation(h.loudness)}reentryPickAt(t,e){const i=this.sceneRenderer.pickReentryAt(t,e);if(!i)return;const n=this.naming.names?.reentryTooltip??wN,s=this.detonationsFor?.reentries.find(u=>u.id===i.view.reentryId),r=(s?.title?this.said.read(s.title):"")||s?.object?.name||n.name,a=i.view.head,c=6371,h=Math.sqrt(c**2+a.distanceKm**2+2*c*a.distanceKm*Math.sin(a.altitudeDeg*Math.PI/180))-c;return{kind:"reentry",name:(i.view.fragmentId.includes(".")?n.fragment:n.piece).replace("{name}",r).replace("{mag}",i.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(h).toLocaleString()).replace("{distance}",Math.round(a.distanceKm).toLocaleString())}}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=Le(t,0),n=t.event.place?.[0],s=i?.lat??n?.lat,r=i?.lng??n?.lng;return e.length>0&&s!==void 0&&r!==void 0&&_t.detonationsOf(e,{lat:s,lng:r,heightM:i?.elevationM??0}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),dn.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(gl(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){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>=Ee.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(t,t),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),this.aircraftAudio?.setPaused(!t),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${RA}</style>${TA}`,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 lt(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(AN));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.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new fu(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.ufoElement=document.createElement(Km),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=s=>this.frozenMapOf(s),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&In.fill(n,this)}),this.creditsButton.title=Fm,this.creditsButton.setAttribute("aria-label",Fm),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(kb,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1)||this.detonates(s),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of Ee.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Es(Ao.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return i?{setting:vc.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}:void 0}travelHeadingAt(t,e){const i=Le(t,e);if(!i)return 0;for(const n of[400,-400]){const s=Le(t,e+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=de(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:n},n}traceLabels(t){const e=Ao.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const n of t){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Ee.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(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of Ee.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,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(t===Jr||t===jr||t===ec)&&i!==e&&this.forwardPlayerAttributes(),t===ec&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[Jr,jr,ec]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.sceneRenderer.setCompassForced(t)}lookToward(t){const e=Le(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:i,z:n}=de(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,n)<1)return this.setLookOffset(0,0);const s=(Math.atan2(i,-n)*180/Math.PI+360)%360;this.setLookOffset(((s-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.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed)}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,i,n=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,n)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}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=Eo.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),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=Wi.toCurrent(t);this.ufoElement.sightingData=e,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?Re.expand(ss.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new M0(this,()=>document.createElement(E0))}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}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}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 i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.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.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(t){const e=Ch.isEmpty(t)?"none":`${JSON.stringify(t)}
9221
+ `;function Gw(o){const e=document.createElement("canvas");e.width=128,e.height=128;const i=e.getContext("2d"),n=128/2-2,s=128/2,r=128/2,a="#010101",c="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const h=Cr(o.illuminatedFraction,0,1),l=o.phaseFraction<.5,u=n*Math.abs(1-2*h),d=h<.5;return i.save(),i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.clip(),i.fillStyle=c,i.beginPath(),l?(i.arc(s,r,n,-Math.PI/2,Math.PI/2,!1),i.ellipse(s,r,u,n,0,Math.PI/2,-Math.PI/2,d)):(i.arc(s,r,n,Math.PI/2,-Math.PI/2,!1),i.ellipse(s,r,u,n,0,-Math.PI/2,Math.PI/2,d)),i.fill(),i.restore(),new No(e)}function JP(o){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(o,64,68),new No(t)}function Pm(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}class M0{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:`${M0.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 i=this.ensureScene();i.interpretation!==this.source.interpretation&&(i.interpretation=this.source.interpretation),i.compareAccount!==this.source.compareAccount&&(i.compareAccount=this.source.compareAccount),i.showAt(t);for(let n=0;n<M0.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(s=>requestAnimationFrame(()=>s())),!this.wanted);n++)if(i.snapshotTo(e)){e.dataset.ready="true";break}}}finally{this.pumping=!1}}}class fi{static held=new Map;static loaded=new Map;static generation=0;static address(t,e){const i=e??(typeof location>"u"?"http://localhost/":location.href);return new URL(t,i).href}static hold(t,e){fi.held.set(t,e),fi.loaded.delete(t),fi.generation++}static release(){if(fi.held.size!==0){for(const t of fi.held.keys())fi.loaded.delete(t);fi.held.clear(),fi.generation++}}static bytes(t,e=fetch.bind(globalThis)){const i=fi.held.get(t);if(i)return Promise.resolve(i);let n=fi.loaded.get(t);return n||(n=e(t).then(async s=>{if(!s.ok)throw new Error(`Frozen data not found (${s.status}): ${t}`);return new Uint8Array(await s.arrayBuffer())}),fi.loaded.set(t,n),n.catch(()=>fi.loaded.delete(t))),n}static async json(t){return JSON.parse(new TextDecoder().decode(await fi.bytes(t)))}static async zip(t){const e=await fi.bytes(t),{unzipSync:i}=await Ie(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);return i(e)}}class ia{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 i,n=1/0;for(const s of this.list){if(s.far)continue;const{x:r,z:a}=de(s.lat,s.lng,t,e),c=Math.hypot(r,a);c<n&&(n=c,i=s)}return i}farRingOf(t,e){return this.list.find(i=>i.far&&Math.abs(i.lat-t)<=ia.SAME_BOUNDS_DEG&&Math.abs(i.lng-e)<=ia.SAME_BOUNDS_DEG)}static boundsOf(t){return ru(t.lat,t.lng,t.radiusM)}static sameBounds(t,e){const i=(n,s)=>Math.abs(n-s)<=ia.SAME_BOUNDS_DEG;return i(t.north,e.north)&&i(t.south,e.south)&&i(t.east,e.east)&&i(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((i,n)=>i.lat===e[n].lat&&i.lng===e[n].lng&&i.radiusM===e[n].radiusM&&i.far===e[n].far)}}class y0{static async encode(t){const{zipSync:e,strToU8:i}=await Ie(async()=>{const{zipSync:r,strToU8:a}=await import("./browser-_Ncw3Jhn.js");return{zipSync:r,strToU8:a}},[],import.meta.url),n={},s={version:1,takenOn:t.takenOn,attribution:t.attribution,patches:t.patches.map((r,a)=>{const c=`${a}.f32`;return n[c]=y0.byPlane(r.grid.heights),{lat:r.lat,lng:r.lng,radiusM:r.radiusM,...r.far?{far:r.far}:{},bounds:r.grid.bounds,width:r.grid.width,height:r.grid.height,file:c}})};return n["index.json"]=i(JSON.stringify(s,null,1)),e(n,{level:9})}static decode(t){const e=t["index.json"];if(!e)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(e));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(n=>{const s=t[n.file];if(!s||s.length!==n.width*n.height*4)return[];const r={heights:y0.fromPlanes(s),width:n.width,height:n.height,bounds:n.bounds};return[{lat:n.lat,lng:n.lng,radiusM:n.radiusM,...n.far?{far:n.far}:{},grid:r}]})}}static byPlane(t){const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=t.length,n=new Uint8Array(e.length);for(let s=0;s<i;s++)for(let r=0;r<4;r++)n[r*i+s]=e[s*4+r];return n}static fromPlanes(t){const e=t.length/4,i=new Uint8Array(t.length);for(let n=0;n<e;n++)for(let s=0;s<4;s++)i[n*4+s]=t[s*e+n];return new Float32Array(i.buffer)}}class wv{constructor(t){this.annex=t}async getElevationGrid(t,e,i){const{patches:n}=await this.annex,s=n.find(a=>ia.sameBounds(ia.boundsOf(a),t));if(s)return{...s.grid,heights:new Float32Array(s.grid.heights)};const r=n.find(a=>ia.contains(a.grid.bounds,t));if(r)return wv.resample(r.grid,t,e);throw new Error("The frozen relief does not hold this ground")}static resample(t,e,i){const{width:n,height:s}=i,r=new Float32Array(n*s),a=t.bounds.east-t.bounds.west,c=t.bounds.north-t.bounds.south;for(let h=0;h<s;h++){const l=e.north-(e.north-e.south)*(s>1?h/(s-1):0),u=Math.min(t.height-1,Math.max(0,(t.bounds.north-l)/c*(t.height-1))),d=Math.floor(u),f=Math.min(t.height-1,d+1),p=u-d;for(let m=0;m<n;m++){const g=e.west+(e.east-e.west)*(n>1?m/(n-1):0),v=Math.min(t.width-1,Math.max(0,(g-t.bounds.west)/a*(t.width-1))),M=Math.floor(v),w=Math.min(t.width-1,M+1),y=v-M,b=(x,A)=>t.heights[x*t.width+A],S=b(d,M)*(1-y)+b(d,w)*y,_=b(f,M)*(1-y)+b(f,w)*y;r[h*n+m]=S*(1-p)+_*p}}return{heights:r,width:n,height:s,bounds:e}}}function AS(o,t){return o.find(e=>e.id===t)??o[0]}class jP{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 Cb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const _S=[{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:o=>new Ob({fetchImpl:o})},{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:o=>new jP({fetchImpl:o})}];class Vw{static async encode(t){const{zipSync:e,strToU8:i}=await Ie(async()=>{const{zipSync:c,strToU8:h}=await import("./browser-_Ncw3Jhn.js");return{zipSync:c,strToU8:h}},[],import.meta.url),n={},s={};let r=0;for(const[c,h]of t.tiles){const l=`tiles/${r++}`;n[l]=h.bytes,s[c]={file:l,type:h.type}}const a={version:1,takenOn:t.takenOn,source:t.source,attribution:t.attribution,patches:t.patches,map:t.map,tiles:s};return n["index.json"]=i(JSON.stringify(a,null,1)),e(n,{level:0})}static decode(t){const e=t["index.json"];if(!e)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(e)),n=new Map;for(const[s,{file:r,type:a}]of Object.entries(i.tiles)){const c=t[r];c&&n.set(s,{bytes:c,type:a})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:n}}}class q0{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(n=>(this.attributionRead=n.attribution,AS(_S,n.source).create(q0.fetchFrom(n.tiles)))))).getImageryTexture(t,e)}static fetchFrom(t){return async e=>{const i=typeof e=="string"?e:e instanceof URL?e.href:e.url,n=t.get(i);return n?new Response(n.bytes,{status:200,headers:{"content-type":n.type}}):new Response(null,{status:404})}}}class QP{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,AS(_S,t.source).create(q0.fetchFrom(t.tiles)).getImageryTexture(t.map.bounds,{width:t.map.pixels,height:t.map.pixels})})}}class bv{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(i=>ia.sameBounds(ia.boundsOf(i),t))?.items??[]}}class tN{constructor(t,e=""){this.attributionStated=e,this.reader=new bv(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 eN{constructor(t,e=""){this.attributionStated=e,this.reader=new bv(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(t){return this.reader.itemsFor(t)}}class iN{constructor(t,e=""){this.attributionStated=e,this.reader=new bv(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 w0{static providers(t,e,i){const n=f=>Ch.held(t,f),s=n("relief"),r=n("imagery"),a=n("roads"),c=n("water"),h=n("railways");if(!s&&!r&&!a&&!c&&!h)return i;const l=f=>fi.address(f.src,e),u=[],d={...i};if(s){const f=fi.zip(l(s)).then(p=>y0.decode(p));d.elevation=new wv(f),u.push(f.then(p=>p.patches))}if(r){const f=fi.zip(l(r)).then(p=>Vw.decode(p));d.imagery=new q0(f,r.attribution),u.push(f.then(p=>p.patches))}if(a){const f=fi.json(l(a));d.roads=new tN(f,a.attribution),u.push(f.then(p=>p.patches))}if(c){const f=fi.json(l(c));d.water=new eN(f,c.attribution),u.push(f.then(p=>p.patches))}if(h){const f=fi.json(l(h));d.railways=new iN(f,h.attribution),u.push(f.then(p=>p.patches))}return d.patches=new ia(w0.firstRead(u)),d}static map(t,e){const i=fi.zip(fi.address(t.src,e)).then(n=>Vw.decode(n));return new QP(i,t.attribution)}static async firstRead(t){for(const e of t)try{const i=await e;if(i.length>0)return i.map(({lat:n,lng:s,radiusM:r,far:a})=>({lat:n,lng:s,radiusM:r,...a?{far:a}:{}}))}catch{}return[]}}class Ah{constructor(t){this.annex=t}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(t,e,i){let n;try{n=await this.annex}catch{return{status:"failed"}}const s=c=>Math.abs(c.lat-t.lat)<=Ah.SAME_PLACE_DEG&&Math.abs(c.lng-t.lng)<=Ah.SAME_PLACE_DEG,a=n.answers.find(c=>s(c)&&Math.abs(c.startMs-e)<=Ah.SAME_TIME_MS&&Math.abs(c.endMs-i)<=Ah.SAME_TIME_MS)??n.answers.find(c=>c.startMs<=e&&c.endMs>=i);return a?a.answer:{status:"failed"}}}const Nm=7.5,Lm=9;class Or{static cache=new Map;static load(t){let e=Or.cache.get(t);return e||(e=fetch(t).then(i=>i.arrayBuffer()).then(i=>Or.parse(i)),Or.cache.set(t,e)),e}static upTo(t,e){const i=t.filter((r,a)=>a===0||t[a-1].magnitudeLimit<e);if(i.length<=1)return Or.load(t[0].url);const n=i.map(r=>r.url).join(`
9222
+ `);let s=Or.cache.get(n);return s||(s=Promise.all(i.map(r=>Or.load(r.url))).then(r=>r.reduce((a,c)=>Or.concat(a,c))),Or.cache.set(n,s)),s}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(n,s)=>{const r=new Float32Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),r};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class ii{constructor(t){if(this.heights=t,t.length!==ii.WIDTH*ii.HEIGHT)throw new Error(`a lunar relief has ${ii.WIDTH*ii.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*ii.SAMPLES_PER_DEGREE;static HEIGHT=180*ii.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=ii.SAMPLES_PER_DEGREE,n=(e%360+360)%360*i-.5,s=(90-t)*i-.5,r=Math.floor(n),a=Math.floor(s),c=n-r,h=s-a,l=(f,p)=>{const m=(f%ii.WIDTH+ii.WIDTH)%ii.WIDTH,g=Math.min(ii.HEIGHT-1,Math.max(0,p));return this.heights[g*ii.WIDTH+m]},u=l(r,a)*(1-c)+l(r+1,a)*c,d=l(r,a+1)*(1-c)+l(r+1,a+1)*c;return(u*(1-h)+d*h)*ii.UNIT_KM}static inBand(t,e){const i=Math.PI/180,n=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return n>=ii.BAND_FROM_DEG&&n<=ii.BAND_TO_DEG}static withBump(t,e,i,n=.4){const s=new Int8Array(ii.WIDTH*ii.HEIGHT),r=ii.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),c=Math.floor(e*r),h=Math.floor((90-t)*r);for(let l=-a;l<=a;l++)for(let u=-a;u<=a;u++)Math.hypot(u,l)<=a&&(s[(h+l)*ii.WIDTH+(c+u+ii.WIDTH)%ii.WIDTH]=Math.round(i/ii.UNIT_KM));return new ii(s)}static smooth(){return new ii(new Int8Array(ii.WIDTH*ii.HEIGHT))}}class qs{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,n=qs.SAMPLES){const{s,u:r,w:a,distanceKm:c}=qs.frame(t,e),h=Math.PI/180,l=new Float32Array(n),u=ii.REFERENCE_RADIUS_KM;for(let d=0;d<n;d++){const f=d/n*2*Math.PI,p=Math.cos(f),m=Math.sin(f),g=p*r[0]+m*a[0],v=p*r[1]+m*a[1],M=p*r[2]+m*a[2];let w=0;for(let y=qs.SEARCH_FROM_DEG;y<=qs.SEARCH_TO_DEG;y+=qs.SEARCH_STEP_DEG){const b=Math.cos(y*h),S=Math.sin(y*h),_=b*s[0]+S*g,x=b*s[1]+S*v,A=b*s[2]+S*M,I=Math.asin(Math.max(-1,Math.min(1,A)))/h,D=Math.atan2(x,_)/h,C=u+i.heightKm(I,D),N=Math.atan2(C*S,c-C*b);N>w&&(w=N)}l[d]=w/h}return{radiusDeg:l,meanRadiusDeg:Math.asin(u/c)/h}}static frame(t,e){const i=new Na(e.lat,e.lng,e.elevationM),n=La(t),s=s1(t,i,!1),r=new ze(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*qs.AU_KM,c=qs.bodyFixed(t),h=c(r),l=Math.hypot(h[0],h[1],h[2]),u=[h[0]/l,h[1]/l,h[2]/l],d=I6(t,i),f=pv(d),p=Ca(d,new ze(-r.x,-r.y,-r.z,n.t)),m=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),g=Math.atan2(-p.y,p.x),v=new ze(-Math.sin(m)*Math.cos(g),Math.sin(m)*Math.sin(g),Math.cos(m),n.t),M=new ze(-Math.sin(g),-Math.cos(g),0,n.t);return{s:u,u:c(Ca(f,v)),w:c(Ca(f,M)),distanceKm:a}}static surfacePoint(t,e,i,n){const{s,u:r,w:a}=qs.frame(t,e),c=Math.PI/180,h=[0,1,2].map(u=>Math.cos(i*c)*r[u]+Math.sin(i*c)*a[u]),l=[0,1,2].map(u=>Math.cos(n*c)*s[u]+Math.sin(n*c)*h[u]);return{latDeg:Math.asin(l[2])/c,lonDeg:Math.atan2(l[1],l[0])/c}}static radiusAt(t,e){const i=t.radiusDeg.length,n=(e/360*i%i+i)%i,s=Math.floor(n),r=n-s;return t.radiusDeg[s]*(1-r)+t.radiusDeg[(s+1)%i]*r}static uncoveredFraction(t,e,i){const n=t.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const c=a/n*2*Math.PI,h=Math.cos(c),l=Math.sin(c),u=h*i.upDeg+l*i.rightDeg,d=u*u-s+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const m=Math.max(0,u-f),g=Math.max(m,t.radiusDeg[a]);p>g&&(r+=.5*(p*p-g*g))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=X6(ft.Moon,t),i=Math.PI/180,n=e.ra*15*i,s=e.dec*i,r=e.spin*i,a=(h,[l,u,d])=>[Math.cos(h)*l+Math.sin(h)*u,-Math.sin(h)*l+Math.cos(h)*u,d],c=(h,[l,u,d])=>[l,Math.cos(h)*u+Math.sin(h)*d,-Math.sin(h)*u+Math.cos(h)*d];return h=>a(r,c(Math.PI/2-s,a(Math.PI/2+n,[h.x,h.y,h.z])))}static subObserverPoint(t,e){const i=new Na(e.lat,e.lng,e.elevationM),n=La(t),s=s1(t,i,!1),r=qs.bodyFixed(t)(new ze(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class uu{static cache=new Map;static load(t){let e=uu.cache.get(t);return e||(e=uu.fetchRelief(t).catch(()=>{}),uu.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new ii(new Int8Array(i.buffer,i.byteOffset,i.length))}}class b0{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=b0.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=b0.MATRICES[String(t.type)];if(!e)return Rs.NONE;const i=Number(t.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((r,a)=>Rs.IDENTITY[a]+(r-Rs.IDENTITY[a])*n),contrastGain:1}}}class xv{static ID="fatigue";id=xv.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return Rs.NONE}}class qo{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=qo.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:qo.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(qo.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return Rs.NONE;const n=i/qo.MEASURED_LEVEL*qo.MEASURED_LOSS_DB;return{colorMatrix:Rs.IDENTITY,contrastGain:10**(-n/20)}}}class du{static ALL=[new b0,new qo,new xv];static byId(t){return du.ALL.find(e=>e.id===t)}static perceptionOf(t){return du.ALL.reduce((e,i)=>Rs.combine(e,i.perceive(t?.[i.id]??{})),Rs.NONE)}static compact(t){const e={};for(const i of du.ALL){const n=t[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(e[i.id]=s)}return Object.keys(e).length>0?e:void 0}}class x0{constructor(t){this.names=t}body(t,e){return this.names?.bodies[t]??e}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,e){return this.names?.decorKinds[t]??e}point(t){return fc.point(t,this.names?.compassPoints)}towards(t){return fc.towards(t,this.names)}}class dr{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??dr.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,n){const{line:s}=t,r=[];s.name&&r.push(dr.kind(s,e).toLocaleLowerCase(n)),r.push(s.tracks>1?e.tracks.replace("{count}",String(s.tracks)):e.singleTrack);const a=s.voltageV?dr.voltage(s.voltageV,n):void 0;if(t.contactM!==void 0){const c=t.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?e.overheadVoltage.replace("{voltage}",a):e.overhead).replace("{height}",c))}else s.electrification==="third_rail"?r.push(a?e.thirdRailVoltage.replace("{voltage}",a):e.thirdRail):s.electrification==="none"&&r.push(e.notElectrified);return s.gaugeMm===dr.METRE_GAUGE_MM?r.push(e.metreGauge):s.gaugeMm!==dr.STANDARD_GAUGE_MM&&r.push(e.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(e.distance.replace("{distance}",i(t.distanceM))),s.services?.length?`${dr.name(s,e)}; ${r.join(", ")}`:`${dr.name(s,e)} — ${r.join(", ")}`}}class fu{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,i=!0){const n=fu.resolve(t,e);if(this.url=n,!n||!i){this.release();return}this.element.src=n,this.element.hidden=!1;const s=this.shown;this.shown=!0,s||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===fu.PUBLISHED_ORIGIN&&fu.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.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")}}const nN={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},sN=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,rN=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Ww=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,aN=20,oN=1;class _h{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(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("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}hc.unlock(this.context)}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const n=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=n==="hail"?Math.min(1,e*1.3+.2):n==="rain"?e:0,n!==this.ambientKey){this.ambientKey=n;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,n!=="none"&&this.startLoop(sN,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,c=>{this.ambientSource=c?.source,this.ambientGain=c?.gain,c&&(c.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/aN,1);const s=i>oN;if(s!==this.windActive){this.windActive=s;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(rN,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,c=>{this.windSource=c?.source,this.windGain=c?.gain,c&&(c.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:i,windSpeed:n}=this.requested;this.setAmbient(e,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(Ww,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const i=Math.min(1,Math.max(0,t)),n=e.createBufferSource();n.buffer=this.crackBuffer(e);const s=e.createBiquadFilter();s.type="lowpass",s.frequency.value=_h.CRACK_CUTOFF_HZ;const r=e.createGain();r.gain.value=i,n.connect(s).connect(r).connect(this.output(e)),n.start(),this.playOneShot(Ww,i,_h.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*_h.CRACK_DECAY_S*6),i=t.createBuffer(1,e,t.sampleRate),n=i.getChannelData(0);for(let s=0;s<e;s++){const r=s/t.sampleRate;n[s]=(Math.random()*2-1)*Math.min(1,r/.005)*Math.exp(-r/_h.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,n){if(e!==i()){t?.source.stop();return}n(t)}async startLoop(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=e,s.connect(r).connect(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(t,e,i=1){const n=this.context;if(n)try{const s=await this.getBuffer(t),r=n.createBufferSource();r.buffer=s,r.playbackRate.value=i;const a=n.createGain();a.gain.value=e,r.connect(a).connect(this.output(n)),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}class ya{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[n,s]=this.perifocalAxes(),r=Math.sqrt(ya.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*ya.stumpffC(n),a=e-i*i*i/Math.sqrt(ya.SUN_GM_AU3_PER_DAY2)*ya.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(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),i=Math.sqrt(ya.SUN_GM_AU3_PER_DAY2)*Math.abs(t),n=a=>{const c=this.inverseSemiMajorAxis*a*a,h=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*h)*a*a*a*ya.stumpffS(c)+h*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<ya.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const c=(r+s)/2;n(c)<i?r=c:s=c}return e*(r+s)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(t),s=Math.sin(t),r=Math.cos(e),a=Math.sin(e),c=Math.cos(i),h=Math.sin(i);return[{x:n*r-s*a*c,y:s*r+n*a*c,z:a*h},{x:-n*a-s*r*c,y:-s*a+n*r*c,z:r*h}]}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 i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const TS=[{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 cN{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 TS.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(t,e,i){const n=hi(e),s=this.earthPositionAt(n),r=this.apparentPositionOf(t,2451545+n.tt,s),a=this.subtract(r,s),c=this.length(r),h=this.length(a),l=this.tailEndAt(t,r,s,c,n,e,i),u=this.horizontalOf(a,n,e,i);return{apparition:t,position:u,...l,heliocentricDistanceAu:c,earthDistanceAu:h,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(t,c,h)}}static magnitudeAt(t,e,i){const n=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(n,t.peakMagnitude)}static tailEndAt(t,e,i,n,s,r,a){if(t.tailLengthAu===void 0)return{};const c=1+t.tailLengthAu/n,h=this.subtract({x:e.x*c,y:e.y*c,z:e.z*c},i),l=this.subtract(e,i);return{tailEnd:this.horizontalOf(h,s,r,a),tailLengthDeg:this.angleBetween(l,h)}}static apparentPositionOf(t,e,i){const n=this.orbitOf(t);let s=n.positionAt(e);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(e-a)}return s}static horizontalOf(t,e,i,n){const s=Ca(A6(),new ze(t.x,t.y,t.z,e)),r=Ca(hS(e),s),a=s1(e,new Na(n.lat,n.lng,n.elevationM),!0),c=new ze(r.x-a.x,r.y-a.y,r.z-a.z,e),h=Y0(c);return vv(h.ra,h.dec,i,n)}static earthPositionAt(t){return Ca(E6(),To(ft.Earth,t))}static julianDayOf(t){return 2451545+hi(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new ya(t.orbit);return this.orbits.set(t.id,i),i}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 i=(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,i)))*180/Math.PI}}const km=[{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 Xw{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return km.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),n=[];for(const s of km){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:fr.ofJ2000(s.raHours,s.decDeg,t,e),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return km.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,n=e-t.startJd;if(i.length===0||n<i[0][0]||n>i[i.length-1][0])return;let s=1;for(;s<i.length-1&&i[s][0]<n;)s++;const[r,a]=i[s-1]??i[0],[c,h]=i[s]??i[0];if(c===r)return a;const l=Math.min(1,Math.max(0,(n-r)/(c-r)));return a+l*(h-a)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const hN=[{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}],S0=6.5;class Um{static activeAt(t){return hN.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),n=this.dayOfYear(this.asDate(t.start)),s=this.dayOfYear(this.asDate(t.peak)),r=this.dayOfYear(this.asDate(t.end)),a=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),h=this.wrappedDelta(r,s);return a<0?a<-c?0:1+a/c:a>0?a>h?0:1-a/h:1}static observedRatePerHour(t,e,i,n=S0){if(e<=0)return 0;const s=S0-n;return t*Math.sin(e*Math.PI/180)/Math.pow(i,s)}static radiantPosition(t,e,i){return fr.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}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 i=t-e;return i>182?i-365:i<-182?i+365:i}}class Vi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=hi(t),n=new V0(0,i6(t).elon-90,1),s=Ca(D6(i),gv(n,i)),r=Y0(s);return vv(r.ra,r.dec,t,e)}static observedRatePerHour(t,e=S0){const i=Vi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),n=S0-e;return(Vi.QUIET_RATE_PER_HOUR+i)/Math.pow(Vi.POPULATION_INDEX,n)}static schedule(t){const e=new K0(t.seed^1542469173);return Js.schedule(t).map(i=>{const n=Vi.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Vi.turnAround(n,e.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:Vi.toHorizontal(a),bearingDeg:Vi.bearingFrom(a,n)}})}static turnAround(t,e){const[i,n]=Vi.basisAround(t),s=e*Math.PI/180;return{x:i.x*Math.cos(s)+n.x*Math.sin(s),y:i.y*Math.cos(s)+n.y*Math.sin(s),z:i.z*Math.cos(s)+n.z*Math.sin(s)}}static bearingFrom(t,e){const[i,n]=Vi.basisAround(t),s=t.x*e.x+t.y*e.y+t.z*e.z,r=Vi.normalise({x:e.x-t.x*s,y:e.y-t.y*s,z:e.z-t.z*s});return(Math.atan2(r.x*n.x+r.y*n.y+r.z*n.z,r.x*i.x+r.y*i.y+r.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Vi.normalise(Vi.cross(t,e));return[i,Vi.normalise(Vi.cross(t,i))]}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=Vi.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Vi.turnAround(e,t.bearingDeg),n=t.fromRadiantDeg*Math.PI/180;return Vi.toHorizontal({x:e.x*Math.cos(n)+i.x*Math.sin(n),y:e.y*Math.cos(n)+i.y*Math.sin(n),z:e.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,n=Math.cos(e);return{x:n*Math.sin(i),y:Math.sin(e),z:-n*Math.cos(i)}}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 $w="https://ufoathome.org/tle/index.json";class Gn{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??Gn.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($w)||t.push($w),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${Gn.FIRST_SNAPSHOT}T00:00:00Z`)-Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>t.getTime()>=Date.parse(n.from)-Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS&&t.getTime()<=Date.parse(n.to)+Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:n}=e,s=[],r=[];for(const a of Object.keys(i.kinds)){const c=await this.kindAt(a,t,i,n);s.push(...c),r.push(this.coverageOf(a,t,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,n){const s=e.getTime(),r=i.binDays*Gn.DAY_MS,a=Math.floor(s/r),c=s-a*r<r/2?a-1:a+1,h=new Set(i.kinds[t].bins),l=[a,c].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>h.has(m));if(l.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,n).href),...l.map(m=>this.binary(new URL(`${t}/${m}.bin`,n).href))]),f=new Map;for(const m of d)for(const g of Gn.decode(m,i.recordBytes)){const v=f.get(g.norad);(!v||Math.abs(g.epochMs-s)<Math.abs(v.epochMs-s))&&f.set(g.norad,g)}const p=[];for(const m of f.values()){const g=Math.abs(m.epochMs-s)/Gn.DAY_MS;if(g>Gn.MAX_ELEMENT_AGE_DAYS)continue;const v=u[m.norad]??{name:String(m.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||p.push({norad:m.norad,name:v.name,kind:t,launch:v.launch,stdMag:v.stdMag,elements:m,ageDays:g})}return p}coverageOf(t,e,i,n){const{from:s,to:r}=i.kinds[t],a=e.getTime(),c=Gn.MAX_ELEMENT_AGE_DAYS*Gn.DAY_MS,h=n?"covered":a<Date.parse(s)-c?"before":a>Date.parse(r)+c?"after":"gap";return{kind:t,status:h,from:s,to:r}}static decode(t,e){const i=new DataView(t),n=[];for(let s=0;s+e<=t.byteLength;s+=e)n.push({norad:i.getUint32(s,!0),epochMs:i.getFloat64(s+4,!0),bstar:i.getFloat32(s+12,!0),inclinationDeg:i.getFloat32(s+16,!0),raanDeg:i.getFloat32(s+20,!0),eccentricity:i.getFloat32(s+24,!0),argOfPerigeeDeg:i.getFloat32(s+28,!0),meanAnomalyDeg:i.getFloat32(s+32,!0),meanMotion:i.getFloat64(s+36,!0)});return n}loadIndex(){return this.index??=(async()=>{for(const 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 i=this.files.get(t);return i||(i=this.fetchImpl(t).then(n=>{if(!n.ok)throw new Error(`${t}: ${n.status}`);return e(n)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class lN{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=ci.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=ci.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:ci.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:ci.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class mc{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*mc.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=mc.degOver(t)/e;return i<1?1:Math.min(mc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Dn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return mc.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return Dn.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,n=e.fNumber??t.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return Dn.EYE;const s=e.focalLengthMm??t.frame?.focalLengthMm??Dn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=Dn.resolutionArcsec(t,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Dn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(t,e){const i=t.visualAid,n=Dn.EYE,s=e??t.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(t,e,i){const s=(t.detailUm??Dn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*Dn.ARCSEC_PER_RADIAN,r=1.22*Dn.WAVELENGTH_M/(i/1e3)*Dn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(t){return t/Dn.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=Dn.graspOf(t,e),n=Dn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:ki.focalLengthMmFor(t,e.fieldOfViewDeg);return Dn.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const Yw=111320,zl=Math.PI/180,uN=1.02,dN=1;class pu{static of(t,e){const i=pu.sightings(t,e);if(i.length<2)return;const n=pu.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,c=Math.tan(r.widthDeg/2*zl)===0?0:Math.tan(s.widthDeg/2*zl)/Math.tan(r.widthDeg/2*zl);if(c<uN)return;const h=a/(c-1),l=ci.sizeMAt(h,s.widthDeg),u=i.map(d=>({t:d.t,m:ci.distanceMAt(l,d.widthDeg)}));return{widthM:l,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===e)?.shape,s=n?.angular?.widthDeg,r=Le(t,i.t);return s===void 0||s<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:s,lat:r.lat,lng:r.lng,sightAzimuthDeg:n?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,n)=>i.t-n.t)}static baseline(t){let e;for(const i of t)for(const n of t){if(i.t>=n.t)continue;const s=pu.closedAlongSight(i,n),[r,a,c]=s>=0?[n,i,s]:[i,n,-s];c<dN||r.widthDeg<=a.widthDeg||(!e||c>e.closedM)&&(e={near:r,far:a,closedM:c})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*Yw,n=(e.lng-t.lng)*Yw*Math.cos(t.lat*zl),s=(t.sightAzimuthDeg??0)*zl;return i*Math.cos(s)+n*Math.sin(s)}}class is{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:is.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:is.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:is.atLeastNearest(t.derivedM),basis:"derived"};const e=is.largest(t.range?.minM,t.crossing?.behindM),i=is.smallest(t.range?.maxM,t.crossing?.inFrontM),n=e===void 0?void 0:e*is.MARGIN,s=i===void 0?void 0:i/is.MARGIN;return n!==void 0&&s!==void 0?{distanceM:is.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:is.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<is.CONVENTIONAL_M?{distanceM:is.atLeastNearest(s),basis:"bounded"}:{distanceM:is.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(is.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}class ss{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(t){const e=t?.flares;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>ss.bodiesOf(i))]}}static bodiesOf(t){const e={...ss.MJU_7,...t.flare},i=[],n=t.aircraft;if(n.model||n.sound){const s=t.releases.map(l=>l.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,c=n.model?{color:"#30333a",albedo:.15}:{transparency:1},h=l=>{const u=ss.aircraftAt(n,l);return{t:l,eastM:u.x,northM:u.y,altitudeM:u.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:c}};i.push({id:`${t.id}-aircraft`,title:t.title,model:n.model??{id:"sphere"},track:[h(r),h(a)],sound:n.sound})}return n.glow&&i.push(ss.glowBody(t,n.glow)),t.releases.forEach((s,r)=>i.push(ss.flareBody(t,e,s,r))),i}static aircraftAt(t,e){const i=t.headingDeg*Math.PI/180,n=(e-t.t)/1e3*t.speedMS;return{x:t.eastM+Math.sin(i)*n,y:t.northM+Math.cos(i)*n,z:t.altitudeM}}static burnShare(t,e){if(e<0||e>=t.burnS)return 0;if(e<.2)return e/.2;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static trajectory(t,e,i,n=ss.SAMPLE_MS){const s=t.aircraft,r=s.headingDeg*Math.PI/180,c={...ss.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-e.ejectionMS},h=(t.wind?.towardDeg??0)*Math.PI/180,l=t.wind?.speedMS??0,u=Math.sin(h)*l,d=Math.cos(h)*l,f=s.originElevationM??1e3,p=[{t:i,x:c.x,y:c.y,z:c.z}],m=ss.STEP_S,g=Math.round(n/1e3/m),v=Math.ceil(e.burnS/m);for(let M=1;M<=v;M++){const w=M*m,y=e.massKg-e.burnedKg*Math.min(1,w/e.burnS),b=1.225*Math.exp(-(c.z+f)/8500),S=c.vx-u,_=c.vy-d,x=c.vz,A=Math.hypot(S,_,x),I=.5*b*e.dragAreaM2*A/y;c.vx=(c.vx+I*m*u)/(1+I*m),c.vy=(c.vy+I*m*d)/(1+I*m),c.vz=(c.vz-ss.G*m)/(1+I*m),c.x+=c.vx*m,c.y+=c.vy*m,c.z+=c.vz*m,(M%g===0||M===v)&&p.push({t:i+Math.round(w*1e3),x:c.x,y:c.y,z:c.z})}return p}static glowBody(t,e){const i=e.sizeM/2,n=e.luminousIntensityCd/(Math.PI*i*i),s=[{t:e.fromT,lit:!0}];if(e.onS&&e.offS)for(let h=e.fromT,l=!0;h<e.untilT;l=!l)h+=(l?e.onS:e.offS)*1e3,h<e.untilT&&s.push({t:h,lit:!l});const r=(h,l)=>{const u=ss.aircraftAt(t.aircraft,h);return{t:h,eastM:u.x,northM:u.y,altitudeM:u.z,appearance:{color:e.color,luminanceCdM2:l?n:0}}},a=[];s.forEach(({t:h,lit:l},u)=>{u>0&&a.push(r(h-1,!l)),a.push(r(h,l))}),a[0]={...a[0],sizeM:{widthM:e.sizeM,lengthM:e.sizeM,heightM:e.sizeM},present:!0};const c=s[s.length-1];return a.push(r(e.untilT,c.lit),{t:e.untilT+1,present:!1}),{id:`${t.id}-glow`,title:t.title,explains:e.explains,model:{id:"sphere"},track:a}}static flareBody(t,e,i,n){const s=e.flameSizeM,r=s/2,a=e.luminousIntensityCd/(Math.PI*r*r),c=ss.trajectory(t,e,i.t),h=c.map((l,u)=>({t:l.t,eastM:l.x,northM:l.y,altitudeM:l.z,...u===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:e.color,luminanceCdM2:a*ss.burnShare(e,(l.t-i.t)/1e3),...u===0?{haloScale:1}:{}}}));return h.push({t:c[c.length-1].t+1,present:!1}),{id:`${t.id}-flare-${n+1}`,title:t.title,explains:i.explains,model:{id:"sphere"},track:h}}}class Re{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ff8a24",shape:"classic",paperColor:"#ffffff"};static FLAME_CDM2=5e3;static TITLE={en:"Sky lantern",fr:"Lanterne céleste",es:"Farolillo volador",it:"Lanterna volante"};static FLICKER=.15;static INSIDE_SHARE=2;static PAPER_FULL_CDM2=Re.COMMON.luminousIntensityCd/(Math.PI*Re.COMMON.widthM/2*Re.COMMON.heightM/2);static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static TURBULENCE={horizontalMS:.8,verticalMS:.3,timescaleS:30};static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(t){const e=t?.lanterns;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>Re.bodiesOf(i))]}}static bodiesOf(t){return Re.releasesOf(t).map((e,i)=>Re.lanternBody(t,e,i))}static releasesOf(t){const e=[...t.releases??[]],i=t.group;if(!i||!(i.count>0))return e;const n=Re.randomFrom(i.seed??1),s=c=>c.min+(c.max-c.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let c=0;c<i.count;c++){const h=i.fromT+r*c+(n()-.5)*r,l=a*Math.sqrt(n()),u=2*Math.PI*n();e.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,h))),explains:i.explains,eastM:Math.round(l*Math.sin(u)*10)/10,northM:Math.round(l*Math.cos(u)*10)/10,burnedS:i.burnedS,seed:Math.floor(n()*4294967296),lantern:{burnS:Math.round(s(i.burnS??{min:480,max:900})),insideExcessK:Math.round(s(i.insideExcessK??{min:125,max:175}))}})}return e}static randomFrom(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(t,e){return{...Re.COMMON,...t.lantern,...e.lantern}}static heatShare(t,e){if(e<0||e>=t.burnS)return 0;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static windAt(t,e){const i=Re.componentsOf(t.wind),n=t.windAloft;if(!n)return i;const s=Re.componentsOf(n),r=Math.max(0,Math.min(1,e/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(t,e,i=Re.SAMPLE_MS){const n=Re.typeOf(t,e),s=t.site,r=s.altitudeM??0,a=Math.max(0,e.burnedS??0),c=s.originElevationM??0,h=(t.airTemperatureC??10)+273.15,l={x:s.eastM+(e.eastM??0),y:s.northM+(e.northM??0),z:e.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*Re.heatShare(n,a)},u=Re.STEP_S,d=Math.max(1,Math.round(i/1e3/u)),f=Math.ceil(Math.max(0,n.burnS-a)/u),p=[{t:e.t,x:l.x,y:l.y,z:l.z,light:Re.heatShare(n,a),tiltDeg:0,tiltTowardDeg:0}],m=Re.gusts(t.turbulence??Re.TURBULENCE,Re.seedOf(e),u);for(let g=1;g<=f;g++){const v=g*u,M=a+v,w=Re.heatShare(n,M);l.excessK+=(n.insideExcessK*w-l.excessK)*Math.min(1,u/Re.COOLING_S);const y=l.z-r,b=h-Re.LAPSE*Math.max(0,y),S=101325*Math.exp(-(l.z+c)/8400),_=S/(Re.R_AIR*b),x=S/(Re.R_AIR*(b+l.excessK)),A=n.massKg-n.fuelKg*Math.min(1,M/n.burnS),I=(_-x)*n.envelopeVolumeM3*Re.G,D=A+x*n.envelopeVolumeM3+.5*_*n.envelopeVolumeM3,C=Re.windAt(t,y),N=m(),L={x:C.x+N.x,y:C.y+N.y,z:N.z},P=l.vx-L.x,z=l.vy-L.y,H=l.vz-L.z,$=.5*_*n.dragAreaM2*Math.hypot(P,z,H)/D;l.vx=(l.vx+$*u*L.x)/(1+$*u),l.vy=(l.vy+$*u*L.y)/(1+$*u),l.vz=(l.vz+$*u*L.z+(I-A*Re.G)/D*u)/(1+$*u);const Q=l.z<=r&&l.vz<=0;if(Q&&(l.vx=0,l.vy=0,l.vz=0),l.x+=l.vx*u,l.y+=l.vy*u,l.z=Math.max(r,l.z+l.vz*u),g%d===0||g===f){const Z=L.x-l.vx,nt=L.y-l.vy,ot=.5*_*n.dragAreaM2*Math.hypot(Z,nt,L.z-l.vz)*Math.hypot(Z,nt);p.push({t:e.t+Math.round(v*1e3),x:l.x,y:l.y,z:l.z,light:w,tiltDeg:Q?0:Math.atan2(ot,A*Re.G)*180/Math.PI,tiltTowardDeg:(Math.atan2(Z,nt)*180/Math.PI+360)%360})}}return p}static seedOf(t){return t.seed!==void 0?t.seed:Math.round(t.t)*2654435761+Math.round((t.eastM??0)*100)*40503+Math.round((t.northM??0)*100)>>>0}static gusts(t,e,i){const n=Re.randomFrom(e),s=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,n())))*Math.cos(2*Math.PI*n()),r=t.timescaleS>0?Math.exp(-i/t.timescaleS):0,a=Math.sqrt(1-r*r),c={x:t.horizontalMS*s(),y:t.horizontalMS*s(),z:t.verticalMS*s()};return()=>(c.x=r*c.x+a*t.horizontalMS*s(),c.y=r*c.y+a*t.horizontalMS*s(),c.z=r*c.z+a*t.verticalMS*s(),c)}static componentsOf(t){if(!t)return{x:0,y:0};const e=t.towardDeg*Math.PI/180;return{x:Math.sin(e)*t.speedMS,y:Math.cos(e)*t.speedMS}}static lanternBody(t,e,i){const n=Re.typeOf(t,e),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=Re.trajectory(t,e),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},c=Re.through(n.color,n.paperColor),h=r.map((l,u)=>({t:l.t,eastM:l.x,northM:l.y,altitudeM:l.z,...u===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(l.tiltTowardDeg),pitchDeg:-Math.round(l.tiltDeg*10)/10},appearance:{color:c,luminanceCdM2:s*l.light,...u===0?{albedo:.6,haloScale:1}:{}},lights:Re.lightsOf(s*l.light)}));return h.push({t:r[r.length-1].t+1,present:!1}),{id:`${t.id}-lantern-${i+1}`,title:Re.TITLE,explains:e.explains,model:{id:`ufoathome-sky-lantern-${n.shape}`},modelParameters:{paperColor:n.paperColor},flicker:Re.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:h}}static lightsOf(t){return{paper:t,"paper-inside":t*Re.INSIDE_SHARE,flame:t>0?Re.FLAME_CDM2*t/Re.PAPER_FULL_CDM2:0}}static through(t,e){const i=c=>[1,3,5].map(h=>parseInt(c.slice(h,h+2),16)/255),n=i(t),s=i(e),r=n.map((c,h)=>c*s[h]),a=Math.max(...n)/(Math.max(...r)||1);return"#"+r.map(c=>Math.round(Math.min(1,c*a)*255).toString(16).padStart(2,"0")).join("")}}class Sv{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=Sv.FIRST_DAY}}class fN{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,n){try{return await(await this.provider()).between(t,e,i,n)}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 pN="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",mN=[{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 fN(pN,o=>Sv.mayCover(o),async()=>new(await Ie(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-CX1R8zJF.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)}];class rs{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const n=rs.positionAt(t,i);if(!n)return;const s=_t.seenFrom(e,n.geo);if(!(s.altitudeDeg<0))return{track:t,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:rs.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(n=>rs.seenFrom(n,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,n=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*rs.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=e;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>rs.MAX_GAP_S*1e3)return;const c=a>0?(e-s.t)/a:0,h=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*c,l=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*c,lng:rs.wrapLongitude(s.lng+l*c),heightM:h*rs.FT_TO_M},altitudeFt:h,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(t,e,i){const n=rs.positionAt(t,i-500),s=rs.positionAt(t,i+500);if(!n||!s)return;const r=rs.unit(_t.seenFrom(e,n.geo)),a=rs.unit(_t.seenFrom(e,s.geo)),c=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(c)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const Kw="https://ufoathome.org/fireballs/index.json";class Vr{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??Vr.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(Kw)||t.push(Kw),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Vr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Vr.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=t&&r.t<=e):void 0}static seenFrom(t,e){const i=Vr.peakFraction(t),n={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},s=_t.seenFrom(e,n);if(!(s.altitudeDeg<0))return{record:t,peak:s,magnitude:t.peakMagnitude+5*Math.log10(s.distanceKm/_t.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,n=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:n,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Vr.COLOR,trainS:Vr.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 i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(t,i)),i}}const sh=Math.PI/180,Bl=180/Math.PI;class _i{constructor(t,e){this.timeline=t,this.tolerance=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),h=Math.max(_i.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+h||n.altitudeDeg>(c.high??i.altitudeDeg)+h||n.altitudeDeg<(c.low??i.altitudeDeg)-h},size(i,n){const s=t.law({kind:"angularSize",value:i},e);return n<(s.low??i)/_i.SIZE_TOLERANCE||n>(s.high??i)*_i.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[];for(const r of e){const a=_i.projectionOf(r,i,n?.(r));if(a)for(const c of r.explains){const h=this.timeline.getInterpolatedShapeAt(t,c);!h||h.transparency>=1||s.push({..._i.compare(c,r.id,{aim:h.aim,angular:h.angular},a,this.tolerance),title:h.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?_i.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(_i.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,h=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,l=(u,d)=>s?s.size(d,d*u):!_i.withinSize(u);return c!==void 0&&l(c,i.angular.widthDeg)&&r.push("width"),h!==void 0&&l(h,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:h,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:_i.outlineOf(t),s=i&&i.length>0?_i.centreOf(i):t,r=_i.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=_i.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=_i.cross(a,r);let h=1/0,l=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},m=_i.dot(p,r);if(m<=0)return;const g=Math.atan2(_i.dot(p,a),m),v=Math.atan2(_i.dot(p,c),m);h=Math.min(h,g),l=Math.max(l,g),u=Math.min(u,v),d=Math.max(d,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*Bl+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*Bl},angular:{widthDeg:(l-h)*Bl,heightDeg:(d-u)*Bl}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*sh,n=e.altitudeDeg*sh,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*sh);return Math.acos(Math.max(-1,Math.min(1,s)))*Bl}static withinSize(t){return t<=_i.SIZE_TOLERANCE&&t>=1/_i.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&bS.includes(r))for(let u=0;u<=_i.RINGS;u++){const d=u/_i.RINGS*Math.PI;for(let f=0;f<_i.SEGMENTS;f++){const p=f/_i.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*sh,h=t.attitude.pitchDeg*sh,l=t.attitude.rollDeg*sh;return s.map(([u,d,f])=>{const p=u*Math.cos(l)+f*Math.sin(l),m=-u*Math.sin(l)+f*Math.cos(l),g=d*Math.cos(h)-m*Math.sin(h),v=d*Math.sin(h)+m*Math.cos(h);return{eastM:t.eastM+p*Math.cos(c)+g*Math.sin(c),northM:t.northM-p*Math.sin(c)+g*Math.cos(c),upM:t.upM+v}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}Lb();const gN={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},vN="{name} — mag {mag}, {alt}° above the horizon",MN="{name} — {size}, {distance} away",yN="{name} — satellite, mag {mag}, {height} km up",wN={name:"Re-entry",piece:"{name} — mag {mag}, {height} km up, {distance} km away",fragment:"{name}, a fragment — mag {mag}, {height} km up, {distance} km away"},qw={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},bN={name:"Afterimage, in the eye",detail:"{name}: where the image of a light brighter than the Sun fell, the retina's pigment is bleached: for a few seconds it goes on glowing, white then coloured, and then what is seen there looks darker. It stays where it is in the field of view whichever way the eye turns, and takes minutes to fade."},xN={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},SN="satellites-change",EN="fireballs-change",AN="references-change",_N="aircraft-change",RS="rr0-confrontation",TN="{name} — mag {mag}, {alt}° below the horizontal",Fm="Credits",Zw="comet:",Jw="nova:",zm={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},RN=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,IN=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,DN=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,CN=-18,ON={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},mf={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Ee 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",Jr,jr,ec]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new T;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Gn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Vr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=mN[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Ee.trafficRuntimeLoading??=Ie(()=>import("./trafficRuntime-CfPqH9j0.js"),__vite__mapDeps([6,5]),import.meta.url).then(t=>Ee.trafficRuntime=t),Ee.trafficRuntimeLoading.catch(()=>{Ee.trafficRuntimeLoading=void 0}),Ee.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new _h;vehicleAudio=new EA;aircraftAudio;vehicleHearing=new Gf;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();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 i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const n=(t.clientX-i.left)/i.width*2-1,s=1-(t.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(n,s)?this.sceneRenderer.pickGhostAt(n,s)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>Ee.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(t){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(t.clientX-i.left)/i.width*e.width,s=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(t.clientX-i.left)/i.width*2-1,a=-((t.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const c=this.pickAt(r,a,!0,t.altKey);c?this.showHoverTooltip(t,t.altKey&&c.detail?c.detail():c.name):this.hoverTooltip.hidden=!0,this.showGhostPath(c?.path,i)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),s=n(t.from),r=n(t.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[c,h,l,u]=Array.from(this.ghostPath.children);for(const d of[c,h])d.setAttribute("x1",String(s.x)),d.setAttribute("y1",String(s.y)),d.setAttribute("x2",String(r.x)),d.setAttribute("y2",String(r.y));l.setAttribute("cx",String(a.x)),l.setAttribute("cy",String(a.y)),u.setAttribute("cx",String(r.x)),u.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(t,e)){const x=r?.ghostTooltip??qw,A=x.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:A,detail:()=>x.dropDetail.replace("{name}",A)}}const a=this.sceneRenderer.pickBodyAt(t,e);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const c=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,h=c?this.interpretationShown?.bodies.find(x=>x.id===c):void 0,l=h?this.said.read(h.title)||(h.model.id==="figure"?s.decorKind("entity",zm.entity):void 0):void 0;if(c!==void 0&&l)return{kind:"body",id:c,name:l};const u=this.ufoElement.sighting.skyEvents?.beams,d=u?.length?this.sceneRenderer.pickBeamAt(t,e):void 0,f=d?u?.find(x=>x.id===d.id):void 0;if(d&&f){const x=this.said.read(f.title)||"Laser";return{kind:"beam",id:f.id,name:x,detail:()=>`${x} (${f.wavelengthNm} nm, ${f.powerW.toLocaleString()} W), ${this.distanceText(d.distanceM)}`}}const p=i?this.ghostPick(t,e):void 0;if(p)return p;if(this.sceneRenderer.pickAfterimageAt(t,e)){const x=this.naming.names?.afterimageTooltip??bN;return{kind:"afterimage",name:x.name,detail:()=>x.detail.replace("{name}",x.name)}}const m=this.pickDecorAt(t,e),g=m?this.ufoElement.sighting.decor.find(x=>x.id===m):void 0;if(g){const x=this.said.read(g.title)||s.decorKind(g.kind,zm[g.kind]);return{kind:"decor",id:g.id,name:x,detail:()=>this.decorTooltip(g,x)}}const v=this.sceneRenderer.pickRailwayAt(t,e);if(v){const x=r?.railwayTooltip??dr.ENGLISH;return{kind:"railway",id:v.line.id,name:dr.name(v.line,x),detail:()=>dr.detail(v,x,A=>this.distanceText(A))}}const M=this.trafficTooltipAt(t,e);if(M)return{kind:"traffic",name:M};const w=this.plumePickAt(t,e);if(w)return w;const y=this.sceneRenderer.pickSatelliteAt(t,e);if(y)return{kind:"satellite",name:(r?.satelliteTooltip??yN).replace("{name}",y.name).replace("{mag}",y.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(y.heightKm).toLocaleString())};const b=this.reentryPickAt(t,e);if(b)return b;const S=this.sceneRenderer.pickOpticsAt(t,e);if(S){const x=(r?.opticsTooltips??nN)[S.id].replace("{angle}",String(Math.round(S.angleDeg??0)));return{kind:"optics",id:S.id,name:x.split(" — ")[0],detail:()=>x}}const _=this.sceneRenderer.pickStarAt(t,e);if(_){const x=_.star.mag,A=_.altitudeDeg,I=A<0?r?.starTooltipBelow??TN:r?.starTooltip??vN,D=s.star(_.star);return{kind:"star",name:D,detail:()=>I.replace("{name}",D).replace("{mag}",x.toLocaleString(void 0,{maximumFractionDigits:Math.abs(x)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(A))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const i=this.ufoElement.canvasElement,n={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},s=`${Math.round(t/n.x)}:${Math.round(e/n.y)}`,r=performance.now(),a=this.ghostLights.get(s);if(a&&r-a.atMs<Ee.GHOST_LIGHT_KEPT_MS)return a.light;let c=this.shiningDecorNear(t,e,2*Math.max(n.x,n.y)),h;if(!c)for(const[l,u]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+l*n.x,e+u*n.y,!1);if(d?.kind==="star")h??=d;else if(d){c=d;break}}return c??=this.shiningDecorNear(t,e,6*Math.max(n.x,n.y)),c??=h,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(s,{light:c??null,atMs:r}),c??null}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const n=this.naming.names?.ghostTooltip??qw,s=this.lightOfGhost(i.source.x,i.source.y)??void 0,r=(s?.kind==="star"?s.name.split(" — ")[0]:s?.name)??n.unnamed,a=i.ghost,h=(Si.scatters(a)?n.halo:a.cause==="glass"?n.double:n.ghost).replace("{name}",r),l=a.scale<0?n.opposite:a.scale===1?n.around:n.sameSide;return{kind:"ghost",id:s?.id,name:h,detail:()=>n.detail.replace("{name}",h).replace("{cause}",n.causes[a.cause??"lens"]).replace("{where}",l),path:{from:{x:a.scale*i.source.x,y:a.scale*i.source.y},to:i.source}}}shiningDecorNear(t,e,i){let n;for(const s of this.ufoElement.sighting.decor){if(!(s.kind==="streetlight"||s.kind==="trafficlight"||(s.lights?.length??0)>0||s.kind==="vehicle"&&s.lit))continue;const a=this.sceneRenderer.decorScreenBox(s.id);if(!a)continue;const c=Math.hypot(Math.max(a.minX-t,0,t-a.maxX),Math.max(a.minY-e,0,e-a.maxY));if(c>i||n&&c>=n.distance)continue;const h=this.said.read(s.title)||this.naming.decorKind(s.kind,zm[s.kind]);n={distance:c,pick:{kind:"decor",id:s.id,name:h}}}return n?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new ac(n=>{if(!Si.records(t.instrument)||!Si.falling(t.lens))return 0;const s=gl(t,n*1e3),r=Le(t,n*1e3);return(s.precipitationAmount??1)*Si.impactRate(s,t.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(t,e){const i=this.ufoElement.sighting.skyEvents?.launches,n=i?.length?this.sceneRenderer.pickPlumeAt(t,e):void 0,s=n?i?.find(h=>h.id===n.launchId):void 0;if(!n||!s)return;const r=this.naming.names?.plumeTooltip??xN,a=this.said.read(s.title)||s.vehicle?.mission||r.name,c=()=>n.release===void 0||n.release==="burn"?r.ascent:s.jets?.find((l,u)=>`jet:${l.id??u}`===n.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:s.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",c()).replace("{distance}",this.distanceText(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}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 i=h=>h.toLocaleString(void 0,{maximumFractionDigits:h<10?1:0}),n=ut.sizeOf(t),s=this.sceneRenderer.decorDistanceM(t.id),r=s===void 0?"":this.distanceText(s);return(this.naming.names?.decorTooltip??MN).replace("{name}",e).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(t){const e=t.startsWith(Zw)?t.slice(Zw.length):void 0,i=e?TS.find(r=>r.id===e):void 0;if(i)return this.naming.comet(i);const n=t.startsWith(Jw)?Xw.byId(t.slice(Jw.length)):void 0;if(n)return this.naming.nova(n);const s=gN[t];return s===void 0?t:this.naming.body(t,s)}get naming(){return this.sceneNaming}sceneNaming=new x0;namesLanguage="en";async loadSceneNames(){const t=C1(Ao.preferencesFor(this),P1);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await bb(t);t===this.namesLanguage&&this.applySceneNaming(new x0(e))}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 i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,c)=>{c>0&&s.append(" ");const h=document.createElement("span");h.className="scene-loader-word",h.setAttribute("aria-hidden","true");for(const l of a){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=l,h.append(u)}s.append(h),i++})};n(this.loaderNotVideo,t),i+=6,n(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t;const e=t.names?.credits??Fm;this.creditsButton.title=e,this.creditsButton.setAttribute("aria-label",e),t.names&&this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names?.compassPoints)}showHoverTooltip(t,e){this.hoverTooltip.textContent=e,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect(),n=t.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${t.clientY-i.top+12}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};hearDetonations(t,e,i,n){const s=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,r=this.detonationsFor;(!r||s!==r.key||t.length!==r.reentries.length||t.some((h,l)=>h!==r.reentries[l]))&&(this.detonationsFor={reentries:[...t],key:s,detonations:t.length?_t.detonationsOf(t,i):[]});const a=this.detonationsFor.detonations;if(n)return;const c=this.lastDetonationT;if(this.lastDetonationT=e,!(c===void 0||e<c||e-c>Ee.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const h of a)h.t>c&&h.t<=e&&this.weatherAudio.playDetonation(h.loudness)}reentryPickAt(t,e){const i=this.sceneRenderer.pickReentryAt(t,e);if(!i)return;const n=this.naming.names?.reentryTooltip??wN,s=this.detonationsFor?.reentries.find(u=>u.id===i.view.reentryId),r=(s?.title?this.said.read(s.title):"")||s?.object?.name||n.name,a=i.view.head,c=6371,h=Math.sqrt(c**2+a.distanceKm**2+2*c*a.distanceKm*Math.sin(a.altitudeDeg*Math.PI/180))-c;return{kind:"reentry",name:(i.view.fragmentId.includes(".")?n.fragment:n.piece).replace("{name}",r).replace("{mag}",i.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(h).toLocaleString()).replace("{distance}",Math.round(a.distanceKm).toLocaleString())}}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=Le(t,0),n=t.event.place?.[0],s=i?.lat??n?.lat,r=i?.lng??n?.lng;return e.length>0&&s!==void 0&&r!==void 0&&_t.detonationsOf(e,{lat:s,lng:r,heightM:i?.elevationM??0}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),dn.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(gl(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){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>=Ee.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(t,t),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),this.aircraftAudio?.setPaused(!t),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${RA}</style>${TA}`,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 lt(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(AN));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.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new fu(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.ufoElement=document.createElement(Km),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=s=>this.frozenMapOf(s),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&In.fill(n,this)}),this.creditsButton.title=Fm,this.creditsButton.setAttribute("aria-label",Fm),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(kb,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1)||this.detonates(s),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of Ee.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Es(Ao.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return i?{setting:vc.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}:void 0}travelHeadingAt(t,e){const i=Le(t,e);if(!i)return 0;for(const n of[400,-400]){const s=Le(t,e+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=de(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:n},n}traceLabels(t){const e=Ao.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const n of t){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Ee.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(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of Ee.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,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(t===Jr||t===jr||t===ec)&&i!==e&&this.forwardPlayerAttributes(),t===ec&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[Jr,jr,ec]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.sceneRenderer.setCompassForced(t)}lookToward(t){const e=Le(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:i,z:n}=de(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,n)<1)return this.setLookOffset(0,0);const s=(Math.atan2(i,-n)*180/Math.PI+360)%360;this.setLookOffset(((s-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.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed)}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,i,n=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,n)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}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=Eo.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),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=Wi.toCurrent(t);this.ufoElement.sightingData=e,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?Re.expand(ss.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new M0(this,()=>document.createElement(E0))}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}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}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 i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.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.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(t){const e=Ch.isEmpty(t)?"none":`${JSON.stringify(t)}
9223
9223
  ${this.documentUrl??""}
9224
9224
  ${fi.generation}`;if(e===this.frozenKey)return;const i=this.frozenKey!==void 0&&this.traffic?.set!==void 0;this.frozenKey=e,this.sceneRenderer.setTerrainProviders(w0.providers(t,this.documentUrl,this.liveTerrainProviders??Pb())),this.ufoElement.observerMapFrozen=this.frozenMapOf(t),i&&(this.traffic=void 0,this.decorMemo=void 0)}frozenMapOf(t){const e=Ch.held(t,"map");if(!e)return;const i=`${fi.address(e.src,this.documentUrl)}
9225
- ${fi.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:w0.map(e,this.documentUrl)}),this.frozenMap.imagery}frozenMap;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()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=ci.CANVAS_HEIGHT_PX,i=ki.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:Nm,url:this.getAttribute("star-catalog-src")??IN},{magnitudeLimit:Lm,url:this.getAttribute("deep-star-catalog-src")??DN}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>Nm?Lm:Nm;const n=await Or.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Lm||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=Dn.gainFor(t.instrument,{fNumber:Le(t,0)?.fNumber,fieldOfViewDeg:ln.fovOf(t,0),exposureSeconds:t.exposure});return Of(CN,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=ur.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,n=this.degreesPerPixelAt(t),s=mc.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(t).length,ur.instants(this.decorWithTraffic(this.ufoElement.sighting),Le(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(e.fromMs+e.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:e.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:ln.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:uh.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;e||this.sceneRenderer.setRecordingTime(t),this.setWeather(gl(i,t)),this.sceneRenderer.setInstrument(i.instrument,Le(i,t)?.fNumber),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??Ee.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??Ee.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=Le(i,t);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=Le(i,0),r=rh(i,0),a=Xo(i.event.time??{},n?.lng??mf.lng,i.event.utcOffsetHours),c=i.weatherSource!==void 0&&a?AA(a):void 0,h=Object.fromEntries(kf(rh(i,t)).map(C=>[C.id,HM(t,i.weatherTrack,r,s,n,C.id,C.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(HM(t,i.weatherTrack,r,s,n,void 0,c),h),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,t)}:mf),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(Dn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:ln.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,pr.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(Si.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3))),this.sceneRenderer.setPerception(du.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ni.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(Le(i,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const l=n?.lat??mf.lat,u=n?.lng??mf.lng,d=Xo(i.event.time??{},u,i.event.utcOffsetHours),f={lat:l,lng:u,elevationM:n?.elevationM??0};this.pushSatellitesAt(d,t,f),this.ensureFireballs(d);const p=i.skyEvents,m=[...p?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(m.length===0?[]:_t.viewsAt(m,t,{lat:l,lng:u,heightM:f.elevationM})),this.hearDetonations(m,t,{lat:l,lng:u,heightM:f.elevationM},e!==void 0);const g=m.filter(C=>_t.mayDazzle(C));this.sceneRenderer.setRetinaHistory(g.length===0?void 0:C=>{const N=Le(i,C),L={lat:N?.lat??l,lng:N?.lng??u,heightM:N?.elevationM??f.elevationM};return{views:_t.viewsAt(g,C,L),pose:N}},i),this.sceneRenderer.setBeams(p?.beams??Ee.NO_BEAMS);const v=p?.launches??[];if(this.sceneRenderer.setLaunchPlumes(v.length===0||!d?[]:Dt.viewsAt(v,t,{lat:l,lng:u,heightM:f.elevationM},Dt.sunDirectionAt(new Date(d.getTime()+t)))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!d),!d){this.sceneRenderer.setAstronomy(ON);return}const M=new Date(d.getTime()+t),w=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/mc.DEG_PER_SECOND*1e3)),y=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),b=`${Math.floor(M.getTime()/w)}|${Math.round(l/y)}|${Math.round(u/y)}|${Math.round(f.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(b===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=b;const S=tf("Sun",M,f),_=tf("Moon",M,f);let x=ji.separationOf(S,_)<1?ji.viewAt(M,f):void 0;if(x){const C=ji.offsetOf(S,_,x.separationDeg);if(x.obscuration>Ee.LIMB_FROM_OBSCURATION){const N=this.limbFor(M,f);N&&(x={...x,obscuration:1-qs.uncoveredFraction(N,x.sunRadiusDeg,C),limb:N})}x={...x,horizonShare:ji.horizonShare(x,C,S.altitudeDeg,S.azimuthDeg,Gr.distanceKm(M,f))}}const A={...S,magnitude:cm("Sun",M)-2.5*Math.log10(ji.beamFraction(x))};this.lastSun={altitudeDeg:A.altitudeDeg,azimuthDeg:A.azimuthDeg};const I={..._,phase:Y6(M),magnitude:cm("Moon",M),radiusDeg:Gr.apparentRadiusDeg(M,f)},D=$6.map(C=>({body:C,position:tf(C,M,f),magnitude:cm(C,M)}));this.sceneRenderer.setAstronomy({sun:A,moon:I,planets:D,comet:this.cometAt(M,f),novae:Xw.appearancesAt(M,f).map(({outburst:C,position:N,magnitude:L})=>({id:C.id,position:N,magnitude:L})),stars:this.starCatalog?{catalog:this.starCatalog,date:M,observer:f}:void 0,frame:{date:M,observer:f},localHour:((M.getUTCHours()+M.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(u/15)))%24+24)%24,eclipse:x}),this.ufoElement.setSunAltitude(A.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,uu.load(RN).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const n=qs.profile(t,e,this.limbRelief);return this.limbCache={profile:n,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},n}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(t.getTime()+e),s=[];for(const r of this.satellites.passes.positionsAt(n,i,-1))r.magnitude!==void 0&&s.push({norad:r.object.norad,name:r.object.name,position:{altitudeDeg:r.altitudeDeg,azimuthDeg:r.azimuthDeg},magnitude:r.magnitude,heightKm:r.heightKm});this.sceneRenderer.setSatellites(s)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=t?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!Vr.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,Ee.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(c=>Vr.asReentry(c,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(EN)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const n=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:n},n}seatedDecor(t,e){if(!t.some(r=>r.observerKeyframes?.length))return t;const i=t.map(r=>{if(!r.observerKeyframes?.length)return"";const a=TM(r,e);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===t&&n.seats===i)return n.seated;const s=t.map(r=>{if(!r.observerKeyframes?.length)return r;const a=TM(r,e);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:t,seats:i,seated:s},s}ensureTraffic(t){const e=Le(t,0),i=e?.lng===void 0?void 0:Xo(t.event.time??{},e.lng,t.event.utcOffsetHours),n=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=Ee.aircraftProviders.get(this.aircraftSource.id);if(a||Ee.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const c={key:r,status:"loading",startMs:s,observer:{lat:e.lat,lng:e.lng}};this.traffic=c;const h={lat:e.lat,lng:e.lng,heightM:e.elevationM??0},l=rs.MAX_GAP_S*1e3,u=Ee.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:e.elevationM??0},f=(p,m)=>p.TrafficDecor.from(c.tracks??[],h,s,p.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:g=>this.sunElevationAt(g,d)});a.between(h,s-u,s+n+l).then(async p=>{if(this.traffic!==c)return;if(p.status!=="found"){c.status=p.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let m;try{m=await Ee.loadTrafficRuntime()}catch{this.traffic===c&&(c.status="unavailable",this.announceTraffic());return}this.traffic===c&&(c.status="ready",c.tracks=p.tracks,c.set=f(m),this.startAircraftSound(c,m),this.announceTraffic(),this.describeTraffic(a,c,m,f),c.set.shown>0&&(this.readUpperAir(c,m,s-u,s+n+l),this.readTrailTraffic(a,c,m,h,s-Ee.TRAIL_LOOKBACK_MS,s+n+l)))})}trafficSunlight(t){const e=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return e;for(const[r,a]of n.presence){if(t<a.fromMs||t>a.untilMs)continue;const c=n.flights.get(r),h=c?rs.positionAt(c,i.startMs+t):void 0;h&&e.set(r,{heightM:h.geo.heightM,sunElevationDeg:cs.sunElevationDeg(s,i.observer,h.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=Ee.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const n=Ee.trafficRuntime;if(!n)return;const s=e.descriptions?.get(Pn.keyOf(i)),r=Le(this.ufoElement.sighting,this.lastTimeMs),a={lat:e.observer.lat,lng:e.observer.lng,heightM:r?.elevationM??0},c=n.AmbientNoise.dbA(gl(this.ufoElement.sighting,this.lastTimeMs)),h=n.TrafficInfos.at(i,s,a,e.startMs+this.lastTimeMs,{ambientDbA:c}),l=h&&this.contrailAt(t,this.lastTimeMs);return h&&l?{...h,contrail:l}:h}contrailAt(t,e){const i=this.traffic?.contrails?.find(s=>s.id===t);if(!i)return;let n;for(const s of i.points){if(s.tMs>e)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){!t.set||!t.observer||(t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,Pn.keyOf,{...t.observer,heightM:0},{ambientDbA:e.AmbientNoise.BASE_DB_A}))}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=Ee.trafficRuntime;if(!n){i.setVoices([]);return}const s=Le(t,e),r=gl(t,e),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},c=this.trafficVoices(e,s,a,n),h=t.event.place?.[0],l={lat:s?.lat??h?.lat,lng:s?.lng??h?.lng};l.lat!==void 0&&l.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,c.push(...this.decorAircraftHearing.voices(t,e,{lat:l.lat,lng:l.lng,heightM:s?.elevationM??0},a,u=>this.decorModelSounds.get(u.model?.id??""))),c.push(...this.bodyVoices(t,e,a,n)),c.sort((u,d)=>d.levelDbA-u.levelDbA),c.length=Math.min(c.length,4)),i.setVoices(c,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(Ee.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(Ee.trafficRuntime):Ee.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,n){const s=this.interpretationShown,r=t.event.place?.[0];if(!s||!r||!s.bodies.some(f=>f.sound))return[];const a=this.sceneRenderer.bodyGround,c=f=>zt.eyeOf(t,f,a),h=c(e);if(!h)return[];const l=new Map,u=(f,p)=>{let m=l.get(f.id);return m||l.set(f.id,m=new zt(f,a,c)),m.at(p)};this.bodyHearing??=new n.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,u,h,r,e,d,i)}trafficVoices(t,e,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:e?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,Pn.keyOf,a,s.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length!==0){for(const i of e){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||Ee.trafficRuntime){!this.aircraftAudio&&Ee.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Ee.trafficRuntime));return}Ee.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio;return e.setLevel(this.ufoElement.level),this.interacted&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"),e}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(_N)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,n){if(!t.describe||!e.set||!e.tracks)return;const s=new Set([...e.set.flights.values()].map(h=>Pn.keyOf(h))),r=e.tracks.filter(h=>s.has(Pn.keyOf(h))&&h.points.length>0),a=new Map,c=new Map;await Promise.all(r.map(async h=>{const l=new Date(h.points[0].t).toISOString().slice(0,10),u=await t.describe(h,l).catch(()=>{});u&&(c.set(Pn.keyOf(h),u),a.set(Pn.keyOf(h),i.AircraftModels.of(u)))})),!(this.traffic!==e||a.size===0)&&(e.descriptions=c,e.models=a,e.set=n(i,a),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,n,s,r){if(e.startMs===void 0)return;const a=await t.between(n,s,r).catch(()=>{});if(this.traffic!==e||a?.status!=="found")return;const c=a.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),h=new Map(e.models??[]);if(t.describe&&await Promise.all(c.filter(u=>u.points.length>0&&!h.has(Pn.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&h.set(Pn.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const l=i.TrafficDecor.from(c,n,e.startMs,Ee.TRAIL_MAX_AIRCRAFT,{models:h});e.trailSet=Ee.alignTrailIds(l,e.set),e.models=new Map([...h,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[a,c]of e.flights){const h=e.presence.get(a);if(h)for(const[l,u]of t.flights){const d=t.presence.get(l);!d||Pn.keyOf(u)!==Pn.keyOf(c)||d.fromMs<=h.untilMs&&h.fromMs<=d.untilMs&&i.set(l,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=e.objects.filter(a=>!s.has(a.id));return{...t,objects:[...t.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...t.presence].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.presence.get(a.id)])]),flights:new Map([...[...t.flights].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.flights.get(a.id)])])}}async readUpperAir(t,e,i,n){if(!t.observer)return;const s=Ch.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(s){const h=fi.address(s.src,this.documentUrl);r=Ee.upperAirProviders.get(h),r||Ee.upperAirProviders.set(h,r=new Ah(fi.json(h)))}else{const h=this.upperAirSource??e.UPPER_AIR_SOURCES[0];r=Ee.upperAirProviders.get(h.id),r||Ee.upperAirProviders.set(h.id,r=h.create())}const a={lat:t.observer.lat,lng:t.observer.lng},c=await r.between(a,i,n);this.traffic!==t||c.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:c}),t.air=c.samples,t.airSource=c.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,n=i?.trailSet??i?.set,s=this.lastSun;if(!i||!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const r of i.contrails){const a=n.presence.get(r.id),c=n.flights.get(r.id);if(!a||!c)continue;const h=rs.positionAt(c,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,t)));h&&e.set(r.id,{heightM:h.geo.heightM,sunElevationDeg:cs.sunElevationDeg(s,i.observer,h.geo)})}return e}sunElevationAt(t,e){const i=tf("Sun",new Date(t.t),e);return cs.sunElevationDeg(i,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){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??Ee.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(SN)))},s=Ee.tleArchive;(async()=>{if(!await s.covers(t))return n("outside");const[r,a]=await Promise.all([s.at(t),De(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const 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(Pn.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,n=Le(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!e||r===void 0||a===void 0))return e.passes.positionsAt(t,{lat:r,lng:a,elevationM:n?.elevationM??0})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,n=Le(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!e||r===void 0||a===void 0)return[];const c=Xo(i.event.time??{},a,i.event.utcOffsetHours);if(!c)return[];const h=Math.min(Math.max(t,0),4*36e5),l={lat:r,lng:a,elevationM:n?.elevationM??0},u=JSON.stringify([this.satellitesFor,c.getTime(),r,a,l.elevationM,h]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(h/1e3/600)),f=e.passes.passesDuring(c,new Date(c.getTime()+h),l,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=cN.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=e.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(t),a=new Map,c=new Map,h=new Set;for(const p of i.sourceIds){const m=i.getInterpolatedShapeAt(t,p);if(!m)continue;const g={...m,bounds:{...m.bounds,x:m.bounds.x+s.x,y:m.bounds.y+s.y}};a.set(p,g);const v=m.aim?this.sceneRenderer.screenPointOf(lr.directionOf(m.aim,this.directionScratch)):{ndcX:(g.bounds.x+g.bounds.width/2)/n.width*2-1,ndcY:-((g.bounds.y+g.bounds.height/2)/n.height*2-1)},M=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,w=M?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,p):{};h.add(p),(M||m.aim)&&h.delete(p);const y=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),b=this.sizeEstimateOf(p);b.add(y,w);const S=pu.of(e,p);c.set(p,is.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:S&&y>0?ci.distanceMAt(S.widthM,y):void 0,range:b.distanceRangeAt(y),crossing:w}))}for(const[p,m]of a)for(const[g,v]of a){if(g===p||v.transparency>=1||v.bounds.width*v.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=v.bounds.x&&m.bounds.y>=v.bounds.y&&m.bounds.x+m.bounds.width<=v.bounds.x+v.bounds.width&&m.bounds.y+m.bounds.height<=v.bounds.y+v.bounds.height))continue;const w=c.get(g);w&&c.set(p,{distanceM:w.distanceM*.999,basis:w.basis});break}this.depths=c;const l=i.sourceIds,u=[];for(const[p,m]of a)u.push({sourceId:p,shape:m,distanceM:c.get(p).distanceM,renderOrder:l.indexOf(p),aim:m.aim,hidden:h.has(p)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const d=Le(e,t),f=(d?.rollDeg??0)+ni.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(u,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:ki.starPointsOf(e.instrument,d?.fNumber),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.interpretationShown=Re.expand(ss.expand(t)),this.ufoElement.playerTitle=t?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(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,i){const n=this.sceneRenderer.bodyGround,s=zt.eyeOf(this.ufoElement.sighting,i,n);return s?zt.lineOfSightMeetsGround(s,t,e,n):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>zt.eyeOf(n,d,i),r=new zt(t,i,s).at(e),a=s(e);if(!r||!a)return;const c=r.eastM-a.eastM,h=r.northM-a.northM,l=r.upM-a.upM,u=Math.hypot(c,h);return{azimuthDeg:(Math.atan2(c,h)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(l,u)*180/Math.PI,distanceM:Math.hypot(u,l),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=c=>zt.eyeOf(n,c,i),r=new zt(t,i,s).at(e),a=s(e);return r&&a?_i.projectionOf(r,a):void 0}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>zt.eyeOf(n,p,i),r=new zt(t,i,s),a=r.at(e)?e:t.track[0]?.t,c=a===void 0?void 0:r.at(a),h=a===void 0?void 0:s(a);if(!c||!h)return;const l=c.eastM-h.eastM,u=c.northM-h.northM,d=c.upM-h.upM,f=Math.hypot(l,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(l,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,c=p=>zt.eyeOf(n,p,a);i&&(s=i.bodies.map(p=>new zt(p,a,c).at(t)).filter(p=>p!==void 0));const h=rh(n,t),l=h.windDirectionDeg*Math.PI/180,u={x:h.windSpeed*Math.sin(l),z:-h.windSpeed*Math.cos(l)};this.sceneRenderer.setBodies(s,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(t):void 0;if(d&&(r=new _i(n.timeline,this.confrontationTolerance).at(t,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!e)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(RS,{detail:r})))}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 i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(n)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const n=this.lastLightningT;if(this.lastLightningT=e,n===void 0||e<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=e).pop();s&&rh(t,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(t){const e=rh(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=t.event.time,s=t.event.place?.[0],r=n?.year!==void 0?Xo(n,s?.lng??0,t.event.utcOffsetHours):void 0,a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=dn.schedule({durationMs:a,seed:c,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],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,n=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?Xo(i,e.lng,t.event.utcOffsetHours):void 0;if(!n||e?.lat===void 0||e.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:e.lat,lng:e.lng,elevationM:0},r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(e.lat*1e3),c=Vi.schedule({ratePerHour:Vi.observedRatePerHour(Vi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Vi.TYPICAL_VELOCITY_KM_S,seed:a}),h=Um.activeAt(n).map(u=>{const d=Um.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:Um.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!h||h.rate<=0){this.sceneRenderer.setMeteorShower(c,0,0);return}const l=Js.schedule({ratePerHour:h.rate,durationMs:r,velocityKmS:h.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...l,...c],h.position.altitudeDeg,h.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 i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>Js.magnitudeOf(r)<=e).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const n=i[t%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,n=i.frame,s=Le(e,t),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=ki.focalLengthMmFor(i,ln.fovOf(e,t));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return $r.of(e.instrument,ci.CANVAS_HEIGHT_PX,ln.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new lN,this.sizeEstimates.set(t,e)),e}}const E0="rr0-scene";function IS(){Lb(),customElements.get(E0)||customElements.define(E0,Ee)}const PN={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",speed:"Speed",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",referenceGhosts:"Ghosts in the picture",referenceFindGhosts:"Look for ghosts",referenceGhostsSearching:"Looking…",referenceGhostsFound:"{count} ghosts found, each across the lens's axis from its light.",referenceGhostsFoundScaled:"{count} ghosts found, each at {scale} times its light's offset from the lens's axis.",referenceGhostsLow:"Perhaps {count} ghost(s): too few to be sure.",referenceGhostsNone:"No ghost found: no faint spot lies across one point from a light.",referenceGhostsCropped:"The lens's axis is off the picture's centre: the picture was cropped.",referenceGhostsHide:"Hide ghosts",referenceGhostsShow:"Show ghosts",iso:"Sensitivity",isoTitle:"The film's speed, or the sensor's gain. Left empty, a device that sets its own exposure sets it; stated, it is set by hand, as in a phone's manual mode.",metering:"Metering",meteringDevice:"the device's own",meteringAverage:"the whole frame (older phones, camcorders)",meteringHighlights:"keeping highlights (recent phones)",meteringTitle:"How a device that sets its own exposure reads the light: by the mean of its whole frame, which burns out a bright light in a dark frame, or holding back so that a light taking up a fair part of it keeps its colour.",lensGlass:"Taken through",lensGlassNone:"the lens alone",lensGlassFilter:"a filter on the lens",lensGlassWindow:"a window",lensGlassWindscreen:"a windscreen",lensDrops:"Drops on the glass",lensDropsTitle:"0 to 1: how much of the outermost glass drops of water cover. Blank: from the rain or snow falling, unless the glass is sheltered",lensCondensation:"Condensation",lensCondensationTitle:"0 to 1: condensation on the glass, as on a lens taken from the warm into the cold. Blank: none",lensDirt:"Dirt",lensDirtTitle:"0 to 1: dirt, grease or fingerprints on the glass. Blank: none",lensSheltered:"Sheltered from the rain",lensShelteredTitle:"The outermost glass was out of the rain or snow: under a roof, or behind a windscreen whose wipers run",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",rareIceCrystals:"Rare crystals",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorTrafficLight:"Traffic light",decorCrossing:"Pedestrian crossing",decorRoadSign:"Road sign",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Yl={...PN,accountBy:"Account by",unnamedObserver:"Observer {n}",about:"About",close:"Close",observation:"Observation",date:"Date",location:"Location",case:"Case",description:"Description",source:"Source",basis:{measured:"measured",stated:"stated",derived:"derived",assumed:"assumed"},credits:"Credits",editThisObservation:"Edit this observation",share:"Share",embedObservation:"Embed the observation",back:"Back",shareScope:"Share",shareScopeCase:"Whole case",shareOpensOn:"Opens on",shareStartAt:"Start at",shareOptionLabels:"Show summary chips",shareOptionMap:"Open map",shareOptionMilestones:"Show moments",shareOptionCompare:"Compare account",showLabels:"Show what it states",interpretation:"Interpretation",account:"Account",interpretationBy:"{title}, by {by}",confrontation:"Against the account",confrontationDirection:"{deg}° off",confrontationWidth:"width ×{ratio}",confrontationHeight:"height ×{ratio}",showComparison:"Compare with the account",hideComparison:"Stop comparing with the account",hideLabels:"Hide what it states",variant:"Variant: {name}",verdicts:{consolidated:"compatible with consolidated biases",contested:"only by invoking contested biases",incompatible:"incompatible even at the bounds"},variantFields:{time:"Time",heading:"Heading",elevation:"Elevation",size:"Size",duration:"Duration",sweep:"Sweep across the sky"},variantReadings:{grouped:"lights read as one body","still-seen-moving":"a still light seen moving","moving-seen-still":"a moving light seen hovering","brightening-as-approach":"growing brighter read as coming nearer"}},NN=Object.freeze(Object.defineProperty({__proto__:null,sightingMessages_en:Yl},Symbol.toStringTag,{value:"Module"}));class Wr{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,i){const n=new URL(`${t}.mjs`,e);return n.href.startsWith(`${Wr.CDN}/`)?`${i}/lib/${t}.mjs`:(n.pathname=n.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),n.href)}static VERSION_PARAMETER="v";static freezable(t){return t in Wr.DIRECTORIES}static frozenLink(t,e){const i=new URL(t);return i.searchParams.set(Wr.VERSION_PARAMETER,e),i.href}static frozen(t,e){return`${Wr.CDN}/${Wr.PACKAGE}@${e}/${Wr.DIRECTORIES[t]}/${t}.mjs`}}class ju{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:ju.PRODUCTION}catch{return ju.PRODUCTION}}}const w1={share:"Share",close:"Close",link:"Link",embed:"Embed",copy:"Copy",copied:"Copied",freeze:"Freeze version {version}",freezeHint:"The embed keeps the rendering of this version of UFO@home, loaded from jsDelivr, and gets none of the later fixes. Unticked, it follows each release.",unsaved:"The link opens the file at its address: your unsaved changes are not in it. Save the file there first.",unavailable:"Only a file loaded from an address can be shared: put it online, then open it from its address."},LN=Object.freeze(Object.defineProperty({__proto__:null,shareMessages_en:w1},Symbol.toStringTag,{value:"Module"})),kN=`
9225
+ ${fi.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:w0.map(e,this.documentUrl)}),this.frozenMap.imagery}frozenMap;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()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=ci.CANVAS_HEIGHT_PX,i=ki.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:Nm,url:this.getAttribute("star-catalog-src")??IN},{magnitudeLimit:Lm,url:this.getAttribute("deep-star-catalog-src")??DN}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>Nm?Lm:Nm;const n=await Or.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Lm||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=Dn.gainFor(t.instrument,{fNumber:Le(t,0)?.fNumber,fieldOfViewDeg:ln.fovOf(t,0),exposureSeconds:t.exposure});return Of(CN,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=ur.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,n=this.degreesPerPixelAt(t),s=mc.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(t).length,ur.instants(this.decorWithTraffic(this.ufoElement.sighting),Le(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(e.fromMs+e.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:e.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:ln.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:uh.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;e||this.sceneRenderer.setRecordingTime(t),this.setWeather(gl(i,t)),this.sceneRenderer.setInstrument(i.instrument,Le(i,t)?.fNumber),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??Ee.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??Ee.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=Le(i,t);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=Le(i,0),r=rh(i,0),a=Xo(i.event.time??{},n?.lng??mf.lng,i.event.utcOffsetHours),c=i.weatherSource!==void 0&&a?AA(a):void 0,h=Object.fromEntries(kf(rh(i,t)).map(C=>[C.id,HM(t,i.weatherTrack,r,s,n,C.id,C.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(HM(t,i.weatherTrack,r,s,n,void 0,c),h),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,t)}:mf),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(Dn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:ln.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,pr.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(Si.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3))),this.sceneRenderer.setPerception(du.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ni.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(Le(i,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const l=n?.lat??mf.lat,u=n?.lng??mf.lng,d=Xo(i.event.time??{},u,i.event.utcOffsetHours),f={lat:l,lng:u,elevationM:n?.elevationM??0};this.pushSatellitesAt(d,t,f),this.ensureFireballs(d);const p=i.skyEvents,m=[...p?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(m.length===0?[]:_t.viewsAt(m,t,{lat:l,lng:u,heightM:f.elevationM})),this.hearDetonations(m,t,{lat:l,lng:u,heightM:f.elevationM},e!==void 0);const g=m.filter(C=>_t.mayDazzle(C));this.sceneRenderer.setRetinaHistory(g.length===0?void 0:C=>{const N=Le(i,C),L={lat:N?.lat??l,lng:N?.lng??u,heightM:N?.elevationM??f.elevationM};return{views:_t.viewsAt(g,C,L),pose:N}},i),this.sceneRenderer.setBeams(p?.beams??Ee.NO_BEAMS);const v=p?.launches??[];if(this.sceneRenderer.setLaunchPlumes(v.length===0||!d?[]:Dt.viewsAt(v,t,{lat:l,lng:u,heightM:f.elevationM},Dt.sunDirectionAt(new Date(d.getTime()+t)))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!d),!d){this.sceneRenderer.setAstronomy(ON);return}const M=new Date(d.getTime()+t),w=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/mc.DEG_PER_SECOND*1e3)),y=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),b=`${Math.floor(M.getTime()/w)}|${Math.round(l/y)}|${Math.round(u/y)}|${Math.round(f.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(b===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=b;const S=tf("Sun",M,f),_=tf("Moon",M,f);let x=ji.separationOf(S,_)<1?ji.viewAt(M,f):void 0;if(x){const C=ji.offsetOf(S,_,x.separationDeg);if(x.obscuration>Ee.LIMB_FROM_OBSCURATION){const N=this.limbFor(M,f);N&&(x={...x,obscuration:1-qs.uncoveredFraction(N,x.sunRadiusDeg,C),limb:N})}x={...x,horizonShare:ji.horizonShare(x,C,S.altitudeDeg,S.azimuthDeg,Gr.distanceKm(M,f))}}const A={...S,magnitude:cm("Sun",M)-2.5*Math.log10(ji.beamFraction(x))};this.lastSun={altitudeDeg:A.altitudeDeg,azimuthDeg:A.azimuthDeg};const I={..._,phase:Y6(M),magnitude:cm("Moon",M),radiusDeg:Gr.apparentRadiusDeg(M,f)},D=$6.map(C=>({body:C,position:tf(C,M,f),magnitude:cm(C,M)}));this.sceneRenderer.setAstronomy({sun:A,moon:I,planets:D,comet:this.cometAt(M,f),novae:Xw.appearancesAt(M,f).map(({outburst:C,position:N,magnitude:L})=>({id:C.id,position:N,magnitude:L})),stars:this.starCatalog?{catalog:this.starCatalog,date:M,observer:f}:void 0,frame:{date:M,observer:f},localHour:((M.getUTCHours()+M.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(u/15)))%24+24)%24,eclipse:x}),this.ufoElement.setSunAltitude(A.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,uu.load(RN).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const n=qs.profile(t,e,this.limbRelief);return this.limbCache={profile:n,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},n}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(t.getTime()+e),s=[];for(const r of this.satellites.passes.positionsAt(n,i,-1))r.magnitude!==void 0&&s.push({norad:r.object.norad,name:r.object.name,position:{altitudeDeg:r.altitudeDeg,azimuthDeg:r.azimuthDeg},magnitude:r.magnitude,heightKm:r.heightKm});this.sceneRenderer.setSatellites(s)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=t?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!Vr.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,Ee.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(c=>Vr.asReentry(c,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(EN)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const n=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:n},n}seatedDecor(t,e){if(!t.some(r=>r.observerKeyframes?.length))return t;const i=t.map(r=>{if(!r.observerKeyframes?.length)return"";const a=TM(r,e);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===t&&n.seats===i)return n.seated;const s=t.map(r=>{if(!r.observerKeyframes?.length)return r;const a=TM(r,e);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:t,seats:i,seated:s},s}ensureTraffic(t){const e=Le(t,0),i=e?.lng===void 0?void 0:Xo(t.event.time??{},e.lng,t.event.utcOffsetHours),n=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=Ee.aircraftProviders.get(this.aircraftSource.id);if(a||Ee.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const c={key:r,status:"loading",startMs:s,observer:{lat:e.lat,lng:e.lng}};this.traffic=c;const h={lat:e.lat,lng:e.lng,heightM:e.elevationM??0},l=rs.MAX_GAP_S*1e3,u=Ee.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:e.elevationM??0},f=(p,m)=>p.TrafficDecor.from(c.tracks??[],h,s,p.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:g=>this.sunElevationAt(g,d)});a.between(h,s-u,s+n+l).then(async p=>{if(this.traffic!==c)return;if(p.status!=="found"){c.status=p.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let m;try{m=await Ee.loadTrafficRuntime()}catch{this.traffic===c&&(c.status="unavailable",this.announceTraffic());return}this.traffic===c&&(c.status="ready",c.tracks=p.tracks,c.set=f(m),this.startAircraftSound(c,m),this.announceTraffic(),this.describeTraffic(a,c,m,f),c.set.shown>0&&(this.readUpperAir(c,m,s-u,s+n+l),this.readTrailTraffic(a,c,m,h,s-Ee.TRAIL_LOOKBACK_MS,s+n+l)))})}trafficSunlight(t){const e=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return e;for(const[r,a]of n.presence){if(t<a.fromMs||t>a.untilMs)continue;const c=n.flights.get(r),h=c?rs.positionAt(c,i.startMs+t):void 0;h&&e.set(r,{heightM:h.geo.heightM,sunElevationDeg:cs.sunElevationDeg(s,i.observer,h.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=Ee.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const n=Ee.trafficRuntime;if(!n)return;const s=e.descriptions?.get(Pn.keyOf(i)),r=Le(this.ufoElement.sighting,this.lastTimeMs),a={lat:e.observer.lat,lng:e.observer.lng,heightM:r?.elevationM??0},c=n.AmbientNoise.dbA(gl(this.ufoElement.sighting,this.lastTimeMs)),h=n.TrafficInfos.at(i,s,a,e.startMs+this.lastTimeMs,{ambientDbA:c}),l=h&&this.contrailAt(t,this.lastTimeMs);return h&&l?{...h,contrail:l}:h}contrailAt(t,e){const i=this.traffic?.contrails?.find(s=>s.id===t);if(!i)return;let n;for(const s of i.points){if(s.tMs>e)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){!t.set||!t.observer||(t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,Pn.keyOf,{...t.observer,heightM:0},{ambientDbA:e.AmbientNoise.BASE_DB_A}))}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=Ee.trafficRuntime;if(!n){i.setVoices([]);return}const s=Le(t,e),r=gl(t,e),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},c=this.trafficVoices(e,s,a,n),h=t.event.place?.[0],l={lat:s?.lat??h?.lat,lng:s?.lng??h?.lng};l.lat!==void 0&&l.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,c.push(...this.decorAircraftHearing.voices(t,e,{lat:l.lat,lng:l.lng,heightM:s?.elevationM??0},a,u=>this.decorModelSounds.get(u.model?.id??""))),c.push(...this.bodyVoices(t,e,a,n)),c.sort((u,d)=>d.levelDbA-u.levelDbA),c.length=Math.min(c.length,4)),i.setVoices(c,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(Ee.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(Ee.trafficRuntime):Ee.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,n){const s=this.interpretationShown,r=t.event.place?.[0];if(!s||!r||!s.bodies.some(f=>f.sound))return[];const a=this.sceneRenderer.bodyGround,c=f=>zt.eyeOf(t,f,a),h=c(e);if(!h)return[];const l=new Map,u=(f,p)=>{let m=l.get(f.id);return m||l.set(f.id,m=new zt(f,a,c)),m.at(p)};this.bodyHearing??=new n.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,u,h,r,e,d,i)}trafficVoices(t,e,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:e?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,Pn.keyOf,a,s.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length!==0){for(const i of e){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||Ee.trafficRuntime){!this.aircraftAudio&&Ee.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Ee.trafficRuntime));return}Ee.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio;return e.setLevel(this.ufoElement.level),this.interacted&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"),e}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(_N)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,n){if(!t.describe||!e.set||!e.tracks)return;const s=new Set([...e.set.flights.values()].map(h=>Pn.keyOf(h))),r=e.tracks.filter(h=>s.has(Pn.keyOf(h))&&h.points.length>0),a=new Map,c=new Map;await Promise.all(r.map(async h=>{const l=new Date(h.points[0].t).toISOString().slice(0,10),u=await t.describe(h,l).catch(()=>{});u&&(c.set(Pn.keyOf(h),u),a.set(Pn.keyOf(h),i.AircraftModels.of(u)))})),!(this.traffic!==e||a.size===0)&&(e.descriptions=c,e.models=a,e.set=n(i,a),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,n,s,r){if(e.startMs===void 0)return;const a=await t.between(n,s,r).catch(()=>{});if(this.traffic!==e||a?.status!=="found")return;const c=a.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),h=new Map(e.models??[]);if(t.describe&&await Promise.all(c.filter(u=>u.points.length>0&&!h.has(Pn.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&h.set(Pn.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const l=i.TrafficDecor.from(c,n,e.startMs,Ee.TRAIL_MAX_AIRCRAFT,{models:h});e.trailSet=Ee.alignTrailIds(l,e.set),e.models=new Map([...h,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[a,c]of e.flights){const h=e.presence.get(a);if(h)for(const[l,u]of t.flights){const d=t.presence.get(l);!d||Pn.keyOf(u)!==Pn.keyOf(c)||d.fromMs<=h.untilMs&&h.fromMs<=d.untilMs&&i.set(l,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=e.objects.filter(a=>!s.has(a.id));return{...t,objects:[...t.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...t.presence].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.presence.get(a.id)])]),flights:new Map([...[...t.flights].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.flights.get(a.id)])])}}async readUpperAir(t,e,i,n){if(!t.observer)return;const s=Ch.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(s){const h=fi.address(s.src,this.documentUrl);r=Ee.upperAirProviders.get(h),r||Ee.upperAirProviders.set(h,r=new Ah(fi.json(h)))}else{const h=this.upperAirSource??e.UPPER_AIR_SOURCES[0];r=Ee.upperAirProviders.get(h.id),r||Ee.upperAirProviders.set(h.id,r=h.create())}const a={lat:t.observer.lat,lng:t.observer.lng},c=await r.between(a,i,n);this.traffic!==t||c.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:c}),t.air=c.samples,t.airSource=c.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,n=i?.trailSet??i?.set,s=this.lastSun;if(!i||!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const r of i.contrails){const a=n.presence.get(r.id),c=n.flights.get(r.id);if(!a||!c)continue;const h=rs.positionAt(c,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,t)));h&&e.set(r.id,{heightM:h.geo.heightM,sunElevationDeg:cs.sunElevationDeg(s,i.observer,h.geo)})}return e}sunElevationAt(t,e){const i=tf("Sun",new Date(t.t),e);return cs.sunElevationDeg(i,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){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??Ee.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(SN)))},s=Ee.tleArchive;(async()=>{if(!await s.covers(t))return n("outside");const[r,a]=await Promise.all([s.at(t),Ie(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const 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(Pn.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,n=Le(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!e||r===void 0||a===void 0))return e.passes.positionsAt(t,{lat:r,lng:a,elevationM:n?.elevationM??0})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,n=Le(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!e||r===void 0||a===void 0)return[];const c=Xo(i.event.time??{},a,i.event.utcOffsetHours);if(!c)return[];const h=Math.min(Math.max(t,0),4*36e5),l={lat:r,lng:a,elevationM:n?.elevationM??0},u=JSON.stringify([this.satellitesFor,c.getTime(),r,a,l.elevationM,h]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(h/1e3/600)),f=e.passes.passesDuring(c,new Date(c.getTime()+h),l,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=cN.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=e.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(t),a=new Map,c=new Map,h=new Set;for(const p of i.sourceIds){const m=i.getInterpolatedShapeAt(t,p);if(!m)continue;const g={...m,bounds:{...m.bounds,x:m.bounds.x+s.x,y:m.bounds.y+s.y}};a.set(p,g);const v=m.aim?this.sceneRenderer.screenPointOf(lr.directionOf(m.aim,this.directionScratch)):{ndcX:(g.bounds.x+g.bounds.width/2)/n.width*2-1,ndcY:-((g.bounds.y+g.bounds.height/2)/n.height*2-1)},M=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,w=M?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,p):{};h.add(p),(M||m.aim)&&h.delete(p);const y=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),b=this.sizeEstimateOf(p);b.add(y,w);const S=pu.of(e,p);c.set(p,is.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:S&&y>0?ci.distanceMAt(S.widthM,y):void 0,range:b.distanceRangeAt(y),crossing:w}))}for(const[p,m]of a)for(const[g,v]of a){if(g===p||v.transparency>=1||v.bounds.width*v.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=v.bounds.x&&m.bounds.y>=v.bounds.y&&m.bounds.x+m.bounds.width<=v.bounds.x+v.bounds.width&&m.bounds.y+m.bounds.height<=v.bounds.y+v.bounds.height))continue;const w=c.get(g);w&&c.set(p,{distanceM:w.distanceM*.999,basis:w.basis});break}this.depths=c;const l=i.sourceIds,u=[];for(const[p,m]of a)u.push({sourceId:p,shape:m,distanceM:c.get(p).distanceM,renderOrder:l.indexOf(p),aim:m.aim,hidden:h.has(p)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const d=Le(e,t),f=(d?.rollDeg??0)+ni.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(u,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:ki.starPointsOf(e.instrument,d?.fNumber),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.interpretationShown=Re.expand(ss.expand(t)),this.ufoElement.playerTitle=t?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(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,i){const n=this.sceneRenderer.bodyGround,s=zt.eyeOf(this.ufoElement.sighting,i,n);return s?zt.lineOfSightMeetsGround(s,t,e,n):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>zt.eyeOf(n,d,i),r=new zt(t,i,s).at(e),a=s(e);if(!r||!a)return;const c=r.eastM-a.eastM,h=r.northM-a.northM,l=r.upM-a.upM,u=Math.hypot(c,h);return{azimuthDeg:(Math.atan2(c,h)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(l,u)*180/Math.PI,distanceM:Math.hypot(u,l),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=c=>zt.eyeOf(n,c,i),r=new zt(t,i,s).at(e),a=s(e);return r&&a?_i.projectionOf(r,a):void 0}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>zt.eyeOf(n,p,i),r=new zt(t,i,s),a=r.at(e)?e:t.track[0]?.t,c=a===void 0?void 0:r.at(a),h=a===void 0?void 0:s(a);if(!c||!h)return;const l=c.eastM-h.eastM,u=c.northM-h.northM,d=c.upM-h.upM,f=Math.hypot(l,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(l,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,c=p=>zt.eyeOf(n,p,a);i&&(s=i.bodies.map(p=>new zt(p,a,c).at(t)).filter(p=>p!==void 0));const h=rh(n,t),l=h.windDirectionDeg*Math.PI/180,u={x:h.windSpeed*Math.sin(l),z:-h.windSpeed*Math.cos(l)};this.sceneRenderer.setBodies(s,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(t):void 0;if(d&&(r=new _i(n.timeline,this.confrontationTolerance).at(t,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!e)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(RS,{detail:r})))}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 i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(n)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const n=this.lastLightningT;if(this.lastLightningT=e,n===void 0||e<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=e).pop();s&&rh(t,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(t){const e=rh(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=t.event.time,s=t.event.place?.[0],r=n?.year!==void 0?Xo(n,s?.lng??0,t.event.utcOffsetHours):void 0,a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=dn.schedule({durationMs:a,seed:c,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],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,n=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?Xo(i,e.lng,t.event.utcOffsetHours):void 0;if(!n||e?.lat===void 0||e.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:e.lat,lng:e.lng,elevationM:0},r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(e.lat*1e3),c=Vi.schedule({ratePerHour:Vi.observedRatePerHour(Vi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Vi.TYPICAL_VELOCITY_KM_S,seed:a}),h=Um.activeAt(n).map(u=>{const d=Um.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:Um.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!h||h.rate<=0){this.sceneRenderer.setMeteorShower(c,0,0);return}const l=Js.schedule({ratePerHour:h.rate,durationMs:r,velocityKmS:h.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...l,...c],h.position.altitudeDeg,h.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 i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>Js.magnitudeOf(r)<=e).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const n=i[t%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,n=i.frame,s=Le(e,t),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=ki.focalLengthMmFor(i,ln.fovOf(e,t));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return $r.of(e.instrument,ci.CANVAS_HEIGHT_PX,ln.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new lN,this.sizeEstimates.set(t,e)),e}}const E0="rr0-scene";function IS(){Lb(),customElements.get(E0)||customElements.define(E0,Ee)}const PN={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",speed:"Speed",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",referenceGhosts:"Ghosts in the picture",referenceFindGhosts:"Look for ghosts",referenceGhostsSearching:"Looking…",referenceGhostsFound:"{count} ghosts found, each across the lens's axis from its light.",referenceGhostsFoundScaled:"{count} ghosts found, each at {scale} times its light's offset from the lens's axis.",referenceGhostsLow:"Perhaps {count} ghost(s): too few to be sure.",referenceGhostsNone:"No ghost found: no faint spot lies across one point from a light.",referenceGhostsCropped:"The lens's axis is off the picture's centre: the picture was cropped.",referenceGhostsHide:"Hide ghosts",referenceGhostsShow:"Show ghosts",iso:"Sensitivity",isoTitle:"The film's speed, or the sensor's gain. Left empty, a device that sets its own exposure sets it; stated, it is set by hand, as in a phone's manual mode.",metering:"Metering",meteringDevice:"the device's own",meteringAverage:"the whole frame (older phones, camcorders)",meteringHighlights:"keeping highlights (recent phones)",meteringTitle:"How a device that sets its own exposure reads the light: by the mean of its whole frame, which burns out a bright light in a dark frame, or holding back so that a light taking up a fair part of it keeps its colour.",lensGlass:"Taken through",lensGlassNone:"the lens alone",lensGlassFilter:"a filter on the lens",lensGlassWindow:"a window",lensGlassWindscreen:"a windscreen",lensDrops:"Drops on the glass",lensDropsTitle:"0 to 1: how much of the outermost glass drops of water cover. Blank: from the rain or snow falling, unless the glass is sheltered",lensCondensation:"Condensation",lensCondensationTitle:"0 to 1: condensation on the glass, as on a lens taken from the warm into the cold. Blank: none",lensDirt:"Dirt",lensDirtTitle:"0 to 1: dirt, grease or fingerprints on the glass. Blank: none",lensSheltered:"Sheltered from the rain",lensShelteredTitle:"The outermost glass was out of the rain or snow: under a roof, or behind a windscreen whose wipers run",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities","ballester-guasp.pending":"to be assessed","poher.0":"0/5 · not strange, or not classifiable","poher.1":"1/5 · a point in a straight line","poher.2":"2/5 · an abnormal trajectory","poher.3":"3/5 · strange: erratic, landed or vanished","poher.4":"4/5 · landing with traces","poher.5":"5/5 · landing with occupants"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",rareIceCrystals:"Rare crystals",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorTrafficLight:"Traffic light",decorCrossing:"Pedestrian crossing",decorRoadSign:"Road sign",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Yl={...PN,accountBy:"Account by",unnamedObserver:"Observer {n}",about:"About",close:"Close",observation:"Observation",date:"Date",location:"Location",case:"Case",description:"Description",source:"Source",basis:{measured:"measured",stated:"stated",derived:"derived",assumed:"assumed"},credits:"Credits",editThisObservation:"Edit this observation",share:"Share",embedObservation:"Embed the observation",back:"Back",shareScope:"Share",shareScopeCase:"Whole case",shareOpensOn:"Opens on",shareStartAt:"Start at",shareOptionLabels:"Show summary chips",shareOptionMap:"Open map",shareOptionMilestones:"Show moments",shareOptionCompare:"Compare account",showLabels:"Show what it states",interpretation:"Interpretation",account:"Account",interpretationBy:"{title}, by {by}",confrontation:"Against the account",confrontationDirection:"{deg}° off",confrontationWidth:"width ×{ratio}",confrontationHeight:"height ×{ratio}",showComparison:"Compare with the account",hideComparison:"Stop comparing with the account",hideLabels:"Hide what it states",variant:"Variant: {name}",verdicts:{consolidated:"compatible with consolidated biases",contested:"only by invoking contested biases",incompatible:"incompatible even at the bounds"},variantFields:{time:"Time",heading:"Heading",elevation:"Elevation",size:"Size",duration:"Duration",sweep:"Sweep across the sky"},variantReadings:{grouped:"lights read as one body","still-seen-moving":"a still light seen moving","moving-seen-still":"a moving light seen hovering","brightening-as-approach":"growing brighter read as coming nearer"}},NN=Object.freeze(Object.defineProperty({__proto__:null,sightingMessages_en:Yl},Symbol.toStringTag,{value:"Module"}));class Wr{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,i){const n=new URL(`${t}.mjs`,e);return n.href.startsWith(`${Wr.CDN}/`)?`${i}/lib/${t}.mjs`:(n.pathname=n.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),n.href)}static VERSION_PARAMETER="v";static freezable(t){return t in Wr.DIRECTORIES}static frozenLink(t,e){const i=new URL(t);return i.searchParams.set(Wr.VERSION_PARAMETER,e),i.href}static frozen(t,e){return`${Wr.CDN}/${Wr.PACKAGE}@${e}/${Wr.DIRECTORIES[t]}/${t}.mjs`}}class ju{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:ju.PRODUCTION}catch{return ju.PRODUCTION}}}const w1={share:"Share",close:"Close",link:"Link",embed:"Embed",copy:"Copy",copied:"Copied",freeze:"Freeze version {version}",freezeHint:"The embed keeps the rendering of this version of UFO@home, loaded from jsDelivr, and gets none of the later fixes. Unticked, it follows each release.",unsaved:"The link opens the file at its address: your unsaved changes are not in it. Save the file there first.",unavailable:"Only a file loaded from an address can be shared: put it online, then open it from its address."},LN=Object.freeze(Object.defineProperty({__proto__:null,shareMessages_en:w1},Symbol.toStringTag,{value:"Module"})),kN=`
9226
9226
  <style>
9227
9227
  /* What the dialog is drawn with: light by default, and the dark set when the system asks for it, as the player and the editors
9228
9228
  are. The form controls follow through color-scheme. Defined here and not by the host, so that any element can hold this dialog;
@@ -9448,6 +9448,6 @@ ${fi.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery
9448
9448
  <button id="copy" class="share-copy" type="button">Copy</button>
9449
9449
  </div>
9450
9450
  </dialog>
9451
- `;class Wh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Wh.TAG)||customElements.define(Wh.TAG,Wh)}subject;messages=w1;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=kN;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.freeze=t("freeze"),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.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,i=t==="en"?w1:await KA(t);if(e===this.languageToken)return this.messages=i,this.applyMessages(),i}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(),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.freeze.checked;this.linkField.value=e?Wr.frozenLink(t.link(),"0.161.0"):t.link(),this.fitLink();const n=`<script type="module" src="${e?Wr.frozen(t.module,"0.161.0"):Wr.current(t.module,import.meta.url,ju.home())}"><\/script>
9452
- ${t.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const t=this.messages,e=(i,n)=>{this.shadow.getElementById(i).textContent=n};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("freeze-label",t.freeze.replace("{version}","0.161.0")),this.freeze.parentElement.title=t.freezeHint,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??=De(async()=>{const{ShareCodeEditor:t}=await import("./ShareCodeEditor-C53SBK2N.js");return{ShareCodeEditor:t}},[],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()}}}class On{static PLAIN=/^\d+(?:[.,]\d+)?$/;static COLONS=/^(?:(\d+):)?(\d{1,2}):(\d{1,2}(?:[.,]\d+)?)$/;static UNITS=/^(?:(\d+(?:[.,]\d+)?)h)?(?:(\d+(?:[.,]\d+)?)m)?(?:(\d+(?:[.,]\d+)?)s)?$/i;static CLOCK=/^(?:(\d{4})-(\d{2})-(\d{2})[T ])?T?(\d{1,2}):(\d{2})(?::(\d{2}(?:[.,]\d+)?))?$/;static num(t){return t===void 0?0:Number(t.replace(",","."))}static delta(t){const e=(t??"").trim();if(e==="")return;if(On.PLAIN.test(e))return On.num(e);const i=On.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||On.num(a)>=60?void 0:On.num(s)*3600+Number(r)*60+On.num(a)}const n=On.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?On.num(n[1])*3600+On.num(n[2])*60+On.num(n[3]):/^P/i.test(e)?Th.seconds(e.toUpperCase()):void 0}static isClock(t){return On.clock(t)!==void 0}static clock(t){const e=On.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,h={hour:Number(r),minute:Number(a),second:On.num(c)};if(!(h.hour>=24||h.minute>=60||h.second>=60)){if(i!==void 0){const l={year:Number(i),month:Number(n),day:Number(s)};if(l.month<1||l.month>12||l.day<1||l.day>31)return;h.date=l}return h}}static elapsedSince(t,e){if(!t||t.hour===void 0||t.minute===void 0)return;const i=t.hour*3600+t.minute*60+(t.second??0),n=e.hour*3600+e.minute*60+e.second;if(e.date){if(t.year===void 0||t.month===void 0||t.day===void 0)return;const r=Date.UTC(e.date.year,e.date.month-1,e.date.day)/1e3+n,a=Date.UTC(t.year,t.month-1,t.day)/1e3+i;return Math.max(0,r-a)}let s=n-i;return s<=-43200&&(s+=86400),Math.max(0,s)}}IS();Wh.register();const Lf=ju.home(),gf="compare-account",Bm="start-time",jw="start-clock",Hl="observer",vf="case",Mf="account",yf="variant-",Hm=`${Lf}/edit/`;class Xh extends HTMLElement{static get observedAttributes(){return["src","show-labels",Bm,jw,Hl,Jr,jr,gf]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;observerText;observerSelect;infoButton;infoPanel;infoAppLink;editLink;infoObservationHeading;infoObservationList;infoCreditsToggle;infoCreditsList;infoCloseButton;shareButton;shareDialog;shareStartOn;shareStart;shareScopeRow;shareScopeLabel;shareScope;shareOpensRow;shareOpensLabel;shareOpens;shareStartLabel;shareOptions;labelsToggle;paramSummary;summaryBuilder=new ao(Yl,new x0,new Es(["en"]),new bf({}),{messages:Yl,locale:"en"});summarySignature="";assessmentEntries=[];assessmentToken=0;supportsPopover=typeof HTMLElement.prototype.showPopover=="function";entries=[];caseSource;interpretationChoice;interpretationLabel;interpretationSelect;confrontationElement;confrontationHeading;confrontationList;compareButton;variantChips;variantMoved;interpretationLoaders=new Map;interpretationToken=0;offeredFor;currentSrc;infoOpen=!1;creditsOpen=!1;labelsShown=!1;language="en";messages=Yl;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${eA}</style>${tA}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(E0),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.accountElement=this.shadow.getElementById("account"),this.accountPrefix=this.shadow.getElementById("account-prefix"),this.observerText=this.shadow.getElementById("observer-text"),this.observerSelect=this.shadow.getElementById("observer"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.editLink=this.shadow.getElementById("edit-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.labelsToggle=this.shadow.getElementById("info-labels-toggle"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=Jt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=i=>({input:this.shadow.getElementById(`share-opt-${i}`),label:this.shadow.getElementById(`share-opt-${i}-label`)});this.shareOptions={labels:e("labels"),map:e("map"),milestones:e("milestones"),compare:e("compare")},this.interpretationChoice=this.shadow.getElementById("interpretation-choice"),this.interpretationLabel=this.shadow.getElementById("interpretation-label"),this.interpretationSelect=this.shadow.getElementById("interpretation"),this.confrontationElement=this.shadow.getElementById("confrontation"),this.confrontationHeading=this.shadow.getElementById("confrontation-heading"),this.confrontationList=this.shadow.getElementById("confrontation-list"),this.compareButton=this.shadow.getElementById("compare-account"),this.variantChips=this.shadow.getElementById("variant-chips"),this.variantMoved=this.shadow.getElementById("variant-moved"),this.compareButton.addEventListener("click",()=>this.setComparing(!this.sceneElement.compareAccount)),this.observerSelect.addEventListener("change",()=>this.selectObserver(this.observerSelect.value)),this.interpretationSelect.addEventListener("change",()=>void this.chooseInterpretation(this.interpretationSelect.value)),this.sceneElement.addEventListener(RS,i=>this.showConfrontation(i.detail)),this.sceneElement.ufoElement.addEventListener("timeupdate",()=>this.refreshParamSummary()),this.supportsPopover?(this.infoPanel.setAttribute("popover","auto"),this.infoPanel.removeAttribute("hidden"),this.infoButton.setAttribute("popovertarget","info-panel"),this.infoPanel.addEventListener("beforetoggle",i=>{i.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",i=>this.syncInfoOpen(i.newState==="open"))):this.infoButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCloseButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCreditsToggle.addEventListener("click",()=>this.toggleCredits()),this.shareButton.addEventListener("click",()=>this.openShare());for(const i of[this.shareStartOn,this.shareStart,...Object.values(this.shareOptions).map(n=>n.input)])i.addEventListener("input",()=>this.refreshShareLinks());for(const i of[this.shareScope,this.shareOpens])i.addEventListener("change",()=>this.refreshShareLinks());this.isConnected&&this.loadLocaleMessages()}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=Ao.preferencesFor(this);this.preferences=e;const i=C1(e,P1),[n,s,r]=i==="en"?[Yl,{},void 0]:await Promise.all([$A(i),qA(i),bb(i)]);if(t!==this.localeToken)return;const a=i!==this.language;this.language=i,this.messages=n,this.tags=new bf(s),this.said=new Es(e),this.summaryBuilder=new ao(this.messages,new x0(r),this.said,this.tags,{messages:this.messages,locale:i}),this.accountPrefix.textContent=this.messages.accountBy,this.interpretationLabel.textContent=this.messages.interpretation,this.confrontationHeading.textContent=this.messages.confrontation;const c=this.entries.find(h=>h.src===this.currentSrc);c&&this.offerInterpretations(c),this.updateCompareButton(),this.infoButton.title=this.messages.about,this.infoButton.setAttribute("aria-label",this.messages.about),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation),this.infoCloseButton.setAttribute("aria-label",this.messages.close),this.infoObservationHeading.textContent=this.messages.observation,this.infoCreditsToggle.textContent=this.messages.credits,this.syncLabelsToggle(),this.refreshParamSummary(),a&&this.currentSrc&&this.runAssessments(),this.shareButton.title=this.messages.share,this.shareButton.setAttribute("aria-label",this.messages.share),this.shareStartLabel.textContent=this.messages.shareStartAt,this.shareScopeLabel.textContent=this.messages.shareScope,this.shareOpensLabel.textContent=this.messages.shareOpensOn,this.shareOptions.labels.label.textContent=this.messages.shareOptionLabels,this.shareOptions.map.label.textContent=this.messages.shareOptionMap,this.shareOptions.milestones.label.textContent=this.messages.shareOptionMilestones,this.shareOptions.compare.label.textContent=this.messages.shareOptionCompare,this.shareStart.setAttribute("aria-label",this.messages.shareStartAt),this.shareDialog.useLanguage(i),this.infoOpen&&this.populateInfoPanel(),this.updateAccountLine()}preferences=[];localeToken=0;said=new Es(["en"]);tags=new bf({});connectedCallback(){Ao.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(t===Jr||t===jr)&&this.forwardPlayerAttributes(),t===Hl&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===gf&&this.setComparing(this.hasAttribute(gf))}forwardPlayerAttributes(){for(const t of[Jr,jr]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=Eo.recording(t);this.sceneElement.holdForNewScene(e);const i=await e;if(Array.isArray(i))throw new Error(`${t} is a bare list of recordings, which is no longer read: list them as the sighting events of a case.json`);if(mn.isCase(i)){mn.check(i);const n=mn.sightingUrls(i,new URL(t,location.href).href);if(n.length===0)throw new Error(`${t} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(n,{json:i,url:new URL(t,location.href).href})}else this.setEntries([{src:t,sighting:i}],void 0)}get sightingData(){return this.entries.find(t=>t.src===this.currentSrc)?.sighting}set sightingData(t){const e=Wi.toCurrent(t);this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:e}],void 0)}seekTo(t,e){const i=this.caseSource,n=e===void 0?void 0:this.entries.find(s=>{const r=this.plain(s).id;return(i?mn.accountIds(i.json,i.url,s.src,r):[r]).includes(e)});n&&n.src!==this.currentSrc&&this.selectObserver(n.src),this.sceneElement.ufoElement.currentTime=Math.max(0,t)*1e3}get observerUrls(){return this.entries.map(t=>t.src)}set observerUrls(t){this.loadObserverUrls(t)}async loadObserverUrls(t,e){const i=await Promise.all(t.map(async n=>({src:n,sighting:await Eo.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=mn.problems(t,e.map(s=>this.plain(s).id).filter(s=>s!==void 0));for(const s of i)console.warn(`The case ${t.id??""} gives the id "${s}" to more than one event: a reference to it is ambiguous.`);for(const{reading:s,reference:r}of n)console.warn(`The reading ${s} of the case ${t.id??""} is "interpretationOf" "${r}", which no event of the case has as its id, nor any recording it lists.`)}setEntries(t,e){this.entries=t.map(r=>({...r,sighting:Wi.toCurrent(r.sighting)})),this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";const n=t.map((r,a)=>this.observerDisplayName(this.plain(r).observer)??this.caseTitleOf(r)??this.messages.unnamedObserver.replace("{n}",String(a+1)));for(const[r,a]of t.entries()){const c=document.createElement("option");c.value=a.src;const h=n.filter(l=>l===n[r]).length>1;c.textContent=(h?this.caseTitleOf(a):void 0)??n[r],this.observerSelect.appendChild(c)}const s=t.find(r=>r.src===this.currentSrc)??this.entryAsked(t)??t[0];s?this.selectObserver(s.src):this.updateAccountLine()}entryAsked(t){const e=this.getAttribute(Hl)?.trim();if(!e)return;const i=t.find(s=>this.plain(s).observer?.id===e);if(i)return i;const n=t.find(s=>s.src.split("/").pop()===e.split("/").pop());return n||(/^\d+$/.test(e)?t[Number(e)-1]:void 0)}observerKeyOf(t){return this.plain(t).observer?.id??String(this.entries.indexOf(t)+1)}sharedEntry(){const t=this.shareScope.value;if(!(!this.caseSource||t===vf))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===vf}editorUrl(){if(!this.currentSrc)return Hm;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${Hm}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${Hm}?file=${encodeURIComponent(t.href)}`}get editorHref(){return this.editorUrl()}shownTrackUrl(){const t=this.caseSource,e=this.entries.find(s=>s.src===this.currentSrc),i=/^case-(\d+)$/.exec(this.interpretationSelect.value);if(!t||!e||!i)return;const n=mn.interpretationEvents(t.json,mn.accountIds(t.json,t.url,e.src,this.plain(e).id))[Number(i[1])];return n?.url?new URL(n.url,t.url).href:void 0}shareSubject={module:"rr0-sighting",link:()=>this.playUrl(),element:()=>this.replayElement()};replayElement(){const t=this.sharedAddress(),i=[...t.observer?[[Hl,t.observer]]:[],...this.replayAttributes()].map(([n,s])=>s===""?` ${n}`:` ${n}="${s}"`).join("");return`<rr0-sighting src="${t.src}"${i}></rr0-sighting>`}playUrl(){const t=this.sharedAddress(),e=[...t.observer?[`${Hl}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${Lf}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${Lf}/play/${e&&"?"+e}`}sharedAddress(){const t=e=>e?new URL(e,location.href).href:"";if(this.sharesCase){const e=this.entries.find(i=>i.src===this.shareOpens.value)??this.entries.find(i=>i.src===this.currentSrc);return{src:this.caseSource.url,observer:e?this.observerKeyOf(e):void 0}}return{src:t(this.sharedEntry()?.src??this.currentSrc??"")}}replayAttributes(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push([Bm,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Jr,""]),t.milestones.input.checked||e.push([jr,""]),t.compare.input.checked&&e.push([gf,""]),e}replayQuery(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push(`d=${this.shareStartSeconds}`),t.labels.input.checked||e.push("labels=0"),t.map.input.checked&&e.push("map=1"),t.milestones.input.checked||e.push("moments=0"),t.compare.input.checked&&e.push("compare=1"),e}get shareStartSeconds(){const t=Math.floor(Number(this.shareStart.value));return this.shareStartOn.checked&&Number.isFinite(t)&&t>=0?t:void 0}refreshShareLinks(){this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.refresh()}openShare(){const t=this.sceneElement.ufoElement;this.shareStart.max=String(Math.floor(t.seekableDuration/1e3)),this.shareStart.value=String(Math.floor(t.currentTime/1e3)),this.shareStartOn.checked=!1,this.shareOptions.labels.input.checked=this.labelsShown,this.shareOptions.map.input.checked=t.observerMapOpen,this.shareOptions.milestones.input.checked=t.milestonesVisible,this.shareOptions.compare.input.checked=this.sceneElement.compareAccount,this.offerShareScope(),this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.open()}offerShareScope(){const t=this.caseSource!==void 0&&this.entries.length>1;if(this.shareScopeRow.hidden=!t,this.shareScope.innerHTML="",this.shareOpens.innerHTML="",!t)return;const e=(i,n,s)=>{const r=document.createElement("option");r.value=n,r.textContent=s,i.appendChild(r)};e(this.shareScope,vf,this.messages.shareScopeCase);for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??this.caseTitleOf(i)??this.messages.unnamedObserver.replace("{n}",String(this.entries.indexOf(i)+1));e(this.shareScope,i.src,n),e(this.shareOpens,i.src,n)}this.shareScope.value=vf,this.shareOpens.value=this.currentSrc??this.entries[0].src}offerInterpretations(t){const e=this.offeredFor===t.sighting,i=this.interpretationSelect.value;this.offeredFor=t.sighting,this.interpretationToken++,this.interpretationLoaders=new Map,this.interpretationSelect.innerHTML="";const n=(u,d,f)=>{const p=document.createElement("option");p.value=u,p.textContent=d,this.interpretationSelect.appendChild(p),this.interpretationLoaders.set(u,f)},s=t===this.entries.find(u=>u.src===this.currentSrc),r=s?this.sceneElement.ufoElement.sighting.interpretation:void 0;n(Mf,this.messages.account,()=>Promise.resolve(r));const a=this.caseSource;a&&mn.interpretationEvents(a.json,mn.accountIds(a.json,a.url,t.src,this.plain(t).id)).forEach((u,d)=>{const f=this.said.read(u.title)??`#${d+1}`,p=(u.by??[]).map(m=>this.agentName(m)).filter(Boolean).join(", ");n(`case-${d}`,p?this.messages.interpretationBy.replace("{title}",f).replace("{by}",p):f,()=>mn.interpretationOf(u,a.url,m=>Eo.recording(m)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${yf}${u}`,`${this.variantLabel(d)} (${this.messages.verdicts[d.variant.verdict]})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const l=e&&[...this.interpretationSelect.options].some(u=>u.value===i)?i:Mf;this.interpretationSelect.value=l,l===Mf?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(l),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2,this.showConfrontation(this.sceneElement.confrontation),this.updateCompareButton(),this.showVariants(c)}keptVariants(t){const e={consolidated:0,contested:1,incompatible:2};return(t.sighting.variants??[]).map((i,n)=>({index:n,kept:i})).filter(({kept:i})=>i.variant).sort((i,n)=>e[i.kept.variant.verdict]-e[n.kept.variant.verdict]||i.kept.variant.cost-n.kept.variant.cost)}variantLabel(t){return this.messages.variant.replace("{name}",t.variant.label??t.variant.candidate)}showVariants(t){if(this.variantChips.innerHTML="",this.variantChips.hidden=t.length===0,t.length===0){this.showVariantMoved();return}const e=(i,n,s)=>{const r=document.createElement("button");r.type="button",r.dataset.value=i,s&&(r.dataset.verdict=s,r.title=this.messages.verdicts[s],r.append(Object.assign(document.createElement("span"),{className:"dot"}))),r.append(n),r.addEventListener("click",()=>{this.interpretationSelect.value!==i&&(this.interpretationSelect.value=i,this.chooseInterpretation(i))}),this.variantChips.append(r)};e(Mf,this.messages.account);for(const{index:i,kept:n}of t)e(`${yf}${i}`,n.variant.label??n.variant.candidate,n.variant.verdict);this.showVariantMoved()}showVariantMoved(){const t=this.interpretationSelect.value;for(const s of this.variantChips.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.value===t));this.variantMoved.innerHTML="";const e=t.startsWith(yf)?Number(t.slice(yf.length)):-1,i=this.sceneElement.ufoElement.sighting.variants?.[e]?.variant;if(this.variantMoved.hidden=!i||i.moved.length+(i.readings?.length??0)===0,!i)return;const n=new Intl.NumberFormat(this.language,{maximumFractionDigits:1});for(const s of i.moved){const[r,a]=s.field==="time"?["0 min",`${s.variant>0?"+":""}${n.format(s.variant)} min`]:s.field==="duration"?[`${n.format(s.stated)} s`,`${n.format(s.variant)} s`]:[`${n.format(s.stated)}°`,`${n.format(s.variant)}°`],c=document.createElement("span");c.append(`${this.messages.variantFields[s.field]}${this.colon}`,Object.assign(document.createElement("s"),{textContent:r})," → ",Object.assign(document.createElement("b"),{textContent:a})),this.variantMoved.append(c)}for(const s of i.readings??[]){const r=this.messages.variantReadings[s.reading];r&&this.variantMoved.append(Object.assign(document.createElement("span"),{className:"reading",textContent:r}))}}setComparing(t){this.sceneElement.compareAccount=t,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation)}updateCompareButton(){const t=this.sceneElement.compareAccount;this.compareButton.hidden=!this.sceneElement.interpretation,this.compareButton.setAttribute("aria-pressed",String(t));const e=t?this.messages.hideComparison:this.messages.showComparison;this.compareButton.title=e,this.compareButton.setAttribute("aria-label",e)}static DATE_LOCALES={en:"en-US",fr:"fr-FR",es:"es-ES",it:"it-IT"};get colon(){return this.language==="fr"?" : ":": "}async chooseInterpretation(t){const e=++this.interpretationToken,i=this.interpretationLoaders.get(t),n=i?await i().catch(s=>{console.warn(`<rr0-sighting>: could not read interpretation "${t}":`,s)}):void 0;e===this.interpretationToken&&(this.sceneElement.interpretation=n,this.editLink.href=this.editorUrl(),this.dispatchEvent(new CustomEvent("interpretationchange",{detail:{track:this.shownTrackUrl()}})),this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation),this.showVariantMoved())}agentName(t){if("people"in t){const[e,...i]=t.people.replace(/([a-z])([A-Z])/g,"$1 $2").split(" ");return[...i,e].join(" ")}return"org"in t?t.org.replace(/([a-z])([A-Z])/g,"$1 $2"):this.observerDisplayName(t)??""}showConfrontation(t){this.confrontationList.innerHTML="",this.confrontationElement.hidden=!this.sceneElement.interpretation||!this.sceneElement.compareAccount;const e=new Intl.NumberFormat(this.language,{maximumFractionDigits:1,minimumFractionDigits:1}),i=new Intl.NumberFormat(this.language,{maximumFractionDigits:2,minimumFractionDigits:2});for(const n of t){const s=document.createElement("li");s.append(`${this.said.read(n.title)??n.sourceId}${this.colon}`);const r=[];n.separationDeg!==void 0&&r.push([this.messages.confrontationDirection.replace("{deg}",e.format(n.separationDeg)),n.disagreements.includes("direction")]),n.widthRatio!==void 0&&r.push([this.messages.confrontationWidth.replace("{ratio}",i.format(n.widthRatio)),n.disagreements.includes("width")]),n.heightRatio!==void 0&&r.push([this.messages.confrontationHeight.replace("{ratio}",i.format(n.heightRatio)),n.disagreements.includes("height")]),r.forEach(([a,c],h)=>{h>0&&s.append(" · ");const l=document.createElement("span");l.textContent=a,c&&(l.className="disagrees"),s.append(l)}),this.confrontationList.appendChild(s)}}startPending=!1;startSeconds(t){const e=On.clock(this.getAttribute(jw)),i=this.plain(t).time;return(e?On.elapsedSince(i===void 0?void 0:Dh(i),e):void 0)??On.delta(this.getAttribute(Bm))}selectObserver(t){const e=this.entries.find(n=>n.src===t);if(!e)return;this.currentSrc=t,this.observerSelect.value=t,this.sceneElement.documentUrl=e.src?new URL(e.src,location.href).href:void 0;const i=!this.sceneElement.ufoElement.playRequested;if(e.sighting.image?this.sceneElement.showPoster(e.sighting.image,e.src?new URL(e.src,location.href).href:void 0,i):this.sceneElement.showPoster(this.caseSource?.json.image,this.caseSource?.url,i),this.sceneElement.holdForNewScene(),this.sceneElement.sightingData=e.sighting,this.startPending){this.startPending=!1;const n=this.startSeconds(e);n!==void 0&&(this.sceneElement.ufoElement.currentTime=Math.max(0,n)*1e3)}this.offerInterpretations(e),this.updateAccountLine(),this.refreshParamSummary(),this.runAssessments(),this.infoOpen&&this.populateInfoPanel(),this.dispatchEvent(new CustomEvent(UN,{detail:{src:t}}))}async runAssessments(){const t=++this.assessmentToken,e=await new O1(this.messages).read(this.sceneElement.ufoElement.sighting);t===this.assessmentToken&&(this.assessmentEntries=e.entries,this.refreshParamSummary())}updateAccountLine(){const t=this.entries.find(n=>n.src===this.currentSrc),e=t?this.observerDisplayName(this.plain(t).observer):void 0,i=e!==void 0||this.entries.length>1;this.accountElement.hidden=!i,this.observerText.textContent=e??"",this.editLink.hidden=!this.currentSrc,this.editLink.href=this.editorUrl(),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation)}caseTitleOf(t){const e=this.caseSource;if(!e)return;const i=e.json.events?.find(n=>n.url!==void 0&&!n.interpretationOf&&new URL(n.url,e.url).href===new URL(t.src,location.href).href);return i?this.said.read(i.title):void 0}observerDisplayName(t){if(!t)return;const e=[...t.firstNames??[],t.lastName].filter(Boolean).join(" ");return this.said.read(t.title)||e||t.id}plainRecordings=new WeakMap;plain(t){return this.stripped(t).recording}stripped(t){let e=this.plainRecordings.get(t.sighting);return e||(e=os.strip(t.sighting),this.plainRecordings.set(t.sighting,e)),e}basisOf(t,e){const i=this.stripped(t).provenance,n={measured:-1,stated:0,derived:1,assumed:2},s=i.paths().filter(c=>e.some(h=>c===h||c.startsWith(`${h}.`))).map(c=>i.at(c)),r=s.reduce((c,h)=>n[h.basis]>n[c]?h.basis:c,"stated"),a=s.filter(c=>c.basis===r&&c.rationale).map(c=>c.rationale);return{basis:r,rationales:a}}formatDate(t){const e=t.place?.locations?.[0],i=Xo((t.time?Dh(t.time):void 0)??{},e?.lng??0,t.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(t,e?.lng??0)*36e5;if(Number.isFinite(n))return new Intl.DateTimeFormat(Xh.DATE_LOCALES[this.language],{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(t,e){return t.utcOffsetHours??Math.round(e/15)}formatLocation(t){const e=t.place?.locations?.[0];if(e)return`${e.lat.toFixed(4)}, ${e.lng.toFixed(4)}`}toggleInfoPanel(){const t=!this.infoOpen;if(this.supportsPopover){const e=this.infoPanel.matches(":popover-open");t&&!e?this.infoPanel.showPopover():!t&&e&&this.infoPanel.hidePopover();return}t&&this.bringInfoButtonIntoView(),this.syncInfoOpen(t),this.infoPanel.hidden=!t,t?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const t=this.infoButton.getBoundingClientRect(),e=window.innerHeight||document.documentElement.clientHeight;t.top>=0&&t.bottom<=e||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(t){t!==this.infoOpen&&(this.infoOpen=t,this.infoButton.setAttribute("aria-expanded",String(t)),t?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=t=>{const e=t.composedPath();!e.includes(this.infoPanel)&&!e.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}revealInPanel(t){t.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(t){this.toggleAttribute("show-labels",t)}applyLabels(t){this.labelsShown=t,this.syncLabelsToggle(),this.refreshParamSummary(),this.populateInfoPanel()}syncLabelsToggle(){this.labelsToggle.textContent=this.labelsShown?this.messages.hideLabels:this.messages.showLabels,this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,!this.labelsShown){this.paramSummary.replaceChildren(),this.summarySignature="";return}const t=this.sceneElement.ufoElement.sighting,e=[...this.summaryBuilder.entriesFor(t,this.sceneElement.ufoElement.currentTime,{roadGradeDeg:this.sceneElement.roadGradeDeg}),...this.assessmentEntries],i=e.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.full??""}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of e){s&&s.group!==r.group&&(s=void 0);const a=r.group==="summary"?this.messages.summaryGroup:r.group==="observer"?this.messages.observerGroup:r.group in this.messages.summaryGroups?this.messages.summaryGroups[r.group]:r.group==="assessment"?this.messages.assessmentGroup:void 0;if(a!==void 0&&!s){const h=document.createElement("span");h.className="param-nest";const l=document.createElement("span");l.className="param-nest-label",l.textContent=a,h.append(l),s={group:r.group,element:h},n.push(h)}const c=this.paramItem(r);s?s.element.append(c):n.push(c)}this.paramSummary.replaceChildren(...n),this.syncDescription(e)}openDescription;syncDescription(t){this.openDescription!==void 0&&!t.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),fb.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription(t)})}paramItem(t){const e=document.createElement("span");if(e.className=t.fromSource?"param-label from-source":"param-label",t.detail&&(e.title=t.detail),t.full!==void 0){e.classList.add("describable"),e.tabIndex=0,e.setAttribute("role","button");const s=()=>{this.openDescription=t.full,this.syncDescription([t])};e.addEventListener("click",s),e.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),s())})}const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${t.label} `,e.append(i),t.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=t.color,e.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=t.unit===""?t.value:`${t.value} ${t.unit}`,e.append(n),e}populateInfoPanel(){const t=this.entries.find(e=>e.src===this.currentSrc);if(this.infoObservationList.innerHTML="",t){const e=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(e&&this.appendInfoRow(this.infoObservationList,this.messages.case,e),!this.labelsShown){const s=this.formatDate(this.plain(t));s&&this.appendInfoRow(this.infoObservationList,this.messages.date,s,this.basisOf(t,Xh.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages.location,r,this.basisOf(t,Xh.PLACE_PATHS))}const i=this.said.read(this.plain(t).description);i&&!this.labelsShown&&this.appendInfoRow(this.infoObservationList,this.messages.description,i);for(const s of this.plain(t).sources??[])this.appendInfoSource(this.infoObservationList,this.messages.source,s);const n=this.plain(t).tags;!this.labelsShown&&n&&n.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,n.map(s=>this.tags.name(s)).join(", "))}this.infoAppLink.href=Lf,this.infoAppLink.textContent="UFO@home v0.161.0",In.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=this.said.read(i.title)??i.url??"";if(i.url&&/^https?:\/\//i.test(i.url)){const c=document.createElement("a");c.href=i.url,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,s.appendChild(c)}else s.append(r);const a=[i.authors?.join(", "),i.publication?.publisher,i.publication?.time,i.index].filter(Boolean);a.length>0&&s.append(`, ${a.join(", ")}`),t.append(n,s)}static DATE_PATHS=["time","utcOffsetHours","timeZone"];static PLACE_PATHS=["place"];appendInfoRow(t,e,i,n){const s=document.createElement("dt");s.textContent=e;const r=document.createElement("dd");if(r.textContent=i,n){const a=document.createElement("span");a.className=`basis basis-${n.basis}`,a.textContent=this.messages.basis[n.basis],n.rationales.length>0&&(a.title=n.rationales.join(`
9453
- `)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const Qw="rr0-sighting",UN="observerchange",tb="rr0-eyeobserver";class FN extends Xh{}function zN(){IS(),Wh.register(),customElements.get(Qw)||customElements.define(Qw,Xh),customElements.get(tb)||customElements.define(tb,FN)}zN();export{vc as $,hc as A,me as B,rt as C,ch as D,s3 as E,pe as F,Be as G,bs as H,QN as I,Rf as J,No as K,$m as L,CT as M,Al as N,ls as O,Lg as P,_n as Q,_t as R,pu as S,Pn as T,RT as U,rr as V,KN as W,$t as X,vn as Y,Mn as Z,JN as _,rs as a,kn as a0,An as a1,ye as a2,Pi as a3,nn as a4,Jn as a5,Di as a6,pN as a7,Sv as a8,BN as a9,$N as aA,ax as aB,YN as aC,Nn as aD,Gs as aE,rx as aF,jy as aG,H_ as aH,xS as aI,Kf as aJ,Pg as aK,bx as aL,ev as aM,iv as aN,Fe as aO,Io as aP,id as aQ,GN as aa,HN as ab,nd as ac,jN as ad,qN as ae,Jf as af,Sx as ag,s0 as ah,XN as ai,qn as aj,Oy as ak,ZN as al,t8 as am,nx as an,Bs as ao,pd as ap,Mp as aq,H3 as ar,je as as,Do as at,ig as au,Xi as av,oa as aw,Y_ as ax,oi as ay,WN as az,Es as b,tf as c,Mt as d,it as e,eu as f,de as g,lo as h,fe as i,er as j,e8 as k,As as l,e0 as m,tn as n,yr as o,BA as p,T as q,vr as r,Xo as s,Te as t,Lr as u,bt as v,_e as w,i8 as x,oe as y,VN as z};
9451
+ `;class Wh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Wh.TAG)||customElements.define(Wh.TAG,Wh)}subject;messages=w1;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=kN;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.freeze=t("freeze"),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.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,i=t==="en"?w1:await KA(t);if(e===this.languageToken)return this.messages=i,this.applyMessages(),i}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(),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.freeze.checked;this.linkField.value=e?Wr.frozenLink(t.link(),"0.162.0"):t.link(),this.fitLink();const n=`<script type="module" src="${e?Wr.frozen(t.module,"0.162.0"):Wr.current(t.module,import.meta.url,ju.home())}"><\/script>
9452
+ ${t.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const t=this.messages,e=(i,n)=>{this.shadow.getElementById(i).textContent=n};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("freeze-label",t.freeze.replace("{version}","0.162.0")),this.freeze.parentElement.title=t.freezeHint,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??=Ie(async()=>{const{ShareCodeEditor:t}=await import("./ShareCodeEditor-C53SBK2N.js");return{ShareCodeEditor:t}},[],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()}}}class On{static PLAIN=/^\d+(?:[.,]\d+)?$/;static COLONS=/^(?:(\d+):)?(\d{1,2}):(\d{1,2}(?:[.,]\d+)?)$/;static UNITS=/^(?:(\d+(?:[.,]\d+)?)h)?(?:(\d+(?:[.,]\d+)?)m)?(?:(\d+(?:[.,]\d+)?)s)?$/i;static CLOCK=/^(?:(\d{4})-(\d{2})-(\d{2})[T ])?T?(\d{1,2}):(\d{2})(?::(\d{2}(?:[.,]\d+)?))?$/;static num(t){return t===void 0?0:Number(t.replace(",","."))}static delta(t){const e=(t??"").trim();if(e==="")return;if(On.PLAIN.test(e))return On.num(e);const i=On.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||On.num(a)>=60?void 0:On.num(s)*3600+Number(r)*60+On.num(a)}const n=On.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?On.num(n[1])*3600+On.num(n[2])*60+On.num(n[3]):/^P/i.test(e)?Th.seconds(e.toUpperCase()):void 0}static isClock(t){return On.clock(t)!==void 0}static clock(t){const e=On.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,h={hour:Number(r),minute:Number(a),second:On.num(c)};if(!(h.hour>=24||h.minute>=60||h.second>=60)){if(i!==void 0){const l={year:Number(i),month:Number(n),day:Number(s)};if(l.month<1||l.month>12||l.day<1||l.day>31)return;h.date=l}return h}}static elapsedSince(t,e){if(!t||t.hour===void 0||t.minute===void 0)return;const i=t.hour*3600+t.minute*60+(t.second??0),n=e.hour*3600+e.minute*60+e.second;if(e.date){if(t.year===void 0||t.month===void 0||t.day===void 0)return;const r=Date.UTC(e.date.year,e.date.month-1,e.date.day)/1e3+n,a=Date.UTC(t.year,t.month-1,t.day)/1e3+i;return Math.max(0,r-a)}let s=n-i;return s<=-43200&&(s+=86400),Math.max(0,s)}}IS();Wh.register();const Lf=ju.home(),gf="compare-account",Bm="start-time",jw="start-clock",Hl="observer",vf="case",Mf="account",yf="variant-",Hm=`${Lf}/edit/`;class Xh extends HTMLElement{static get observedAttributes(){return["src","show-labels",Bm,jw,Hl,Jr,jr,gf]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;observerText;observerSelect;infoButton;infoPanel;infoAppLink;editLink;infoObservationHeading;infoObservationList;infoCreditsToggle;infoCreditsList;infoCloseButton;shareButton;shareDialog;shareStartOn;shareStart;shareScopeRow;shareScopeLabel;shareScope;shareOpensRow;shareOpensLabel;shareOpens;shareStartLabel;shareOptions;labelsToggle;paramSummary;summaryBuilder=new ao(Yl,new x0,new Es(["en"]),new bf({}),{messages:Yl,locale:"en"});summarySignature="";assessmentEntries=[];assessmentToken=0;supportsPopover=typeof HTMLElement.prototype.showPopover=="function";entries=[];caseSource;interpretationChoice;interpretationLabel;interpretationSelect;confrontationElement;confrontationHeading;confrontationList;compareButton;variantChips;variantMoved;interpretationLoaders=new Map;interpretationToken=0;offeredFor;currentSrc;infoOpen=!1;creditsOpen=!1;labelsShown=!1;language="en";messages=Yl;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${eA}</style>${tA}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(E0),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.accountElement=this.shadow.getElementById("account"),this.accountPrefix=this.shadow.getElementById("account-prefix"),this.observerText=this.shadow.getElementById("observer-text"),this.observerSelect=this.shadow.getElementById("observer"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.editLink=this.shadow.getElementById("edit-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.labelsToggle=this.shadow.getElementById("info-labels-toggle"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=Jt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=i=>({input:this.shadow.getElementById(`share-opt-${i}`),label:this.shadow.getElementById(`share-opt-${i}-label`)});this.shareOptions={labels:e("labels"),map:e("map"),milestones:e("milestones"),compare:e("compare")},this.interpretationChoice=this.shadow.getElementById("interpretation-choice"),this.interpretationLabel=this.shadow.getElementById("interpretation-label"),this.interpretationSelect=this.shadow.getElementById("interpretation"),this.confrontationElement=this.shadow.getElementById("confrontation"),this.confrontationHeading=this.shadow.getElementById("confrontation-heading"),this.confrontationList=this.shadow.getElementById("confrontation-list"),this.compareButton=this.shadow.getElementById("compare-account"),this.variantChips=this.shadow.getElementById("variant-chips"),this.variantMoved=this.shadow.getElementById("variant-moved"),this.compareButton.addEventListener("click",()=>this.setComparing(!this.sceneElement.compareAccount)),this.observerSelect.addEventListener("change",()=>this.selectObserver(this.observerSelect.value)),this.interpretationSelect.addEventListener("change",()=>void this.chooseInterpretation(this.interpretationSelect.value)),this.sceneElement.addEventListener(RS,i=>this.showConfrontation(i.detail)),this.sceneElement.ufoElement.addEventListener("timeupdate",()=>this.refreshParamSummary()),this.supportsPopover?(this.infoPanel.setAttribute("popover","auto"),this.infoPanel.removeAttribute("hidden"),this.infoButton.setAttribute("popovertarget","info-panel"),this.infoPanel.addEventListener("beforetoggle",i=>{i.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",i=>this.syncInfoOpen(i.newState==="open"))):this.infoButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCloseButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCreditsToggle.addEventListener("click",()=>this.toggleCredits()),this.shareButton.addEventListener("click",()=>this.openShare());for(const i of[this.shareStartOn,this.shareStart,...Object.values(this.shareOptions).map(n=>n.input)])i.addEventListener("input",()=>this.refreshShareLinks());for(const i of[this.shareScope,this.shareOpens])i.addEventListener("change",()=>this.refreshShareLinks());this.isConnected&&this.loadLocaleMessages()}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=Ao.preferencesFor(this);this.preferences=e;const i=C1(e,P1),[n,s,r]=i==="en"?[Yl,{},void 0]:await Promise.all([$A(i),qA(i),bb(i)]);if(t!==this.localeToken)return;const a=i!==this.language;this.language=i,this.messages=n,this.tags=new bf(s),this.said=new Es(e),this.summaryBuilder=new ao(this.messages,new x0(r),this.said,this.tags,{messages:this.messages,locale:i}),this.accountPrefix.textContent=this.messages.accountBy,this.interpretationLabel.textContent=this.messages.interpretation,this.confrontationHeading.textContent=this.messages.confrontation;const c=this.entries.find(h=>h.src===this.currentSrc);c&&this.offerInterpretations(c),this.updateCompareButton(),this.infoButton.title=this.messages.about,this.infoButton.setAttribute("aria-label",this.messages.about),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation),this.infoCloseButton.setAttribute("aria-label",this.messages.close),this.infoObservationHeading.textContent=this.messages.observation,this.infoCreditsToggle.textContent=this.messages.credits,this.syncLabelsToggle(),this.refreshParamSummary(),a&&this.currentSrc&&this.runAssessments(),this.shareButton.title=this.messages.share,this.shareButton.setAttribute("aria-label",this.messages.share),this.shareStartLabel.textContent=this.messages.shareStartAt,this.shareScopeLabel.textContent=this.messages.shareScope,this.shareOpensLabel.textContent=this.messages.shareOpensOn,this.shareOptions.labels.label.textContent=this.messages.shareOptionLabels,this.shareOptions.map.label.textContent=this.messages.shareOptionMap,this.shareOptions.milestones.label.textContent=this.messages.shareOptionMilestones,this.shareOptions.compare.label.textContent=this.messages.shareOptionCompare,this.shareStart.setAttribute("aria-label",this.messages.shareStartAt),this.shareDialog.useLanguage(i),this.infoOpen&&this.populateInfoPanel(),this.updateAccountLine()}preferences=[];localeToken=0;said=new Es(["en"]);tags=new bf({});connectedCallback(){Ao.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(t===Jr||t===jr)&&this.forwardPlayerAttributes(),t===Hl&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===gf&&this.setComparing(this.hasAttribute(gf))}forwardPlayerAttributes(){for(const t of[Jr,jr]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=Eo.recording(t);this.sceneElement.holdForNewScene(e);const i=await e;if(Array.isArray(i))throw new Error(`${t} is a bare list of recordings, which is no longer read: list them as the sighting events of a case.json`);if(mn.isCase(i)){mn.check(i);const n=mn.sightingUrls(i,new URL(t,location.href).href);if(n.length===0)throw new Error(`${t} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(n,{json:i,url:new URL(t,location.href).href})}else this.setEntries([{src:t,sighting:i}],void 0)}get sightingData(){return this.entries.find(t=>t.src===this.currentSrc)?.sighting}set sightingData(t){const e=Wi.toCurrent(t);this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:e}],void 0)}seekTo(t,e){const i=this.caseSource,n=e===void 0?void 0:this.entries.find(s=>{const r=this.plain(s).id;return(i?mn.accountIds(i.json,i.url,s.src,r):[r]).includes(e)});n&&n.src!==this.currentSrc&&this.selectObserver(n.src),this.sceneElement.ufoElement.currentTime=Math.max(0,t)*1e3}get observerUrls(){return this.entries.map(t=>t.src)}set observerUrls(t){this.loadObserverUrls(t)}async loadObserverUrls(t,e){const i=await Promise.all(t.map(async n=>({src:n,sighting:await Eo.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=mn.problems(t,e.map(s=>this.plain(s).id).filter(s=>s!==void 0));for(const s of i)console.warn(`The case ${t.id??""} gives the id "${s}" to more than one event: a reference to it is ambiguous.`);for(const{reading:s,reference:r}of n)console.warn(`The reading ${s} of the case ${t.id??""} is "interpretationOf" "${r}", which no event of the case has as its id, nor any recording it lists.`)}setEntries(t,e){this.entries=t.map(r=>({...r,sighting:Wi.toCurrent(r.sighting)})),this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";const n=t.map((r,a)=>this.observerDisplayName(this.plain(r).observer)??this.caseTitleOf(r)??this.messages.unnamedObserver.replace("{n}",String(a+1)));for(const[r,a]of t.entries()){const c=document.createElement("option");c.value=a.src;const h=n.filter(l=>l===n[r]).length>1;c.textContent=(h?this.caseTitleOf(a):void 0)??n[r],this.observerSelect.appendChild(c)}const s=t.find(r=>r.src===this.currentSrc)??this.entryAsked(t)??t[0];s?this.selectObserver(s.src):this.updateAccountLine()}entryAsked(t){const e=this.getAttribute(Hl)?.trim();if(!e)return;const i=t.find(s=>this.plain(s).observer?.id===e);if(i)return i;const n=t.find(s=>s.src.split("/").pop()===e.split("/").pop());return n||(/^\d+$/.test(e)?t[Number(e)-1]:void 0)}observerKeyOf(t){return this.plain(t).observer?.id??String(this.entries.indexOf(t)+1)}sharedEntry(){const t=this.shareScope.value;if(!(!this.caseSource||t===vf))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===vf}editorUrl(){if(!this.currentSrc)return Hm;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${Hm}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${Hm}?file=${encodeURIComponent(t.href)}`}get editorHref(){return this.editorUrl()}shownTrackUrl(){const t=this.caseSource,e=this.entries.find(s=>s.src===this.currentSrc),i=/^case-(\d+)$/.exec(this.interpretationSelect.value);if(!t||!e||!i)return;const n=mn.interpretationEvents(t.json,mn.accountIds(t.json,t.url,e.src,this.plain(e).id))[Number(i[1])];return n?.url?new URL(n.url,t.url).href:void 0}shareSubject={module:"rr0-sighting",link:()=>this.playUrl(),element:()=>this.replayElement()};replayElement(){const t=this.sharedAddress(),i=[...t.observer?[[Hl,t.observer]]:[],...this.replayAttributes()].map(([n,s])=>s===""?` ${n}`:` ${n}="${s}"`).join("");return`<rr0-sighting src="${t.src}"${i}></rr0-sighting>`}playUrl(){const t=this.sharedAddress(),e=[...t.observer?[`${Hl}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${Lf}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${Lf}/play/${e&&"?"+e}`}sharedAddress(){const t=e=>e?new URL(e,location.href).href:"";if(this.sharesCase){const e=this.entries.find(i=>i.src===this.shareOpens.value)??this.entries.find(i=>i.src===this.currentSrc);return{src:this.caseSource.url,observer:e?this.observerKeyOf(e):void 0}}return{src:t(this.sharedEntry()?.src??this.currentSrc??"")}}replayAttributes(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push([Bm,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Jr,""]),t.milestones.input.checked||e.push([jr,""]),t.compare.input.checked&&e.push([gf,""]),e}replayQuery(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push(`d=${this.shareStartSeconds}`),t.labels.input.checked||e.push("labels=0"),t.map.input.checked&&e.push("map=1"),t.milestones.input.checked||e.push("moments=0"),t.compare.input.checked&&e.push("compare=1"),e}get shareStartSeconds(){const t=Math.floor(Number(this.shareStart.value));return this.shareStartOn.checked&&Number.isFinite(t)&&t>=0?t:void 0}refreshShareLinks(){this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.refresh()}openShare(){const t=this.sceneElement.ufoElement;this.shareStart.max=String(Math.floor(t.seekableDuration/1e3)),this.shareStart.value=String(Math.floor(t.currentTime/1e3)),this.shareStartOn.checked=!1,this.shareOptions.labels.input.checked=this.labelsShown,this.shareOptions.map.input.checked=t.observerMapOpen,this.shareOptions.milestones.input.checked=t.milestonesVisible,this.shareOptions.compare.input.checked=this.sceneElement.compareAccount,this.offerShareScope(),this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.open()}offerShareScope(){const t=this.caseSource!==void 0&&this.entries.length>1;if(this.shareScopeRow.hidden=!t,this.shareScope.innerHTML="",this.shareOpens.innerHTML="",!t)return;const e=(i,n,s)=>{const r=document.createElement("option");r.value=n,r.textContent=s,i.appendChild(r)};e(this.shareScope,vf,this.messages.shareScopeCase);for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??this.caseTitleOf(i)??this.messages.unnamedObserver.replace("{n}",String(this.entries.indexOf(i)+1));e(this.shareScope,i.src,n),e(this.shareOpens,i.src,n)}this.shareScope.value=vf,this.shareOpens.value=this.currentSrc??this.entries[0].src}offerInterpretations(t){const e=this.offeredFor===t.sighting,i=this.interpretationSelect.value;this.offeredFor=t.sighting,this.interpretationToken++,this.interpretationLoaders=new Map,this.interpretationSelect.innerHTML="";const n=(u,d,f)=>{const p=document.createElement("option");p.value=u,p.textContent=d,this.interpretationSelect.appendChild(p),this.interpretationLoaders.set(u,f)},s=t===this.entries.find(u=>u.src===this.currentSrc),r=s?this.sceneElement.ufoElement.sighting.interpretation:void 0;n(Mf,this.messages.account,()=>Promise.resolve(r));const a=this.caseSource;a&&mn.interpretationEvents(a.json,mn.accountIds(a.json,a.url,t.src,this.plain(t).id)).forEach((u,d)=>{const f=this.said.read(u.title)??`#${d+1}`,p=(u.by??[]).map(m=>this.agentName(m)).filter(Boolean).join(", ");n(`case-${d}`,p?this.messages.interpretationBy.replace("{title}",f).replace("{by}",p):f,()=>mn.interpretationOf(u,a.url,m=>Eo.recording(m)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${yf}${u}`,`${this.variantLabel(d)} (${this.messages.verdicts[d.variant.verdict]})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const l=e&&[...this.interpretationSelect.options].some(u=>u.value===i)?i:Mf;this.interpretationSelect.value=l,l===Mf?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(l),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2,this.showConfrontation(this.sceneElement.confrontation),this.updateCompareButton(),this.showVariants(c)}keptVariants(t){const e={consolidated:0,contested:1,incompatible:2};return(t.sighting.variants??[]).map((i,n)=>({index:n,kept:i})).filter(({kept:i})=>i.variant).sort((i,n)=>e[i.kept.variant.verdict]-e[n.kept.variant.verdict]||i.kept.variant.cost-n.kept.variant.cost)}variantLabel(t){return this.messages.variant.replace("{name}",t.variant.label??t.variant.candidate)}showVariants(t){if(this.variantChips.innerHTML="",this.variantChips.hidden=t.length===0,t.length===0){this.showVariantMoved();return}const e=(i,n,s)=>{const r=document.createElement("button");r.type="button",r.dataset.value=i,s&&(r.dataset.verdict=s,r.title=this.messages.verdicts[s],r.append(Object.assign(document.createElement("span"),{className:"dot"}))),r.append(n),r.addEventListener("click",()=>{this.interpretationSelect.value!==i&&(this.interpretationSelect.value=i,this.chooseInterpretation(i))}),this.variantChips.append(r)};e(Mf,this.messages.account);for(const{index:i,kept:n}of t)e(`${yf}${i}`,n.variant.label??n.variant.candidate,n.variant.verdict);this.showVariantMoved()}showVariantMoved(){const t=this.interpretationSelect.value;for(const s of this.variantChips.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.value===t));this.variantMoved.innerHTML="";const e=t.startsWith(yf)?Number(t.slice(yf.length)):-1,i=this.sceneElement.ufoElement.sighting.variants?.[e]?.variant;if(this.variantMoved.hidden=!i||i.moved.length+(i.readings?.length??0)===0,!i)return;const n=new Intl.NumberFormat(this.language,{maximumFractionDigits:1});for(const s of i.moved){const[r,a]=s.field==="time"?["0 min",`${s.variant>0?"+":""}${n.format(s.variant)} min`]:s.field==="duration"?[`${n.format(s.stated)} s`,`${n.format(s.variant)} s`]:[`${n.format(s.stated)}°`,`${n.format(s.variant)}°`],c=document.createElement("span");c.append(`${this.messages.variantFields[s.field]}${this.colon}`,Object.assign(document.createElement("s"),{textContent:r})," → ",Object.assign(document.createElement("b"),{textContent:a})),this.variantMoved.append(c)}for(const s of i.readings??[]){const r=this.messages.variantReadings[s.reading];r&&this.variantMoved.append(Object.assign(document.createElement("span"),{className:"reading",textContent:r}))}}setComparing(t){this.sceneElement.compareAccount=t,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation)}updateCompareButton(){const t=this.sceneElement.compareAccount;this.compareButton.hidden=!this.sceneElement.interpretation,this.compareButton.setAttribute("aria-pressed",String(t));const e=t?this.messages.hideComparison:this.messages.showComparison;this.compareButton.title=e,this.compareButton.setAttribute("aria-label",e)}static DATE_LOCALES={en:"en-US",fr:"fr-FR",es:"es-ES",it:"it-IT"};get colon(){return this.language==="fr"?" : ":": "}async chooseInterpretation(t){const e=++this.interpretationToken,i=this.interpretationLoaders.get(t),n=i?await i().catch(s=>{console.warn(`<rr0-sighting>: could not read interpretation "${t}":`,s)}):void 0;e===this.interpretationToken&&(this.sceneElement.interpretation=n,this.editLink.href=this.editorUrl(),this.dispatchEvent(new CustomEvent("interpretationchange",{detail:{track:this.shownTrackUrl()}})),this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation),this.showVariantMoved())}agentName(t){if("people"in t){const[e,...i]=t.people.replace(/([a-z])([A-Z])/g,"$1 $2").split(" ");return[...i,e].join(" ")}return"org"in t?t.org.replace(/([a-z])([A-Z])/g,"$1 $2"):this.observerDisplayName(t)??""}showConfrontation(t){this.confrontationList.innerHTML="",this.confrontationElement.hidden=!this.sceneElement.interpretation||!this.sceneElement.compareAccount;const e=new Intl.NumberFormat(this.language,{maximumFractionDigits:1,minimumFractionDigits:1}),i=new Intl.NumberFormat(this.language,{maximumFractionDigits:2,minimumFractionDigits:2});for(const n of t){const s=document.createElement("li");s.append(`${this.said.read(n.title)??n.sourceId}${this.colon}`);const r=[];n.separationDeg!==void 0&&r.push([this.messages.confrontationDirection.replace("{deg}",e.format(n.separationDeg)),n.disagreements.includes("direction")]),n.widthRatio!==void 0&&r.push([this.messages.confrontationWidth.replace("{ratio}",i.format(n.widthRatio)),n.disagreements.includes("width")]),n.heightRatio!==void 0&&r.push([this.messages.confrontationHeight.replace("{ratio}",i.format(n.heightRatio)),n.disagreements.includes("height")]),r.forEach(([a,c],h)=>{h>0&&s.append(" · ");const l=document.createElement("span");l.textContent=a,c&&(l.className="disagrees"),s.append(l)}),this.confrontationList.appendChild(s)}}startPending=!1;startSeconds(t){const e=On.clock(this.getAttribute(jw)),i=this.plain(t).time;return(e?On.elapsedSince(i===void 0?void 0:Dh(i),e):void 0)??On.delta(this.getAttribute(Bm))}selectObserver(t){const e=this.entries.find(n=>n.src===t);if(!e)return;this.currentSrc=t,this.observerSelect.value=t,this.sceneElement.documentUrl=e.src?new URL(e.src,location.href).href:void 0;const i=!this.sceneElement.ufoElement.playRequested;if(e.sighting.image?this.sceneElement.showPoster(e.sighting.image,e.src?new URL(e.src,location.href).href:void 0,i):this.sceneElement.showPoster(this.caseSource?.json.image,this.caseSource?.url,i),this.sceneElement.holdForNewScene(),this.sceneElement.sightingData=e.sighting,this.startPending){this.startPending=!1;const n=this.startSeconds(e);n!==void 0&&(this.sceneElement.ufoElement.currentTime=Math.max(0,n)*1e3)}this.offerInterpretations(e),this.updateAccountLine(),this.refreshParamSummary(),this.runAssessments(),this.infoOpen&&this.populateInfoPanel(),this.dispatchEvent(new CustomEvent(UN,{detail:{src:t}}))}async runAssessments(){const t=++this.assessmentToken,e=await new O1(this.messages).read(this.sceneElement.ufoElement.sighting);t===this.assessmentToken&&(this.assessmentEntries=e.entries,this.refreshParamSummary())}updateAccountLine(){const t=this.entries.find(n=>n.src===this.currentSrc),e=t?this.observerDisplayName(this.plain(t).observer):void 0,i=e!==void 0||this.entries.length>1;this.accountElement.hidden=!i,this.observerText.textContent=e??"",this.editLink.hidden=!this.currentSrc,this.editLink.href=this.editorUrl(),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation)}caseTitleOf(t){const e=this.caseSource;if(!e)return;const i=e.json.events?.find(n=>n.url!==void 0&&!n.interpretationOf&&new URL(n.url,e.url).href===new URL(t.src,location.href).href);return i?this.said.read(i.title):void 0}observerDisplayName(t){if(!t)return;const e=[...t.firstNames??[],t.lastName].filter(Boolean).join(" ");return this.said.read(t.title)||e||t.id}plainRecordings=new WeakMap;plain(t){return this.stripped(t).recording}stripped(t){let e=this.plainRecordings.get(t.sighting);return e||(e=os.strip(t.sighting),this.plainRecordings.set(t.sighting,e)),e}basisOf(t,e){const i=this.stripped(t).provenance,n={measured:-1,stated:0,derived:1,assumed:2},s=i.paths().filter(c=>e.some(h=>c===h||c.startsWith(`${h}.`))).map(c=>i.at(c)),r=s.reduce((c,h)=>n[h.basis]>n[c]?h.basis:c,"stated"),a=s.filter(c=>c.basis===r&&c.rationale).map(c=>c.rationale);return{basis:r,rationales:a}}formatDate(t){const e=t.place?.locations?.[0],i=Xo((t.time?Dh(t.time):void 0)??{},e?.lng??0,t.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(t,e?.lng??0)*36e5;if(Number.isFinite(n))return new Intl.DateTimeFormat(Xh.DATE_LOCALES[this.language],{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(t,e){return t.utcOffsetHours??Math.round(e/15)}formatLocation(t){const e=t.place?.locations?.[0];if(e)return`${e.lat.toFixed(4)}, ${e.lng.toFixed(4)}`}toggleInfoPanel(){const t=!this.infoOpen;if(this.supportsPopover){const e=this.infoPanel.matches(":popover-open");t&&!e?this.infoPanel.showPopover():!t&&e&&this.infoPanel.hidePopover();return}t&&this.bringInfoButtonIntoView(),this.syncInfoOpen(t),this.infoPanel.hidden=!t,t?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const t=this.infoButton.getBoundingClientRect(),e=window.innerHeight||document.documentElement.clientHeight;t.top>=0&&t.bottom<=e||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(t){t!==this.infoOpen&&(this.infoOpen=t,this.infoButton.setAttribute("aria-expanded",String(t)),t?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=t=>{const e=t.composedPath();!e.includes(this.infoPanel)&&!e.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}revealInPanel(t){t.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(t){this.toggleAttribute("show-labels",t)}applyLabels(t){this.labelsShown=t,this.syncLabelsToggle(),this.refreshParamSummary(),this.populateInfoPanel()}syncLabelsToggle(){this.labelsToggle.textContent=this.labelsShown?this.messages.hideLabels:this.messages.showLabels,this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,!this.labelsShown){this.paramSummary.replaceChildren(),this.summarySignature="";return}const t=this.sceneElement.ufoElement.sighting,e=[...this.summaryBuilder.entriesFor(t,this.sceneElement.ufoElement.currentTime,{roadGradeDeg:this.sceneElement.roadGradeDeg}),...this.assessmentEntries],i=e.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.full??""}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of e){s&&s.group!==r.group&&(s=void 0);const a=r.group==="summary"?this.messages.summaryGroup:r.group==="observer"?this.messages.observerGroup:r.group in this.messages.summaryGroups?this.messages.summaryGroups[r.group]:r.group==="assessment"?this.messages.assessmentGroup:void 0;if(a!==void 0&&!s){const h=document.createElement("span");h.className="param-nest";const l=document.createElement("span");l.className="param-nest-label",l.textContent=a,h.append(l),s={group:r.group,element:h},n.push(h)}const c=this.paramItem(r);s?s.element.append(c):n.push(c)}this.paramSummary.replaceChildren(...n),this.syncDescription(e)}openDescription;syncDescription(t){this.openDescription!==void 0&&!t.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),fb.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription(t)})}paramItem(t){const e=document.createElement("span");if(e.className=t.fromSource?"param-label from-source":"param-label",t.detail&&(e.title=t.detail),t.full!==void 0){e.classList.add("describable"),e.tabIndex=0,e.setAttribute("role","button");const s=()=>{this.openDescription=t.full,this.syncDescription([t])};e.addEventListener("click",s),e.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),s())})}const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${t.label} `,e.append(i),t.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=t.color,e.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=t.unit===""?t.value:`${t.value} ${t.unit}`,e.append(n),e}populateInfoPanel(){const t=this.entries.find(e=>e.src===this.currentSrc);if(this.infoObservationList.innerHTML="",t){const e=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(e&&this.appendInfoRow(this.infoObservationList,this.messages.case,e),!this.labelsShown){const s=this.formatDate(this.plain(t));s&&this.appendInfoRow(this.infoObservationList,this.messages.date,s,this.basisOf(t,Xh.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages.location,r,this.basisOf(t,Xh.PLACE_PATHS))}const i=this.said.read(this.plain(t).description);i&&!this.labelsShown&&this.appendInfoRow(this.infoObservationList,this.messages.description,i);for(const s of this.plain(t).sources??[])this.appendInfoSource(this.infoObservationList,this.messages.source,s);const n=this.plain(t).tags;!this.labelsShown&&n&&n.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,n.map(s=>this.tags.name(s)).join(", "))}this.infoAppLink.href=Lf,this.infoAppLink.textContent="UFO@home v0.162.0",In.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=this.said.read(i.title)??i.url??"";if(i.url&&/^https?:\/\//i.test(i.url)){const c=document.createElement("a");c.href=i.url,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,s.appendChild(c)}else s.append(r);const a=[i.authors?.join(", "),i.publication?.publisher,i.publication?.time,i.index].filter(Boolean);a.length>0&&s.append(`, ${a.join(", ")}`),t.append(n,s)}static DATE_PATHS=["time","utcOffsetHours","timeZone"];static PLACE_PATHS=["place"];appendInfoRow(t,e,i,n){const s=document.createElement("dt");s.textContent=e;const r=document.createElement("dd");if(r.textContent=i,n){const a=document.createElement("span");a.className=`basis basis-${n.basis}`,a.textContent=this.messages.basis[n.basis],n.rationales.length>0&&(a.title=n.rationales.join(`
9453
+ `)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const Qw="rr0-sighting",UN="observerchange",tb="rr0-eyeobserver";class FN extends Xh{}function zN(){IS(),Wh.register(),customElements.get(Qw)||customElements.define(Qw,Xh),customElements.get(tb)||customElements.define(tb,FN)}zN();export{Mn as $,hc as A,zt as B,rt as C,ch as D,oe as E,pe as F,Be as G,VN as H,QN as I,s3 as J,bs as K,$m as L,CT as M,Rf as N,No as O,Lg as P,Al as Q,_t as R,Es as S,Pn as T,RT as U,rr as V,KN as W,ls as X,_n as Y,$t as Z,vn as _,rs as a,JN as a0,vc as a1,kn as a2,An as a3,ye as a4,Pi as a5,nn as a6,Jn as a7,Di as a8,pN as a9,oi as aA,WN as aB,$N as aC,ax as aD,YN as aE,Nn as aF,Gs as aG,rx as aH,jy as aI,H_ as aJ,xS as aK,Kf as aL,Pg as aM,bx as aN,ev as aO,iv as aP,Fe as aQ,Io as aR,id as aS,Sv as aa,BN as ab,GN as ac,HN as ad,nd as ae,jN as af,qN as ag,Jf as ah,Sx as ai,s0 as aj,XN as ak,qn as al,Oy as am,ZN as an,t8 as ao,nx as ap,Bs as aq,pd as ar,Mp as as,H3 as at,je as au,Do as av,ig as aw,Xi as ax,oa as ay,Y_ as az,pu as b,tf as c,ys as d,Mt as e,it as f,de as g,eu as h,me as i,lo as j,fe as k,As as l,er as m,e8 as n,e0 as o,BA as p,tn as q,vr as r,Xo as s,yr as t,T as u,Te as v,Lr as w,bt as x,_e as y,i8 as z};