@rr0/ufoathome 0.150.1 → 0.150.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -2399,9 +2399,9 @@ canvas[data-cursor="rotate"] {
|
|
|
2399
2399
|
`;class Kc{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 Kc(e)}static TRAVEL_M=50;get travels(){return this.spanM>Kc.TRAVEL_M}get moved(){return this.spanM>Kc.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(ie(e,t.east,e,t.west).x),Math.abs(ie(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:es(0,-s,i,n).lat,south:es(0,s,i,n).lat,east:es(s,0,i,n).lng,west:es(-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 ws{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){const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>ws.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new ws(Math.max(1-(t.instrument.stabilization??0),ws.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]=ws.HZ;return{eastM:i*ws.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*ws.SWAY_M*(.6*n(a,2.2)+.4*n(h,.8)),upM:i*ws.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*ws.DRIFT_YAW_DEG*(.6*n(l,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*ws.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*ws.DRIFT_ROLL_DEG*n(s,2.9)}}}class $e{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=Kc.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=ie(a.lat,a.lng,r.lat,r.lng),l=h.x,u=-h.z,d=Math.hypot(l,u),f=d/c,p=$e.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 $e(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=$e.of(t)?.offsetAt(e)??$e.STILL;return i?n:$e.add(n,ws.of(t)?.offsetAt(e))}static stepHzFor(t){return t<$e.SLOWEST_WALK_M_PER_S||t>$e.FASTEST_WALK_M_PER_S?0:$e.REFERENCE_STEP_HZ*Math.pow(t/$e.REFERENCE_SPEED_M_PER_S,$e.CADENCE_EXPONENT)}offsetAt(t){return $e.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/$e.REFERENCE_SPEED_M_PER_S,n=(a,c,h,l)=>{if(a<0||a>$e.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/$e.JOLT_DECAY_S)*Math.sin(2*Math.PI*$e.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,$e.STOP_LURCH_M,$e.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,$e.START_LURCH_M,$e.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 $e.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=$e.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/$e.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:$e.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:$e.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:$e.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 IS{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 Iy=["nw","n","ne","e","se","s","sw","w"],DS=24,Jl=8,CS=3,OS=8;function jl(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 _h(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const PS={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 fs{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-DS}},a=_h(t.bounds),c={};for(const h of Object.keys(r))c[h]=jl(r[h],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...Iy,"rotate"]){const s=fs.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=((fs.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=_h(t),r=jl(n,s,-e),{x:a,y:c,width:h,height:l}=t,u=PS[i];let d=a,f=c,p=a+h,g=c+l;return u.left&&(d=Math.min(r.x,p-Jl)),u.right&&(p=Math.max(r.x,d+Jl)),u.top&&(f=Math.min(r.y,g-Jl)),u.bottom&&(g=Math.max(r.y,f+Jl)),{x:d,y:f,width:p-d,height:g-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=fs.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=_h(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=_h(t.bounds);return t.points.map(i=>jl({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=OS){const n=fs.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=_h(t.bounds),n=jl(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?fs.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=fs.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=fs.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<=CS?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const Lp=6,Ql=Lp/2,J1=20,j1=24,Q1=9,tv=6,ev=7,iv=6,er=4;class hh{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+Q1*f),iv*f)-d:0,g=f>0?d*(1+ev*f)-d:0,m=3*j1*(t.blur??0)+1.5*J1*t.haloScale,v=Math.max(p,g,0)+m+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(${(j1*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+Q1*e),iv*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<=tv;d++){const f=d/tv,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+ev*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,g=a+Math.cos(p)*d,m=c+Math.sin(p)*d,v=this.ctx.createLinearGradient(a,c,g,m);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(g,m),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=J1*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(fs.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of fs.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(fs.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=hh.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(fs.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 Iy){const n=t[i];this.ctx.fillRect(n.x-Ql,n.y-Ql,Lp,Lp)}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,Ql+1,Ql+1,0,0,2*Math.PI),this.ctx.fill())}}const nv=.05,sv=.08,rv=2,av=3,LS=14,NS=.02;class kS{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}}Co.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,nv);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,nv)}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*rv),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*rv),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*av),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(NS*t.sampleRate)),s=Math.round(av*LS);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,sv/3);const n=i+sv;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 lr{static KINDS=["beams","launches","reentries"];static isEmpty(t){return!t||lr.KINDS.every(e=>!t[e]?.length)}static written(t){if(lr.isEmpty(t))return;const e={};for(const i of lr.KINDS)t[i]?.length&&(e[i]=t[i]);return e}static read(t,e){const i=e,n={};for(const r of lr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&lr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...h}=i;s=lr.isReading(h)?h:void 0}return{skyEvents:lr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function rl(o){return[...o].sort((t,e)=>t.t-e.t)}function jf(o,t){let e;for(const i of rl(o)){if(i.t>t)break;e=i}return e}const Qf=Math.PI/180,tu=180/Math.PI;class wr{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*Qf/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new wr(t.projection,e,i)}degToPx(t){const e=t*Qf;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*tu:2*Math.atan(t/(2*this.focalPx))*tu}angleDegToRadiusPx(t){const e=t*Qf;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*tu:Math.atan(t/this.focalPx)*tu}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(Je.angularWidthDeg(t))}}class In{static fovOf(t,e){return Be(t,e)?.fovDeg??nn.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)<In.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<In.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=wr.of(t.instrument,Je.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,Be(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=Be(t,s.t),c=wr.of(t.instrument,Je.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(([m,v])=>m!=="bounds"&&m!=="points"&&JSON.stringify(v)!==JSON.stringify(u[m]))),p={...d,...f},g=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);In.near(g,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)<=In.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:nn.frameWidthPx(t.instrument,Je.CANVAS_HEIGHT_PX)/2,y:Je.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=In.OFF_CANVAS_DEG?Math.sign(e)*In.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=nn.frameWidthPx(e,Je.CANVAS_HEIGHT_PX)/2,s=nn.frameWidthPx(t.instrument,Je.CANVAS_HEIGHT_PX)/2,r=Je.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=wr.of(e,Je.CANVAS_HEIGHT_PX,h),u=wr.of(t.instrument,Je.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,g=f.y+f.height/2-r,m=Math.hypot(p,g),v=m===0?1:u.angleDegToRadiusPx(l.radiusPxToAngleDeg(m))/m,y={...f,x:s+p*v-f.width/2,y:r+g*v-f.height/2};return{...d,shape:{...d.shape,bounds:y}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=Be(t,n.t),r=this.fovOf(t,n.t),a=wr.of(t.instrument,Je.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 Nn{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(Nn.isRelative(t)){const i=Nn.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return Nn.isAbsolute(t)&&e.origin?Nn.toLocal(t,e.origin):void 0}static restated(t,e,i){if(Nn.isRelative(t)){const s=Nn.referenceOf(t,i);return s?Nn.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=Nn.toGeo(e,i.origin);return{lat:Nn.degrees(n.lat),lng:Nn.degrees(n.lng)}}static relative(t,e,i){const n={eastM:Nn.metres(t),northM:Nn.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=ie(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return es(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 Un{static restatedDecor(t){const e=Un.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=Un.restated(i.saidPosition,i,Un.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=Un.restated(r.saidPosition,r,Un.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=Un.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=Nn.toLocal({lat:s.lat,lng:s.lng},i),a=Un.restated(s.saidPosition,r,Un.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=Un.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?Un.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},Un.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}=Ys(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return Nn.restated(t,{eastM:e.eastM,northM:e.northM},i)}}function US(o){return Bn.restore(FS(o),o.provenance)}function FS(o){return In.toAngular(o),In.toAim(o),{version:1,id:o.id,time:o.event.time,endTime:o.event.endTime,durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place: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:o.timeline.toJSON(),observerTrack:Un.restatedObserverTrack(o),weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:Un.restatedDecor(o),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,lens:o.lens,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:Un.restatedInterpretation(o),variants:o.variants.length>0?o.variants:void 0,skyEvents:lr.written(o.skyEvents),frozen:o.frozen}}function zS(o){oo.check(o,"sighting");const{recording:t,provenance:e}=Bn.strip(o),i=BS(t);return i.provenance=e,i}function BS(o){const t=[],e=new Df({eventType:"sighting",time:o.time,endTime:o.endTime,durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:o.place,description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Af.fromJSON(o.timeline,t),o.observerTrack?Sl.fromJSON(o.observerTrack):new Sl,o.weatherTrack?El.fromJSON(o.weatherTrack):new El,o.soundTrack?Al.fromJSON(o.soundTrack):new Al,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,o.decor??[],o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),rl(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.lens=o.lens,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle;const i=lr.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,In.toBounds(e),In.toPosition(e),e}class lh{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=lh.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=>` ${lh.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
2400
2400
|
${i.join(`
|
|
2401
2401
|
`)}`)}}class Us{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!Us.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Us.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(Us.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):Us.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:Us.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=Us.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:Us.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:Us.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return Us.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 Hs{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?Hs.travelDegOver(t,e,i,i+n*1e3)/s/Hs.PIXELS_PER_INSTANT:0,a=Hs.flashesOver(t,n)*Hs.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(Hs.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=Hs.directionAt(r,e,i),c=Hs.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=Ys(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 mg=["en","fr","es","it"],HS={en:()=>Ee(()=>Promise.resolve().then(()=>KS),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>Ee(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>Ee(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>Ee(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function GS(o){return HS[o]()}const VS={en:()=>Ee(()=>Promise.resolve().then(()=>LO),void 0,import.meta.url).then(o=>o.sightingMessages_en),fr:()=>Ee(()=>import("./SightingMessages_fr-G2VuAfwH.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>Ee(()=>import("./SightingMessages_es-CM9UNBab.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>Ee(()=>import("./SightingMessages_it-B66vxPfo.js"),[],import.meta.url).then(o=>o.sightingMessages_it)};function WS(o){return VS[o]()}const XS={en:()=>Ee(()=>Promise.resolve().then(()=>NO),void 0,import.meta.url).then(o=>o.shareMessages_en),fr:()=>Ee(()=>import("./ShareMessages_fr-DyOB2E5o.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>Ee(()=>import("./ShareMessages_es-BM5hHumO.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>Ee(()=>import("./ShareMessages_it-C9F8UHk_.js"),[],import.meta.url).then(o=>o.shareMessages_it)};function $S(o){return XS[o]()}function YS(o){switch(o){case"fr":return Ee(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return Ee(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return Ee(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}function Dy(o){switch(o){case"fr":return Ee(()=>import("./SceneNames_fr-DixomaFq.js"),[],import.meta.url).then(t=>t.sceneNames_fr);case"es":return Ee(()=>import("./SceneNames_es-CPCIUfgZ.js"),[],import.meta.url).then(t=>t.sceneNames_es);case"it":return Ee(()=>import("./SceneNames_it-BTNeU7-M.js"),[],import.meta.url).then(t=>t.sceneNames_it);default:return Promise.resolve(void 0)}}const Cy={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:lh.EN},KS=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:Cy},Symbol.toStringTag,{value:"Module"})),Oy=Math.PI/180,qS=180/Math.PI,ZS=256,Py=19,JS=1.25;function Ly(o,t){return 156543.03392*Math.cos(o*Oy)/2**t}function Ny(o,t){return Ly(o,t)*ZS}function jS(o,t){let e=0;for(;e<Py&&Ny(o,e+1)>=t;)e++;return e}function ky(o,t){return Ny(o,t)}function QS(o,t){const e=t*JS;let i=0;for(;i<Py&&Ly(o,i)>e;)i++;return i}function cd(o){const t=o*Oy;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function Uy(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:cd(t)*i}}function Fy(o,t,e){const i=cd(o.north),n=cd(o.south);return{x:(t-o.west)/(o.east-o.west),y:(cd(e)-i)/(n-i)}}function tE(o,t,e){const{x:i,y:n}=Uy(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function eE(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=ov(o.y,t);return{south:ov(o.y+1,t),north:n,west:e,east:i}}function ov(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*qS}function zy(o,t,e,i){const n=tE(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(eE),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 iE="#2ec4ff";class no{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=Fy(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??iE;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:no.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,no.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=ie(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=no.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?no.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(ie(r,t.east,r,t.west).x)/this.width,h=no.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 ti{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 ti.including(t.boundsAround(ti.MIN_SPAN_M,ti.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(ti.MAX_ZOOM,Math.max(ti.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=ti.mercatorY01(e.north),s=ti.mercatorY01(e.south),r=ti.mercatorY01(i.north),a=ti.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=ti.mercatorY01(n.north),r=ti.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(ti.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=ti.mercatorY01(t.north),n=ti.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:ti.latitudeAt(i+(this.centerY-e)*(n-i)),south:ti.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=ie(n,t.east,n,s).x;let a=r;for(const c of e){const{x:h,z:l}=ie(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:es(0,-a,n,s).lat,south:es(0,a,n,s).lat,east:es(a,0,n,s).lng,west:es(-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=ti.mercatorY01(t.north),s=ti.mercatorY01(t.south);return{lat:ti.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 xs=256,cv=3,nE=32768;class sE{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(ie(i,t.east,i,t.west).x),r=Math.abs(ie(t.north,n,t.south,n).z),a=jS(i,Math.max(s,r)),{tiles:c}=zy(n,i,a,cv),h=cv*xs,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 g=0;g<e.width;g++){const m=t.west+(t.east-t.west)*(g/(e.width-1));d[f*e.width+g]=this.sampleAt(p,m,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=xs,c.height=xs;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,xs,xs),u=(t.x-e.x)*xs,d=(t.y-e.y)*xs;for(let f=0;f<xs;f++)for(let p=0;p<xs;p++){const g=(f*xs+p)*4,m=l[g]*256+l[g+1]+l[g+2]/256-nE,v=u+p,y=d+f;i[y*n+v]=m}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=Uy(e,t,i),h=(a-n.x)*xs,l=(c-n.y)*xs,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),g=h-u,m=l-d,v=s[d*r+u],y=s[d*r+f],x=s[p*r+u],M=s[p*r+f],b=v+(y-v)*g,S=x+(M-x)*g;return b+(S-b)*m}}class Of{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 y=i+2+v*12;s.set(e.getUint16(y,!0),{type:e.getUint16(y+2,!0),count:e.getUint32(y+4,!0),value:e.getUint32(y+8,!0)})}const r=(v,y)=>{const x=s.get(v);if(x===void 0){if(y===void 0)throw new Error(`TIFF without tag ${v}`);return y}return x.type===3?x.value&65535:x.value},a=v=>{const y=s.get(v);if(y===void 0)throw new Error(`TIFF without tag ${v}`);const x=y.type===3?2:4,M=[];if(y.count*x<=4){const b=new DataView(new ArrayBuffer(4));b.setUint32(0,y.value,!0);for(let S=0;S<y.count;S++)M.push(x===2?b.getUint16(S*2,!0):b.getUint32(0,!0))}else for(let b=0;b<y.count;b++)M.push(x===2?e.getUint16(y.value+b*2,!0):e.getUint32(y.value+b*4,!0));return M};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),g=new Uint8Array(c*h*l*(u/8));let m=0;for(let v=0;v<f.length&&m<g.length;v++){const y=Math.min(p[v],g.length-m);g.set(new Uint8Array(t,f[v],y),m),m+=y}if(m<g.length)throw new Error("Truncated TIFF");return new Of(c,h,l,d?new Float32Array(g.buffer):g)}}class oa extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class rE{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 Ie{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??Ie.WMS,this.wfs=t.wfsEndpoint??Ie.WFS}static radius(t){return Math.min(t,Ie.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Ie.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=Ie.lidarRadius(e),n=Math.ceil(2*i/Ie.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,Ie.HEIGHT_LAYER),this.raster(t,i,n,Ie.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new oa("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===Ie.NO_DATA))throw new oa("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 rE(a,c,h,n,l)}}async laserDate(t){return Ie.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Ie.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=Ie.radius(e),n=Math.min(Ie.MAX_PHOTO_PIXELS,Math.ceil(2*i/Ie.METRES_PER_PIXEL)),s=await this.raster(t,i,n,Ie.PHOTO_LAYER);if(s.samples<3)throw new oa("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=Ie.radius(e),s=n/Ie.METRES_PER_DEGREE,r=n/(Ie.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,Ie.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),g=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],m=[...f,...g];return{bridges:h,elevatedRoads:l,elevatedRailways:u,lines:d,buildings:m,zones:p,mapDate:Ie.latest(m.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=Ie.MAX_WHOLE_M/Ie.METRES_PER_DEGREE;let h;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,g]=Ie.extent(u);if(d>=n&&f>=s&&p<=r&&g<=a)continue;const m=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(g,a+c)];h=h?[Math.min(h[0],m[0]),Math.min(h[1],m[1]),Math.max(h[2],m[2]),Math.max(h[3],m[3])]:m}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')`,Ie.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/Ie.METRES_PER_DEGREE,r=e/(Ie.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 oa("unreachable",h instanceof Error?h.message:String(h))}if(!c.ok)throw new oa("unreachable",`The survey answered ${c.status}`);try{return Of.parse(await c.arrayBuffer())}catch(h){throw new oa("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 oa("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new oa("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class wa{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=>ie(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>ie(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/wa.SAMPLE_M)),d=Math.atan2(h.x-c.x,-(h.z-c.z));for(let f=0;f<=u;f++){const p=f/u,g=wa.nearest(n,c.x+(h.x-c.x)*p,c.z+(h.z-c.z)*p);g.distanceM>wa.NEAR_M||wa.angleBetween(d,g.heading)<=wa.ALIGNED_DEG&&(r+=l/u)}}return r>=wa.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 Se{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??Se.WMS,this.timeoutMs=t.timeoutMs??Se.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Se.MAX_WINDOW_M,this.geoplatform=new Ie({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(!Ie.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(ie(n.lat,t.east,n.lat,t.west).x),r=Math.abs(ie(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/Se.METRES_PER_DEGREE,north:t.north+c.y/Se.METRES_PER_DEGREE,west:t.west-c.x/(Se.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Se.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},l=g=>Math.min(Se.MAX_PIXELS,Math.max(Se.MIN_PIXELS,Math.ceil(g/Se.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)>Se.COARSE_METRES_PER_PIXEL;for(const g of p?[...Se.LAYERS].reverse():Se.LAYERS)try{const m=await this.heights(h,u,g);g===Se.LAYERS[0]&&await this.layBridgeDecks(m,h,u,i?.route);const v=this.sample(m,e,t,h,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${g} does not cover this place`)}catch(m){f=m}throw f}finer(t,e,i){if(t.width<Se.MESH_FROM_VERTICES||t.height<Se.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Se.FINE_SPACING_M),c=Math.max(r-1,Math.min(Se.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 Of.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>Se.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>wa.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,Se.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(m,[v,y,x])=>s.values[m*s.samples]===v&&s.values[m*s.samples+1]===y&&s.values[m*s.samples+2]===x,a=t.width,c=t.height,h=new Uint8Array(a*c);let l=!1;for(let m=0;m<h.length;m++)r(m,Se.DECK)&&(h[m]=1,l=!0);if(!l)return;const u=Se.DECK_END_PIXELS,d=[];for(let m=0;m<h.length;m++){if(h[m]!==1)continue;const v=m%a,y=(m-v)/a;for(let x=-u;x<=u;x++)for(let M=-u;M<=u;M++){const b=v+M,S=y+x;if(b<0||S<0||b>=a||S>=c)continue;const E=S*a+b;h[E]===0&&r(E,Se.NO_CLASS)&&d.push(E)}}for(const m of d)h[m]=1;const f=this.paint(n,e,a,c),p=this.touching(h,f,a,c);if(p.every(m=>m===0))return;const g=await this.heights(e,i,Se.SURFACE_LAYER);if(g.width!==a||g.height!==c)return;for(let m=0;m<p.length;m++){if(p[m]===0)continue;const v=g.values[m];Number.isFinite(v)&&v>Se.NO_DATA_BELOW&&v>t.values[m]&&(t.values[m]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Se.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),h=(i.north-i.south)*Se.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,y)=>{const x=Math.floor(v/l),M=Math.floor(y/u);if(x<0||M<0||x>=s||M>=r)return;const b=e[M*s+x];return Number.isFinite(b)&&b>Se.NO_DATA_BELOW?b:void 0},p=Se.DECK_HALF_WIDTH_M,g=Se.DECK_APPROACH_M,m=(v,y)=>{const x=Math.hypot(v.x-y.x,v.y-y.y)||1,M={x:(v.x-y.x)/x,y:(v.y-y.y)/x},b=[0,g/2,g].map(S=>f(v.x+M.x*S,v.y+M.y*S)).filter(S=>S!==void 0);return b.length>0?Math.max(...b):void 0};for(const v of Se.chains(n.map(y=>y.map(d)))){const y=[0];for(let I=1;I<v.length;I++)y.push(y[I-1]+Math.hypot(v[I].x-v[I-1].x,v[I].y-v[I-1].y));const x=y[y.length-1];if(x<1||x>Se.DECK_STRAIGHT_MAX_M)continue;const M=m(v[0],v[1]),b=m(v[v.length-1],v[v.length-2]);if(M===void 0||b===void 0)continue;const S=p+g,E=Math.max(0,Math.floor((Math.min(...v.map(I=>I.x))-S)/l)),w=Math.min(s-1,Math.ceil((Math.max(...v.map(I=>I.x))+S)/l)),_=Math.max(0,Math.floor((Math.min(...v.map(I=>I.y))-S)/u)),D=Math.min(r-1,Math.ceil((Math.max(...v.map(I=>I.y))+S)/u));for(let I=_;I<=D;I++)for(let O=E;O<=w;O++){const L=Se.nearestAlong(v,y,{x:(O+.5)*l,y:(I+.5)*u});if(L.distance>p||L.s<-g||L.s>x+g)continue;const N=M+(b-M)*Math.min(1,Math.max(0,L.s/x)),P=I*s+O;e[P]>=N||(t.values[P]=N)}}}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 g=0;g<=p;g++){const m=Math.floor(l+(d-l)*g/p),v=Math.floor(u+(f-u)*g/p);for(let y=-1;y<=1;y++)for(let x=-1;x<=1;x++){const M=m+x,b=v+y;M>=0&&b>=0&&M<i&&b<n&&(s[b*i+M]=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 g=-1;g<=1;g++){const m=d+g,v=f+p;if(m<0||v<0||m>=i||v>=n)continue;const y=v*i+m;t[y]===1&&r[y]===0&&(r[y]=1,h.push(y))}}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 g=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),m=(n.north-g)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const x=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,M=u>1||d>1?this.tent(t,x,m,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,m),b=p*a+v;M===void 0?f++:(h[b]=M,l[b]=1)}}if(!(f===a*c||f/(a*c)>Se.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 g=u;g<=d;g++){const m=p*(1-Math.abs(g-e)/n);if(m<=0)continue;c+=m;const v=t.at(g,f);!Number.isFinite(v)||v<Se.NO_DATA_BELOW||(r+=m*v,a+=m)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),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 m of[l,u,d,f])if(!Number.isFinite(m)||m<Se.NO_DATA_BELOW)return;const p=l+(u-l)*c,g=d+(f-d)*c;return p+(g-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,g=c+f;p<0||g<0||p>=n||g>=i||!e[p*i+g]||(l+=t[p*i+g],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 aE{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 hd=256,oE=5;async function By(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(ie(n,o.east,n,o.west).x),a=Math.abs(ie(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:h,gridSize:l}=cE(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=zy(s,n,h,l),f=l*hd,p=document.createElement("canvas");p.width=f,p.height=f;const g=p.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async M=>{const b=e(M),S=await i(b);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${b}`);const E=await createImageBitmap(await S.blob());g.drawImage(E,(M.x-m.x)*hd,(M.y-m.y)*hd)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const y=document.createElement("canvas");y.width=v,y.height=v;const x=y.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,v,v),{source:y,width:v,height:v,bounds:d}}function cE(o,t,e){let i=QS(o,t/Math.max(1,e)),n=hv(o,i,t);for(;n>oE&&i>0;)i--,n=hv(o,i,t);return{zoom:i,gridSize:n,mPerPixel:ky(o,i)/hd}}function hv(o,t,e){const i=Math.ceil(e/2/ky(o,t));return Math.max(3,2*i+1)}class Hy{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 By(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class jn{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=jn.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=jn.FRANCE;return c>=l.south&&c<=l.north&&h>=l.west&&h<=l.east?[jn.FRANCE_ENDPOINT,...e.filter(d=>d!==jn.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=jn.queue.then(t,t);return jn.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??jn.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(jn.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,jn.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class Sa{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 jn(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Sa.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:Sa.surfaceOf(s),widthM:Sa.widthOf(s),...Sa.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:Sa.WIDTH_M[t.highway]??Sa.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 t0="https://ufoathome.org/roads/index.json";class Pc{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??Pc.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(`
|
|
2402
|
-
`);let e=Pc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Pc.shared.set(t,e),e.then(i=>{i.length===0&&Pc.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.150.
|
|
2403
|
-
`);let e=Lc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Lc.shared.set(t,e),e.then(i=>{i.length===0&&Lc.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.150.1")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==e0?[e,e0]:[e0]).map(i=>i+t)}}class Yn{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=Yn.key(t);let i=Yn.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Yn.asked.set(e,i),i.catch(()=>Yn.asked.delete(e))),structuredClone(await i)}static forget(){Yn.asked.clear()}static key(t){return`v${Yn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Yn.openCache(),n=Yn.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<Yn.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Yn.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-Yn.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Yn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Ra{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 Ie(t)}static covers(t){return Ie.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>Ra.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Ra.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=Ra.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Ra.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>Ra.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.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:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class pn{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 jn(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"~"^(${pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return pn.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=pn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>ie(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 pn.samples(a)){u++;const y=pn.waysAt(d,v);if(y.length===0)continue;const[x]=y;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&h.set(x.voltageV,(h.get(x.voltageV)??0)+1);for(const M of new Set(y.flatMap(b=>b.services)))l.set(M,(l.get(M)??0)+1)}const f=v=>[...v.entries()].sort((y,x)=>x[1]-y[1])[0]?.[0],p=r.name??f(c),g=r.voltageV??(r.electrification==="none"?void 0:f(h)),m=[...l.entries()].filter(([,v])=>v*4>=u).sort((v,y)=>y[1]-v[1]||v[0].localeCompare(y[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=pn.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=pn.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=pn.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=>ie(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=pn.SAMPLE_M/2;a<n;a+=pn.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(pn.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<=pn.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 Nc{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 jn(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Nc.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=pn.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=pn.voltageOf(r),h=Nc.kindOf(r),l=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Nc.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:Nc.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 uE{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(!Ra.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 Wi{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=Wi.key(t);let i=Wi.asked.get(e)??Wi.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},Wi.asked.set(e,i),n.catch(()=>Wi.asked.delete(e))}return structuredClone(await i.answer)}static forget(){Wi.asked.clear(),Wi.failedAt=-1/0}static key(t){return`v${Wi.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of Wi.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 Wi.openCache(),n=Wi.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<Wi.MAX_AGE_MS)return h;s=h}}}catch{}if(this.now()-Wi.failedAt<Wi.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(Wi.failedAt=this.now(),s)return s;throw a}return i&&Wi.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-Wi.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Wi.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const i0="https://ufoathome.org/railways/index.json";class kc{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??kc.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(`
|
|
2404
|
-
`);let e=kc.shared.get(t);return e||(e=this.fetchFirstAvailable(),kc.shared.set(t,e),e.then(i=>{i.length===0&&kc.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.150.1")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==i0?[e,i0]:[i0]).map(i=>i+t)}}function Gy(){return{elevation:dE(),imagery:Vy(),roads:fE(),water:pE(),railways:mE()}}function dE(){return new aE(new Se,new sE)}function Vy(){return new Hy}function fE(){return new Pc({fallback:new hE(new Ta,new Sa)})}function pE(){return new Lc({fallback:new Yn(new lE(new Rl,new so))})}function mE(){return new kc({fallback:new Wi(new uE(new Ra,new Nc))})}const gE=new Set,Tr="show-observer-map",Rr="hide-milestones",So="minified";class Ne extends HTMLElement{static get observedAttributes(){return["src",Tr,Rr,So]}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 ti;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=Df.create();issues=[];issueCheck=0;sightingAudio=new kS;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>Ne.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=Cy;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");Ne.setIcon(this.moreButton,t?Kt.UNFOLDED:Kt.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)<Ne.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>=ti.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=ti.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ne.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=ti.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>${RS}</style>${TS}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new hh(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 no(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.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===Tr&&this.applyObserverMapDefault(),t===Rr&&this.setMilestonesShown(!this.hasAttribute(Rr)),t===So){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(So)}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(Xy)))};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 ka.recording(t)}get sightingData(){return US(this.currentSighting)}set sightingData(t){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=zS(t),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(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 Ee(async()=>{const{default:r}=await import("./sightingSchema-BuVLd3h2.js");return{default:r}},[],import.meta.url);n=new Us(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],lh.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(vE,{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=lh.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.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("playrequest"))}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"),Ne.setIcon(this.referencesButton,i?Kt.PICTURES_ON:Kt.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)),Ne.setIcon(this.tracesButton,this.tracesShownState?Kt.TRACES_ON:Kt.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?rl(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=Ne.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=Ne.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?jf(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 hh(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=Ne.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?jf(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=Hs.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ne.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ne.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ne.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ne.EXPOSURE_STEP_PX),s=Math.min(Ne.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=nn.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:gE;this.canvasRenderer.setStarPoints(nn.starPointsOf(this.sighting.instrument));const n=(Be(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?fs.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(Sy(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 IS(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*Ne.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"?Kt.PLAY:Kt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ne.icons.get(t)!==e&&(Ne.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},Ne.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(),Ne.setIcon(this.playPauseButton,t?Kt.PAUSE:Kt.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(Tr),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;Ne.setIcon(this.observerMapButton,t?Kt.MAP_ON:Kt.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=Kc.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=ti.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?ti.expand(t,Ne.OBSERVER_MAP_IMAGERY_AHEAD):t,n=ti.IMAGERY_PX*(e?1+2*Ne.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:Vy();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?ti.expand(t,Ne.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=Ne.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=Be(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},Ne.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?jf(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?rl(this.currentSighting.milestones):[]){const a=Be(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?wr.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(nn.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,rl(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,Ne.setIcon(this.milestonesButton,this.milestonesShown?Kt.MILESTONES_ON:Kt.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=Be(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Ys(i,t),{lat:s,lng:r}=es(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=Be(this.currentSighting,this.currentTime),s=wr.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return $e.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=Ne.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)),Ne.setIcon(this.miniMuteButton,this.mutedState?Kt.MUTED:Kt.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){Ne.setIcon(this.muteButton,Kt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Ne.setIcon(this.muteButton,this.mutedState?Kt.MUTED:Kt.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;Ne.setIcon(this.fullscreenButton,t?Kt.EXIT_FULLSCREEN:Kt.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 _s(Ua.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=pg(Ua.preferencesFor(this),mg);if(t===this.messagesLanguage||t==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=t;const e=await GS(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=wy(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Op(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 ca(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?uv(lv(this.realStartMs+i)):ca(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?ca(t):ca(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return ca(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return ca(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?ca(this.currentSighting.timeline.duration):this.canShowClockTime?uv(lv(this.realStartMs+this.realDurationMs)):ca(this.realDurationMs)}}function lv(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function uv(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 ca(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Np="rr0-ufo";function Wy(){customElements.get(Np)||customElements.define(Np,Ne)}const vE="recordingissues",Xy="minifiedreset";/**
|
|
2402
|
+
`);let e=Pc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Pc.shared.set(t,e),e.then(i=>{i.length===0&&Pc.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.150.2")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==t0?[e,t0]:[t0]).map(i=>i+t)}}class Ta{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 Ie(t)}static covers(t){return Ie.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>Ta.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=Ta.BY_NATURE[n]??Ta.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),h=Ta.DIRECTIONS[String(t.properties.sens_de_circulation??"")],l=Ta.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 hE{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(Ta.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Rl{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Ie(t)}static covers(t){return Ie.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>Rl.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=>Rl.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 so{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new jn(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 so.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=so.rings(a("inner"));for(const[h,l]of so.rings(a("outer")).entries()){const u=c.filter(d=>so.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 so.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 lE{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Rl.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const e0="https://ufoathome.org/water/index.json";class Lc{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??Lc.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(`
|
|
2403
|
+
`);let e=Lc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Lc.shared.set(t,e),e.then(i=>{i.length===0&&Lc.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.150.2")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==e0?[e,e0]:[e0]).map(i=>i+t)}}class Yn{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=Yn.key(t);let i=Yn.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Yn.asked.set(e,i),i.catch(()=>Yn.asked.delete(e))),structuredClone(await i)}static forget(){Yn.asked.clear()}static key(t){return`v${Yn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Yn.openCache(),n=Yn.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<Yn.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Yn.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-Yn.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Yn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Ra{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 Ie(t)}static covers(t){return Ie.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>Ra.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Ra.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=Ra.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Ra.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>Ra.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.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:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class pn{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 jn(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"~"^(${pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return pn.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=pn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>ie(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 pn.samples(a)){u++;const y=pn.waysAt(d,v);if(y.length===0)continue;const[x]=y;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&h.set(x.voltageV,(h.get(x.voltageV)??0)+1);for(const M of new Set(y.flatMap(b=>b.services)))l.set(M,(l.get(M)??0)+1)}const f=v=>[...v.entries()].sort((y,x)=>x[1]-y[1])[0]?.[0],p=r.name??f(c),g=r.voltageV??(r.electrification==="none"?void 0:f(h)),m=[...l.entries()].filter(([,v])=>v*4>=u).sort((v,y)=>y[1]-v[1]||v[0].localeCompare(y[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=pn.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=pn.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=pn.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=>ie(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=pn.SAMPLE_M/2;a<n;a+=pn.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(pn.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<=pn.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 Nc{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 jn(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Nc.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=pn.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=pn.voltageOf(r),h=Nc.kindOf(r),l=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Nc.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:Nc.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 uE{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(!Ra.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 Wi{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=Wi.key(t);let i=Wi.asked.get(e)??Wi.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},Wi.asked.set(e,i),n.catch(()=>Wi.asked.delete(e))}return structuredClone(await i.answer)}static forget(){Wi.asked.clear(),Wi.failedAt=-1/0}static key(t){return`v${Wi.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of Wi.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 Wi.openCache(),n=Wi.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<Wi.MAX_AGE_MS)return h;s=h}}}catch{}if(this.now()-Wi.failedAt<Wi.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(Wi.failedAt=this.now(),s)return s;throw a}return i&&Wi.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-Wi.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Wi.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const i0="https://ufoathome.org/railways/index.json";class kc{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??kc.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(`
|
|
2404
|
+
`);let e=kc.shared.get(t);return e||(e=this.fetchFirstAvailable(),kc.shared.set(t,e),e.then(i=>{i.length===0&&kc.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.150.2")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==i0?[e,i0]:[i0]).map(i=>i+t)}}function Gy(){return{elevation:dE(),imagery:Vy(),roads:fE(),water:pE(),railways:mE()}}function dE(){return new aE(new Se,new sE)}function Vy(){return new Hy}function fE(){return new Pc({fallback:new hE(new Ta,new Sa)})}function pE(){return new Lc({fallback:new Yn(new lE(new Rl,new so))})}function mE(){return new kc({fallback:new Wi(new uE(new Ra,new Nc))})}const gE=new Set,Tr="show-observer-map",Rr="hide-milestones",So="minified";class Ne extends HTMLElement{static get observedAttributes(){return["src",Tr,Rr,So]}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 ti;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=Df.create();issues=[];issueCheck=0;sightingAudio=new kS;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>Ne.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=Cy;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");Ne.setIcon(this.moreButton,t?Kt.UNFOLDED:Kt.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)<Ne.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>=ti.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=ti.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ne.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=ti.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>${RS}</style>${TS}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new hh(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 no(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.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===Tr&&this.applyObserverMapDefault(),t===Rr&&this.setMilestonesShown(!this.hasAttribute(Rr)),t===So){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(So)}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(Xy)))};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 ka.recording(t)}get sightingData(){return US(this.currentSighting)}set sightingData(t){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=zS(t),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(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 Ee(async()=>{const{default:r}=await import("./sightingSchema-BuVLd3h2.js");return{default:r}},[],import.meta.url);n=new Us(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],lh.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(vE,{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=lh.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.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("playrequest"))}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"),Ne.setIcon(this.referencesButton,i?Kt.PICTURES_ON:Kt.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)),Ne.setIcon(this.tracesButton,this.tracesShownState?Kt.TRACES_ON:Kt.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?rl(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=Ne.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=Ne.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?jf(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 hh(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=Ne.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?jf(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=Hs.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ne.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ne.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ne.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ne.EXPOSURE_STEP_PX),s=Math.min(Ne.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=nn.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:gE;this.canvasRenderer.setStarPoints(nn.starPointsOf(this.sighting.instrument));const n=(Be(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?fs.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(Sy(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 IS(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*Ne.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"?Kt.PLAY:Kt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ne.icons.get(t)!==e&&(Ne.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},Ne.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(),Ne.setIcon(this.playPauseButton,t?Kt.PAUSE:Kt.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(Tr),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;Ne.setIcon(this.observerMapButton,t?Kt.MAP_ON:Kt.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=Kc.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=ti.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?ti.expand(t,Ne.OBSERVER_MAP_IMAGERY_AHEAD):t,n=ti.IMAGERY_PX*(e?1+2*Ne.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:Vy();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?ti.expand(t,Ne.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=Ne.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=Be(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},Ne.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?jf(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?rl(this.currentSighting.milestones):[]){const a=Be(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?wr.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(nn.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,rl(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,Ne.setIcon(this.milestonesButton,this.milestonesShown?Kt.MILESTONES_ON:Kt.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=Be(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Ys(i,t),{lat:s,lng:r}=es(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=Be(this.currentSighting,this.currentTime),s=wr.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return $e.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=Ne.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)),Ne.setIcon(this.miniMuteButton,this.mutedState?Kt.MUTED:Kt.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){Ne.setIcon(this.muteButton,Kt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Ne.setIcon(this.muteButton,this.mutedState?Kt.MUTED:Kt.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;Ne.setIcon(this.fullscreenButton,t?Kt.EXIT_FULLSCREEN:Kt.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 _s(Ua.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=pg(Ua.preferencesFor(this),mg);if(t===this.messagesLanguage||t==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=t;const e=await GS(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=wy(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Op(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 ca(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?uv(lv(this.realStartMs+i)):ca(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?ca(t):ca(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return ca(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return ca(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?ca(this.currentSighting.timeline.duration):this.canShowClockTime?uv(lv(this.realStartMs+this.realDurationMs)):ca(this.realDurationMs)}}function lv(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function uv(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 ca(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Np="rr0-ufo";function Wy(){customElements.get(Np)||customElements.define(Np,Ne)}const vE="recordingissues",Xy="minifiedreset";/**
|
|
2405
2405
|
* @license
|
|
2406
2406
|
* Copyright 2010-2026 Three.js Authors
|
|
2407
2407
|
* SPDX-License-Identifier: MIT
|
|
@@ -8274,7 +8274,7 @@ ${Ot.OUTPUT_PROJECTION_GLSL}`)}}class wn{constructor(t,e){this.width=t,this.heig
|
|
|
8274
8274
|
// A picture with nothing laid over it may not even have cleared its overlay (see EYE_UNIFORMS).
|
|
8275
8275
|
gl_FragColor = vec4(finish(scene, texture2D(uOverlay, vUv) * uGain * uHasOverlay, lampOf(texel.a)), 1.0);
|
|
8276
8276
|
}
|
|
8277
|
-
`,blending:vs,depthTest:!1,depthWrite:!1}),this.quad=new xt(new Wn(2,2),this.copyMaterial),this.quadScene.add(this.quad)}develop(t,e,i,n=1,s){const r=t.getRenderTarget();this.readable=!0,this.copyMaterial.uniforms.uSource.value=e.scene.texture,this.copyMaterial.uniforms.uGain.value=n,this.draw(t,this.copyMaterial,this.mips);const a=this.ghostMaterial.uniforms;a.uSize.value.set(this.mips.width,this.mips.height);const c=Math.min(i.ghosts.length,Kn.MAX_GHOSTS);a.uCount.value=c;for(let d=0;d<c;d++){const f=i.ghosts[d];a.uScale.value[d]=f.scale||1,a.uShare.value[d]=f.share,a.uBlur.value[d]=f.blur,a.uKind.value[d]=f.cause==="drops"?2:fi.scatters(f)?1:0,a.uOffset.value[d].set(f.offset?.[0]??0,f.offset?.[1]??0),a.uTint.value[d].set(...f.tint??[1,1,1])}a.uBlades.value=i.blades,a.uBladeAngle.value=i.bladeAngleRad,a.uDrops.value=i.drops,a.uImpacts.value=i.impacts;const h=a.uHistory.value;for(let d=0;d<h.length;d++)h[d]=i.history[d]??0;a.uStill.value=i.still?1:0,a.uRunning.value=i.running,a.uBright.value.set(((s?.x??0)+1)/2,((s?.y??0)+1)/2),a.uBrightRadius.value=s?.radius??0;const l=s?.flux??[0,0,0];a.uBrightFlux.value.set(l[0]*n,l[1]*n,l[2]*n),this.draw(t,this.ghostMaterial,this.ghostLayer);const u=this.developMaterial.uniforms;u.uSource.value=e.scene.texture,u.uOverlay.value=e.overlay.texture,u.uGain.value=n,u.uKept.value=1-i.scattered,this.draw(t,this.developMaterial,r)}pickAt(t,e,i,n,s){const r=this.mips.width,a=this.mips.height,c=(d,f)=>({x:Math.round((d+1)/2*r),y:Math.round((f+1)/2*a)}),h=c(e,i),l=this.window(t,h.x,h.y,0);if(!l)return;let u;for(const d of n.ghosts){const f=fi.sourceOf(d,{x:e,y:i});if(Math.abs(f.x)>=1||Math.abs(f.y)>=1)continue;const p=Math.max(2,Math.round(d.blur*a/Math.abs(d.scale))),g=Math.min(1+f.x,1-f.x)/2*r/a,m=Math.min(1+f.y,1-f.y)/2,v=Math.max(2*d.blur*a/Math.abs(d.scale),2)/a,y=Kn.smoothstep(0,v,g)*Kn.smoothstep(0,v,m),x=c(f.x,f.y),M=this.window(t,x.x,x.y,p);if(!M)continue;const b=y*d.share*M.mean/(d.scale*d.scale),S=.18*b*s;S<Kn.VISIBLE_RESPONSE||b<.3*l.mean||(!u||S>u.score)&&(u={score:S,hit:{ghost:d,source:{x:M.brightest.x/r*2-1,y:M.brightest.y/a*2-1}}})}return u?.hit}holdsPictureAt(t,e,i){if(!this.readable)return!1;const n=this.window(t,Math.round((e+1)/2*this.mips.width),Math.round((i+1)/2*this.mips.height),4);return n!==void 0&&n.mean>0}dropAt(t,e,i){const n=Math.round((e+1)/2*this.ghostLayer.width),s=Math.round((i+1)/2*this.ghostLayer.height);if(n<0||s<0||n>=this.ghostLayer.width||s>=this.ghostLayer.height)return 0;const r=new Uint16Array(4);return t.readRenderTargetPixels(this.ghostLayer,n,s,1,1,r),Kn.half(r[3])}window(t,e,i,n){const s=Math.max(1,Math.ceil(n/24)),r={x:Math.max(0,e-n),y:Math.max(0,i-n)},a={x:Math.min(this.mips.width-1,e+n),y:Math.min(this.mips.height-1,i+n)};if(r.x>a.x||r.y>a.y)return;const c=a.x-r.x+1,h=a.y-r.y+1,l=new Uint16Array(c*h*4);t.readRenderTargetPixels(this.mips,r.x,r.y,c,h,l);let u=0,d=0,f=-1,p={x:e,y:i};for(let g=r.y;g<=a.y;g+=s){const m=(g-r.y)*c*4;for(let v=0;v<c;v+=s){const y=.2126*Kn.half(l[m+v*4])+.7152*Kn.half(l[m+v*4+1])+.0722*Kn.half(l[m+v*4+2]);u+=y,d++,y>f&&(f=y,p={x:r.x+v,y:g})}}return{mean:d>0?u/d:0,brightest:p}}draw(t,e,i){this.quad.material=e,t.setRenderTarget(i),t.render(this.quadScene,this.quadCamera)}static half(t){const e=t>>10&31,i=t&1023,n=t&32768?-1:1;return e===0?n*i*2**-24:e===31?0:n*(1+i/1024)*2**(e-15)}static smoothstep(t,e,i){const n=Math.max(0,Math.min(1,(i-t)/(e-t)));return n*n*(3-2*n)}resize(t,e){const i=Math.max(1,t),n=Math.max(1,e);(this.mips.width!==Math.ceil(i/2)||this.mips.height!==Math.ceil(n/2))&&(this.readable=!1),this.frame.scene.setSize(i,n),this.frame.overlay.setSize(i,n),this.mips.setSize(Math.ceil(i/2),Math.ceil(n/2)),this.ghostLayer.setSize(Math.ceil(i/2),Math.ceil(n/2))}dispose(){this.frame.scene.dispose(),this.frame.overlay.dispose(),this.mips.dispose(),this.ghostLayer.dispose(),this.copyMaterial.dispose(),this.ghostMaterial.dispose(),this.developMaterial.dispose(),this.quad.geometry.dispose(),this.quadScene.clear()}}class rs{static IDENTITY=[1,0,0,0,1,0,0,0,1];static NONE={colorMatrix:rs.IDENTITY,contrastGain:1};static combine(t,e){const[i,n,s,r,a,c,h,l,u]=t.colorMatrix,[d,f,p,g,m,v,y,x,M]=e.colorMatrix;return{colorMatrix:[d*i+f*r+p*h,d*n+f*a+p*l,d*s+f*c+p*u,g*i+m*r+v*h,g*n+m*a+v*l,g*s+m*c+v*u,y*i+x*r+M*h,y*n+x*a+M*l,y*s+x*c+M*u],contrastGain:t.contrastGain*e.contrastGain}}static isNone(t){return t.contrastGain===1&&t.colorMatrix.every((e,i)=>e===rs.IDENTITY[i])}}class ze{static MIN_RATIO=1;static STEP=.25;static MIN_SHARE_OF_DISPLAY=.75;static GPU_LATE_MS=12;static GPU_ROOM_MS=6;static INTERVAL_LATE_MS=21;static LOWER_COOLDOWN_MS=750;static RAISE_COOLDOWN_MS=2e3;static PROBE_WATCH_MS=2e3;static PROBE_EVERY_MS=6e3;static PROBE_BACKOFF_MS=3e4;ratio;maxRatio;timer;intervalMs;lastChangeMs=-1/0;nextProbeMs=0;probe;constructor(t,e){this.maxRatio=ze.clamp(t),this.ratio=this.maxRatio,this.timer=e?gf.create(e):void 0}get pixelRatio(){return this.ratio}static SETTLE_MS=400;static SUSTAINED_MS=100;lastEditMs=-1/0;editStreakStartMs=-1/0;wasChanging=!1;noteChange(t){t-this.lastEditMs>ze.SETTLE_MS&&(this.editStreakStartMs=t),this.lastEditMs=t}changing(t){return t-this.lastEditMs<=ze.SETTLE_MS&&this.lastEditMs-this.editStreakStartMs>=ze.SUSTAINED_MS}ratioFor(t,e){return this.changing(t)?this.wasChanging?(this.update(t,e),this.ratio):(this.wasChanging=!0,this.reset(),this.ratio):(this.wasChanging=!1,this.maxRatio)}get timesGpu(){return this.timer!==void 0}set maximum(t){this.maxRatio=ze.clamp(t),this.ratio>this.maxRatio&&(this.ratio=this.maxRatio),this.ratio<this.minimum&&(this.ratio=Math.min(this.maxRatio,this.minimum))}get minimum(){const t=Math.floor(this.maxRatio*ze.MIN_SHARE_OF_DISPLAY/ze.STEP)*ze.STEP;return Math.max(ze.MIN_RATIO,t)}get maximum(){return this.maxRatio}beginDrawing(){this.timer?.begin()}endDrawing(){this.timer?.end()}reset(){this.intervalMs=void 0,this.probe=void 0,this.timer?.reset()}update(t,e){const i=this.timer?.poll();if(!(this.timer&&i===void 0))return i!==void 0?this.followGpu(t,i):this.followIntervals(t,e)}followGpu(t,e){if(e>ze.GPU_LATE_MS)return this.lower(t,ze.LOWER_COOLDOWN_MS);if(e<ze.GPU_ROOM_MS)return this.raise(t,ze.RAISE_COOLDOWN_MS)}followIntervals(t,e){if(!(e>0)||e>1e3)return;this.intervalMs=this.intervalMs===void 0?e:this.intervalMs*.9+e*.1;const i=this.intervalMs>ze.INTERVAL_LATE_MS;if(this.probe){if(i)return this.ratio=this.probe.ratioBefore,this.probe=void 0,this.lastChangeMs=t,this.nextProbeMs=t+ze.PROBE_BACKOFF_MS,this.ratio;t-this.probe.sinceMs>=ze.PROBE_WATCH_MS&&(this.probe=void 0,this.nextProbeMs=t+ze.PROBE_EVERY_MS);return}if(i){const n=this.lower(t,ze.LOWER_COOLDOWN_MS);return n!==void 0&&(this.nextProbeMs=t+ze.PROBE_EVERY_MS),n}if(this.ratio<this.maxRatio&&t>=this.nextProbeMs&&t-this.lastChangeMs>=ze.RAISE_COOLDOWN_MS){const n=this.ratio,s=this.raise(t,0);return s!==void 0&&(this.probe={sinceMs:t,ratioBefore:n}),s}}lower(t,e){if(!(this.ratio<=this.minimum||t-this.lastChangeMs<e))return this.ratio=Math.max(this.minimum,ze.clamp(this.ratio-ze.STEP)),this.lastChangeMs=t,this.ratio}raise(t,e){if(!(this.ratio>=this.maxRatio||t-this.lastChangeMs<e))return this.ratio=Math.min(this.maxRatio,ze.clamp(this.ratio+ze.STEP)),this.lastChangeMs=t,this.ratio}static clamp(t){return Number.isFinite(t)?Math.max(ze.MIN_RATIO,Math.round(t/ze.STEP)*ze.STEP):ze.MIN_RATIO}}class gf{constructor(t,e){this.gl=t,this.extension=e}static IN_FLIGHT_MAX=8;static create(t){if(!(t instanceof WebGL2RenderingContext))return;const e=t.getExtension("EXT_disjoint_timer_query_webgl2");return e?new gf(t,e):void 0}pending=[];active;smoothedMs;begin(){if(!(this.active||this.pending.length>=gf.IN_FLIGHT_MAX))try{const t=this.gl.createQuery();if(!t)return;this.gl.beginQuery(this.extension.TIME_ELAPSED_EXT,t),this.active=t}catch{this.active=void 0}}end(){if(this.active){try{this.gl.endQuery(this.extension.TIME_ELAPSED_EXT),this.pending.push(this.active)}catch{}this.active=void 0}}poll(){const t=this.gl;try{for(let e=0;e<this.pending.length;e++){const i=this.pending[e];if(!t.getQueryParameter(i,t.QUERY_RESULT_AVAILABLE))continue;if(!t.getParameter(this.extension.GPU_DISJOINT_EXT)){const s=t.getQueryParameter(i,t.QUERY_RESULT)/1e6;this.smoothedMs=this.smoothedMs===void 0?s:this.smoothedMs*.8+s*.2}t.deleteQuery(i),this.pending.splice(e,1),e--}}catch{this.pending.length=0}return this.smoothedMs}reset(){this.smoothedMs=void 0}}class de{static ICE_INDEX_RED=1.3067;static ICE_INDEX_BLUE=1.317;static SIDE_PRISM_ANGLE_DEG=60;static END_PRISM_ANGLE_DEG=90;static get PARHELIA_MAX_SUN_ALTITUDE_DEG(){const t=de.ICE_INDEX_RED,e=Math.sqrt((4-t*t)/3);return Math.asin(Math.min(1,e))*180/Math.PI}static minimumDeviationDeg(t,e){const i=t*Math.PI/180,n=e*Math.sin(i/2);return n>1?Number.NaN:(2*Math.asin(n)-i)*180/Math.PI}static effectiveIndex(t,e){const i=e*Math.PI/180,n=Math.cos(i);return n<=0?Number.POSITIVE_INFINITY:Math.sqrt(t*t-Math.sin(i)**2)/n}static parheliaAzimuthDeg(t,e=de.ICE_INDEX_RED){const i=de.minimumDeviationDeg(de.SIDE_PRISM_ANGLE_DEG,de.effectiveIndex(e,t));return Number.isFinite(i)?i:void 0}static parheliaDistanceDeg(t,e=de.ICE_INDEX_RED){const i=de.parheliaAzimuthDeg(t,e);if(i===void 0)return;const n=t*Math.PI/180,s=Math.sin(n)**2,r=Math.cos(n)**2*Math.cos(i*Math.PI/180);return Math.acos(Math.max(-1,Math.min(1,s+r)))*180/Math.PI}static get PLATE_END_FACE_LIMIT_DEG(){const t=de.ICE_INDEX_RED;return Math.asin(Math.min(1,Math.sqrt(t*t-1)))*180/Math.PI}static circumzenithalAltitudeDeg(t,e=de.ICE_INDEX_RED){if(t<0||t>90-de.PLATE_END_FACE_LIMIT_DEG)return;const i=Math.cos(t*Math.PI/180),n=Math.sqrt(e*e-i*i);if(!(n>=1))return Math.asin(n)*180/Math.PI}static DECK_HEIGHT_M=8e3;static deckLitUntilDeg(t){return Math.acos(6371e3/(6371e3+Math.max(0,t)))*180/Math.PI}static halo22(){return de.ringOf("halo22",de.SIDE_PRISM_ANGLE_DEG)}static halo46(){return de.ringOf("halo46",de.END_PRISM_ANGLE_DEG)}static ringOf(t,e){const i=de.minimumDeviationDeg(e,de.ICE_INDEX_RED),n=de.minimumDeviationDeg(e,de.ICE_INDEX_BLUE);return{id:t,angleDeg:(i+n)/2,redAngleDeg:i,blueAngleDeg:n}}static strength(t,e,i=90,n=0){const s=Math.max(0,Math.min(1,t)),r=Math.max(0,1-Math.max(0,Math.min(1,e))),a=i>=0?1:n<=0?0:Math.max(0,1+i/n);return s*r*a}static formsAt(t,e=0){if(t<=-e)return[];const i=[de.halo22(),de.halo46()],n=t>0?de.parheliaDistanceDeg(t):void 0;n!==void 0&&i.push({id:"parhelia",angleDeg:n,redAngleDeg:n,blueAngleDeg:de.parheliaDistanceDeg(t,de.ICE_INDEX_BLUE)}),i.push({id:"tangentArc",angleDeg:de.halo22().angleDeg}),t>0&&i.push({id:"parhelicCircle",angleDeg:t});const s=de.circumzenithalAltitudeDeg(t);return s!==void 0&&i.push({id:"circumzenithal",angleDeg:s}),t>de.PLATE_END_FACE_LIMIT_DEG&&i.push({id:"circumhorizontal"}),t<de.PILLAR_MAX_SOURCE_ALTITUDE_DEG&&i.push({id:"pillar"}),i}static PILLAR_MAX_SOURCE_ALTITUDE_DEG=20}class ls{static get WATER_INDEX_RED(){return hn.indexAt(hn.RED_NM)}static get WATER_INDEX_BLUE(){return hn.indexAt(hn.BLUE_NM)}static radiusDeg(t,e){const i=(e*e-1)/(t*t-1);if(i<0||i>1)return Number.NaN;const n=Math.acos(Math.sqrt(i)),s=Math.asin(Math.sin(n)/e),r=2*(n-s)+(t-1)*(Math.PI-2*s),a=2*Math.PI;let c=r%a;return c<0&&(c+=a),c>Math.PI&&(c=a-c),180-c*180/Math.PI}static primary(){return ls.bowOf("primary",2,0)}static secondary(){return ls.bowOf("secondary",3,0)}static bowOf(t,e,i){const n=ls.radiusDeg(e,ls.WATER_INDEX_RED),s=ls.radiusDeg(e,ls.WATER_INDEX_BLUE),r=(n+s)/2;return{id:t,radiusDeg:r,redRadiusDeg:n,violetRadiusDeg:s,topAltitudeDeg:r-i}}static alexandersBandDeg(){return{fromDeg:ls.primary().redRadiusDeg,toDeg:ls.secondary().redRadiusDeg}}static formsAt(t){return t<0?[]:[ls.bowOf("primary",2,t),ls.bowOf("secondary",3,t)].filter(e=>e.topAltitudeDeg>0)}static FULL_MOON_MAGNITUDE=-12.7;static moonlightShare(t){return Math.min(1,10**(-.4*(t-ls.FULL_MOON_MAGNITUDE)))}static strength(t,e,i){if(i<=0)return 0;const n=Math.max(0,Math.min(1,t)),s=Math.max(0,1-Math.max(0,Math.min(1,e)));return n*s}}class us{constructor(t){this.radius=t;const e=us.SEGMENTS*us.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const i=new se;i.setAttribute("position",new ce(this.positions,3)),i.setAttribute("color",new ce(this.colors,3)),i.setDrawRange(0,0),this.object=new xt(i,is.material()),this.object.frustumCulled=!1,is.track(this.object)}static POINTS=24;static SEGMENTS=us.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(us.ACROSS-1)*6;static HEAD_HALF_WIDTH_DEG=.15;static SPREAD_FRACTION=.05;static FADE_POWER=1.8;object;positions;colors;head;tip;brightness=0;set(t,e,i){this.head=t&&Ke(t.altitudeDeg,t.azimuthDeg,1),this.tip=e&&Ke(e.altitudeDeg,e.azimuthDeg,1),this.brightness=i,this.rebuild()}rebuild(){const t=this.object.geometry,e=this.head,i=this.tip;if(!e||!i||this.brightness<=0){t.setDrawRange(0,0);return}const n=this.angleBetween(e,i);if(n<=0){t.setDrawRange(0,0);return}const s=n*us.SPREAD_FRACTION*Math.PI/180,r=l=>this.scale(this.slerp(e,i,l),this.radius),a=l=>this.radius*(us.HEAD_HALF_WIDTH_DEG*Math.PI/180+s*l),c=l=>this.brightness*(1-l)**us.FADE_POWER;let h=0;for(let l=1;l<us.POINTS;l++){const u=(l-1)/us.SEGMENTS,d=l/us.SEGMENTS;h=this.pushBand(h,r(u),r(d),a(u),a(d),c(u),c(d))}t.setDrawRange(0,h),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}pushBand(t,e,i,n,s,r,a){const c=this.normalise(this.cross(this.normalise(e),this.normalise(this.subtract(i,e))));for(let h=0;h<us.ACROSS-1;h++){const l=h-1,u=h,d=this.across(e,c,n,l),f=this.across(i,c,s,l),p=this.across(e,c,n,u),g=this.across(i,c,s,u),m=(v,y)=>v===0?y:0;t=this.push(t,d,m(l,r)),t=this.push(t,f,m(l,a)),t=this.push(t,p,m(u,r)),t=this.push(t,f,m(l,a)),t=this.push(t,g,m(u,a)),t=this.push(t,p,m(u,r))}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i){const n=t*3;this.positions[n]=e.x,this.positions[n+1]=e.y,this.positions[n+2]=e.z;const s=Pt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.55,this.colors[n+1]=s*.75,this.colors[n+2]=s,t+1}slerp(t,e,i){const n=this.angleBetweenRadians(t,e);if(n<1e-9)return t;const s=Math.sin(n),r=Math.sin((1-i)*n)/s,a=Math.sin(i*n)/s;return{x:t.x*r+e.x*a,y:t.y*r+e.y*a,z:t.z*r+e.z*a}}angleBetween(t,e){return this.angleBetweenRadians(t,e)*180/Math.PI}angleBetweenRadians(t,e){const i=t.x*e.x+t.y*e.y+t.z*e.z;return Math.acos(Math.min(1,Math.max(-1,i)))}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}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}}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}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class MC{object=new Pe;radius;tiers;drawn=[];constructor(t){this.radius=t,this.object.name="satellites",this.tiers=Po.map(e=>{const i=new Qn(new se,Ot.material(e.size));return Ot.track(i),i.frustumCulled=!1,this.object.add(i),i})}set(t,e,i,n){const s=this.tiers.map(()=>[]);this.drawn=[];for(const r of t){if(r.magnitude>e)continue;const a=i(r.position);if(a<=0)continue;const c=r.magnitude-2.5*Math.log10(a);if(c>e)continue;const h=_o(c,e),l=Bf(h),{x:u,y:d,z:f}=Ke(r.position.altitudeDeg,r.position.azimuthDeg,this.radius),[p,g,m]=n(r.position,c);s[l].push({x:u,y:d,z:f,r:p,g,b:m,seed:r.norad*.6180339887%1}),this.drawn.push({satellite:r,direction:new R(u,d,f).normalize()})}this.tiers.forEach((r,a)=>{const c=s[a],h=new Float32Array(c.length*3),l=new Float32Array(c.length*3),u=new Float32Array(c.length);c.forEach((f,p)=>{h.set([f.x,f.y,f.z],p*3),l.set([f.r,f.g,f.b],p*3),u[p]=f.seed}),r.geometry.dispose();const d=new se;d.setAttribute("position",new ce(h,3)),d.setAttribute("color",new ce(l,3)),d.setAttribute("seed",new ce(u,1)),r.geometry=d})}get count(){return this.drawn.length}nearest(t,e){let i,n=e;for(const s of this.drawn){const r=s.direction.dot(t);r>n&&(n=r,i=s.satellite)}return i}dispose(){for(const t of this.tiers)t.geometry.dispose(),t.material.dispose();this.object.removeFromParent(),this.drawn=[]}}class ds{static MU=398600.4418;static OMEGA=72921159e-12;static EARTH_RADIUS_KM=6371;static STEP_S=1;static DENSITY=[[0,1.225],[20,.0889],[40,.004],[60,31e-5],[80,185e-7],[100,56e-8],[120,222e-10],[150,208e-11],[200,254e-12],[250,607e-13],[300,192e-13],[400,28e-13],[500,522e-15],[600,114e-15],[700,307e-16],[800,114e-16],[900,576e-17],[1e3,356e-17]];static FREE_PATH_TIMES_DENSITY=68e-9;static ICE_DENSITY=917;static airDensity(t){const e=ds.DENSITY;if(t<=e[0][0])return e[0][1];let i=0;for(;i<e.length-2&&e[i+1][0]<t;)i++;const[n,s]=e[i],[r,a]=e[i+1];return s*Math.exp(Math.log(a/s)*(t-n)/(r-n))}static dragPerKm(t,e,i,n=.5){const s=ds.airDensity(t),r=ds.FREE_PATH_TIMES_DENSITY/s/1e3,a=Math.exp(-r/e),c=s*1e9*Math.PI*e*e/Math.max(i,1e-9),h=3*s/(4*n*1e-6*ds.ICE_DENSITY)*1e3;return a*c+(1-a)*h}static step(t,e,i,n,s){const[r,a,c,h,l,u]=t,d=Math.hypot(r,a,c),f=ds.OMEGA,p=-398600.4418/(d*d*d),g=p*r+2*f*l+f*f*r,m=p*a-2*f*h+f*f*a,v=p*c,y=Math.hypot(h,l,u),M=1/(1+ds.dragPerKm(d-ds.EARTH_RADIUS_KM,i,n,s)*y*e);t[3]=(h+g*e)*M,t[4]=(l+m*e)*M,t[5]=(u+v*e)*M,t[0]=r+t[3]*e,t[1]=a+t[4]*e,t[2]=c+t[5]*e;const b=Math.hypot(t[0],t[1],t[2]);if(b<ds.EARTH_RADIUS_KM){const S=ds.EARTH_RADIUS_KM/b;t[0]*=S,t[1]*=S,t[2]*=S,t[3]=t[4]=t[5]=0}}}class yC{constructor(t,e,i,n,s=.5){this.massKg=i,this.radiusAt=n,this.particleRadiusUm=s,this.state=Float64Array.of(...t,...e),this.positions=new Float64Array(192),this.positions.set(t,0)}positions;steps=0;state;at(t){const e=ds.STEP_S,i=Math.max(0,t/e),n=Math.ceil(i);for(;this.steps<n;){if(ds.step(this.state,e,this.radiusAt(this.steps*e),this.massKg,this.particleRadiusUm),this.steps++,3*(this.steps+1)>this.positions.length){const c=new Float64Array(this.positions.length*2);c.set(this.positions),this.positions=c}this.positions.set(this.state.subarray(0,3),3*this.steps)}const s=Math.floor(i),r=i-s,a=this.positions;return r===0||s>=this.steps?[a[3*s],a[3*s+1],a[3*s+2]]:[0,1,2].map(c=>a[3*s+c]+(a[3*s+3+c]-a[3*s+c])*r)}}class _e{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=1.5;static FADE_MS=600;static TRAIN_POINTS=8;static leadAt(t,e){const i=t.track;if(i.length<2||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<e;)n++;const s=i[n],r=i[n+1],a=r.t-s.t,c=a>0?(e-s.t)/a:0,[h,l]=_e.alongGreatCircle(s,r,c);return{lat:h,lng:l,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*c)*1e3}}static viewsAt(t,e,i){const n=[];for(const s of t){const r=s.track[0]?.t??0,a=s.track[s.track.length-1]?.t??0;s.fragments.forEach((c,h)=>{const l=c.fromT??r,u=c.untilT??a;if(e<l||e>u)return;const d=(c.lagS??0)*1e3,f=_e.leadAt(s,e-d);if(!f)return;const p=_e.seenFrom(i,f);if(p.altitudeDeg<0)return;const g=Math.min(_e.FADE_MS,(u-l)/4),m=g>0?Math.min(1,(e-l)/g,(u-e)/g):1,v=-2.5*Math.log10(Math.max(m,.001)),y=c.absoluteMagnitude+5*Math.log10(p.distanceKm/_e.STANDARD_DISTANCE_KM)+v,x=[p],M=(c.trainS??_e.DEFAULT_TRAIN_S)*1e3;for(let b=1;b<=_e.TRAIN_POINTS;b++){const S=Math.min(M*b/_e.TRAIN_POINTS,e-l),E=_e.leadAt(s,e-d-S);if(!E||(x.push(_e.seenFrom(i,E)),S>=e-l))break}n.push({reentryId:s.id,fragmentId:c.id??String(h),head:p,magnitude:y,color:c.color??_e.DEFAULT_COLOR,train:x})})}return n}static seenFrom(t,e){const i=_e.ecef(t),n=_e.ecef(e),s=n[0]-i[0],r=n[1]-i[1],a=n[2]-i[2],c=t.lat*_e.DEG,h=t.lng*_e.DEG,l=-Math.sin(h)*s+Math.cos(h)*r,u=-Math.sin(c)*Math.cos(h)*s-Math.sin(c)*Math.sin(h)*r+Math.cos(c)*a,d=Math.cos(c)*Math.cos(h)*s+Math.cos(c)*Math.sin(h)*r+Math.sin(c)*a,f=Math.hypot(l,u,d);return{altitudeDeg:Math.asin(d/f)/_e.DEG,azimuthDeg:(Math.atan2(l,u)/_e.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*_e.DEG,i=t.lng*_e.DEG,n=Math.sin(e),s=_e.A/Math.sqrt(1-_e.E2*n*n);return[(s+t.heightM)*Math.cos(e)*Math.cos(i),(s+t.heightM)*Math.cos(e)*Math.sin(i),(s*(1-_e.E2)+t.heightM)*n]}static alongGreatCircle(t,e,i){const n=l=>{const u=l.lat*_e.DEG,d=l.lng*_e.DEG;return[Math.cos(u)*Math.cos(d),Math.cos(u)*Math.sin(d),Math.sin(u)]},s=n(t),r=n(e),a=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),c=Math.acos(a);let h;if(c<1e-12)h=s;else{const l=Math.sin((1-i)*c)/Math.sin(c),u=Math.sin(i*c)/Math.sin(c);h=[s[0]*l+r[0]*u,s[1]*l+r[1]*u,s[2]*l+r[2]*u]}return[Math.atan2(h[2],Math.hypot(h[0],h[1]))/_e.DEG,Math.atan2(h[1],h[0])/_e.DEG]}}class It{static EARTH_RADIUS_KM=6371;static SHADOW_RADIUS_KM=It.EARTH_RADIUS_KM+15;static PENUMBRA_KM=10;static SUN_ILLUMINANCE_LUX=127e3;static RAYLEIGH_PER_M=[58e-7,135e-7,331e-7];static SCALE_HEIGHT_M=8e3;static OZONE_GRAZING_DEPTH=[2.4,1.8,.24];static ANISOTROPY=.7;static ALBEDO=.99;static WAVELENGTHS_UM=[.61,.55,.465];static ICE_INDEX=1.31;static DEFAULTS={exhaustKgPerS:273,condensedShare:.065,particleRadiusUm:.5,expansionKmPerS:.15,initialRadiusKm:.5,lifetimeS:420,collarShare:.85,collarExpansionKmPerS:2.5,collarLifetimeS:20};static PROPELLANTS={"rp1-lox":{condensedShare:.065,particleRadiusUm:.5},"methane-lox":{condensedShare:.09,particleRadiusUm:.5},"hydrogen-lox":{condensedShare:.13,particleRadiusUm:.5},hypergolic:{condensedShare:.079,particleRadiusUm:.4},solid:{condensedShare:.27,particleRadiusUm:.8}};static G0=9.80665;static COLLAR_SPREAD_OF_EXHAUST_VELOCITY=.735;static plumeOf(t){const e={},i=t.vehicle?.engine;if(i){const n=i.specificImpulseS===void 0?void 0:i.specificImpulseS*It.G0;i.thrustKN!==void 0&&n&&(e.exhaustKgPerS=i.thrustKN*1e3/n),n&&(e.collarExpansionKmPerS=n/1e3*It.COLLAR_SPREAD_OF_EXHAUST_VELOCITY),i.propellant&&Object.assign(e,It.PROPELLANTS[i.propellant])}return{...It.DEFAULTS,...e,...t.plume}}static PUFF_EVERY_S=.5;static SIGMA_OF_RADIUS=.5;static MAX_PUFFS=320;static DEG=Math.PI/180;static EARTH_ROTATION=72921159e-12;static VENT_DEFAULTS={speedKmPerS:.7,massKgPerS:20,condensedShare:.5,particleRadiusUm:.5,expansionKmPerS:.1,initialRadiusKm:.2,lifetimeS:600};static paths=new WeakMap;static exhaustVelocityKmPerS(t){return(t.vehicle?.engine?.specificImpulseS??348)*It.G0/1e3}static releasesOf(t){const e=[],i=t.jets??[];if(i.length===0||t.burnFromT!==void 0||t.burnUntilT!==void 0){const n=t.track[0]?.t??0,s=t.track[t.track.length-1]?.t??0;e.push(It.engineRelease(t,"burn",{fromT:t.burnFromT??n,untilT:t.burnUntilT??s}))}return i.forEach((n,s)=>e.push(It.releaseOf(t,n,s))),e}static releaseOf(t,e,i){const n=`jet:${e.id??i}`;if((e.kind??"burn")==="burn")return It.engineRelease(t,n,e);const s=It.VENT_DEFAULTS;return{key:n,fromT:e.fromT,untilT:e.untilT,angleDeg:e.angleDeg??0,azimuthDeg:e.azimuthDeg??0,spinPeriodS:e.spinPeriodS,speedKmPerS:e.speedKmPerS??s.speedKmPerS,massKgPerS:e.massKgPerS??s.massKgPerS,condensedShare:e.condensedShare??s.condensedShare,particleRadiusUm:e.particleRadiusUm??s.particleRadiusUm,initialRadiusKm:e.initialRadiusKm??s.initialRadiusKm,populations:[{share:1,expansionKmPerS:e.expansionKmPerS??s.expansionKmPerS,lifetimeS:e.lifetimeS??s.lifetimeS}]}}static engineRelease(t,e,i){const n=It.plumeOf(t);return{key:e,fromT:i.fromT,untilT:i.untilT,angleDeg:i.angleDeg??0,azimuthDeg:i.azimuthDeg??0,spinPeriodS:i.spinPeriodS,speedKmPerS:i.speedKmPerS??It.exhaustVelocityKmPerS(t),massKgPerS:i.massKgPerS??n.exhaustKgPerS,condensedShare:i.condensedShare??n.condensedShare,particleRadiusUm:i.particleRadiusUm??n.particleRadiusUm,initialRadiusKm:i.initialRadiusKm??n.initialRadiusKm,populations:[{share:1-n.collarShare,expansionKmPerS:i.expansionKmPerS??n.expansionKmPerS,lifetimeS:i.lifetimeS??n.lifetimeS},{share:n.collarShare,expansionKmPerS:n.collarExpansionKmPerS,lifetimeS:n.collarLifetimeS}]}}static extinctionEfficiency(t,e){const i=2*Math.PI*t/e,n=It.ICE_INDEX**2,s=8/3*i**4*((n-1)/(n+2))**2,r=2*i*(It.ICE_INDEX-1),a=r<.001?r*r/2:2-4/r*Math.sin(r)+4/(r*r)*(1-Math.cos(r));return Math.min(s,a)}static scatteringColour(t){const e=It.extinctionEfficiency(t,It.WAVELENGTHS_UM[1]);return It.WAVELENGTHS_UM.map(i=>It.extinctionEfficiency(t,i)/e)}static sunDirectionAt(t){const e=new ea(0,0,-6378137),i=vh(ut.Sun,t,e,!0,!0),n=(i.ra-tb(t))*15*It.DEG,s=i.dec*It.DEG;return[Math.cos(s)*Math.cos(n),Math.cos(s)*Math.sin(n),Math.sin(s)]}static puffsAt(t,e){const i=[];for(const n of t){let s=It.paths.get(n);s||It.paths.set(n,s=new Map);for(const r of It.releasesOf(n)){const a=Math.min(r.untilT,e);if(a<=r.fromT)continue;const c=Math.max(It.PUFF_EVERY_S*1e3,(r.untilT-r.fromT)/It.MAX_PUFFS),h=[];for(let p=r.fromT;p<a;p+=c)h.push(p);h.push(a);const l=r.massKgPerS*(c/1e3),d=3*It.extinctionEfficiency(r.particleRadiusUm,It.WAVELENGTHS_UM[1])/(4*917*r.particleRadiusUm*1e-6),f=It.scatteringColour(r.particleRadiusUm);r.populations.forEach((p,g)=>{if(p.share<=0)return;const m=y=>r.initialRadiusKm+p.expansionKmPerS*y,v=[];for(const y of h){const x=(e-y)/1e3;if(x>p.lifetimeS)continue;const M=y!==a||a===r.untilT,b=`${r.key}|${g}|${y}`;let S=M?s.get(b):void 0;if(!S){if(S=It.launchPuff(n,r,y,l*p.share,m),!S)continue;M&&s.set(b,S)}v.push({ageS:x,position:S.at(x)})}for(let y=v.length-1;y>=0;y--){const{ageS:x,position:M}=v[y],b=v[y-1]??v[y+1],S=b?Math.hypot(M[0]-b.position[0],M[1]-b.position[1],M[2]-b.position[2]):0,E=m(x)+S/2,w=It.SIGMA_OF_RADIUS*E*1e3,_=l*r.condensedShare*p.share*d/(2*Math.PI*w*w),D=Math.max(0,1-(x/p.lifetimeS)**2);_*D<=0||i.push({launchId:n.id,release:r.key,at:It.geoPoint(M),radiusKm:E,opticalDepth:_*D,colour:f,ageS:x})}})}}return i}static viewsAt(t,e,i,n){const s=[];for(const r of It.puffsAt(t,e)){const a=_e.seenFrom(i,r.at);if(a.altitudeDeg<0)continue;const c=It.sunlightAt(r.at,n);if(c.lit<=0)continue;const h=It.scatteringPhase(i,r.at,n),l=It.SUN_ILLUMINANCE_LUX*It.ALBEDO*h*r.opticalDepth*c.lit;l<=0||s.push({launchId:r.launchId,release:r.release,heightKm:r.at.heightM/1e3,centre:a,radiusDeg:Math.atan2(r.radiusKm,a.distanceKm)/It.DEG,luminanceCdM2:l,sunTransmittance:c.transmittance,colour:r.colour,lit:c.lit,ageS:r.ageS})}return s}static launchPuff(t,e,i,n,s){const r={id:t.id,track:t.track,fragments:[]},a=_e.leadAt(r,i);if(!a)return;const c=t.track[0].t,h=t.track[t.track.length-1].t,l=Math.max(c,i-500),u=Math.min(h,i+500),d=It.earthCentred(a),f=It.earthCentred(_e.leadAt(r,l)),p=It.earthCentred(_e.leadAt(r,u)),g=Math.max(.001,(u-l)/1e3),m=[0,1,2].map(N=>(p[N]-f[N])/g),v=It.EARTH_ROTATION,y=[m[0]-v*d[1],m[1]+v*d[0],m[2]],x=N=>{const P=Math.hypot(N[0],N[1],N[2])||1;return N.map(z=>z/P)},M=x(y),b=x(d),S=b[0]*M[0]+b[1]*M[1]+b[2]*M[2];let E=[b[0]-S*M[0],b[1]-S*M[1],b[2]-S*M[2]];Math.hypot(E[0],E[1],E[2])<1e-6&&(E=[-M[2]*M[0],-M[2]*M[1],1-M[2]*M[2]]),E=x(E);const w=[M[1]*E[2]-M[2]*E[1],M[2]*E[0]-M[0]*E[2],M[0]*E[1]-M[1]*E[0]],_=e.spinPeriodS?360*((i-e.fromT)/1e3)/e.spinPeriodS:0,D=(e.azimuthDeg+_)*It.DEG,I=e.angleDeg*It.DEG,O=[0,1,2].map(N=>-M[N]*Math.cos(I)+Math.sin(I)*(Math.cos(D)*E[N]+Math.sin(D)*w[N])),L=[0,1,2].map(N=>m[N]+e.speedKmPerS*O[N]);return new yC(d,L,n,s,e.particleRadiusUm)}static geoPoint(t){const e=Math.hypot(t[0],t[1],t[2]);return{lat:Math.asin(t[2]/e)/It.DEG,lng:Math.atan2(t[1],t[0])/It.DEG,heightM:(e-ds.EARTH_RADIUS_KM)*1e3}}static sunlightAt(t,e){const i=It.earthCentred(t),n=i[0]*e[0]+i[1]*e[1]+i[2]*e[2];if(n>=0)return{lit:1,transmittance:[1,1,1]};const s=Math.hypot(i[0]-n*e[0],i[1]-n*e[1],i[2]-n*e[2]),r=It.PENUMBRA_KM,a=Math.min(1,Math.max(0,(s-(It.SHADOW_RADIUS_KM-r/2))/r));if(a<=0)return{lit:0,transmittance:[0,0,0]};const c=Math.max(0,(s-It.EARTH_RADIUS_KM)*1e3),h=Math.exp(-c/It.SCALE_HEIGHT_M),l=Math.sqrt(2*Math.PI*It.EARTH_RADIUS_KM*1e3*It.SCALE_HEIGHT_M),u=Math.exp(-(((c/1e3-25)/15)**2)),d=[0,1,2].map(f=>Math.exp(-It.RAYLEIGH_PER_M[f]*h*l-It.OZONE_GRAZING_DEPTH[f]*u));return{lit:a,transmittance:d}}static scatteringPhase(t,e,i){const n=It.earthCentred(t),s=It.earthCentred(e),r=[n[0]-s[0],n[1]-s[1],n[2]-s[2]],a=Math.hypot(r[0],r[1],r[2])||1,c=-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])/a,h=It.ANISOTROPY;return(1-h*h)/(4*Math.PI*(1+h*h-2*h*c)**1.5)}static earthCentred(t){const e=t.lat*It.DEG,i=t.lng*It.DEG,n=It.EARTH_RADIUS_KM+t.heightM/1e3;return[n*Math.cos(e)*Math.cos(i),n*Math.cos(e)*Math.sin(i),n*Math.sin(e)]}}class ai{static RADIUS=840;static MAX_PUFFS=1e3;static RINGS=[0,.25,.5,.75,1,1.25];static COLUMN=ai.RINGS.map(t=>{const e=n=>Math.exp(-((n/It.SIGMA_OF_RADIUS)**2)/2),i=e(ai.RINGS[ai.RINGS.length-1]);return Math.max(0,(e(t)-i)/(1-i))});static SECTORS=12;static VERTICES_PER_PUFF=ai.SECTORS*(3+6*(ai.RINGS.length-2));static BRIGHTEST_RELATIVE=6e4;object=new Pe;mesh;positions=new Float32Array(ai.MAX_PUFFS*ai.VERTICES_PER_PUFF*3);colors=new Float32Array(ai.MAX_PUFFS*ai.VERTICES_PER_PUFF*3);shown=0;drawn=[];static VISIBLE_CONTRAST=.1;constructor(){this.object.name="plumes";const t=new se;t.setAttribute("position",new ce(this.positions,3)),t.setAttribute("color",new ce(this.colors,3)),t.setDrawRange(0,0),this.mesh=new xt(t,is.material()),this.mesh.frustumCulled=!1,is.track(this.mesh),this.object.add(this.mesh)}get count(){return this.shown}set(t,e,i,n){let s=0,r=0;this.drawn=[];for(const c of t){if(r>=ai.MAX_PUFFS)break;const h=n(c.centre);if(h<=0)continue;const l=i(c.centre),u=[0,1,2].map(d=>Math.min(ai.BRIGHTEST_RELATIVE,c.luminanceCdM2*(c.colour?.[d]??1)*e*c.sunTransmittance[d]*l[d]*h));Math.max(...u)<=0||(s=this.pushPuff(s,c,u),this.drawn.push({view:c,direction:this.normalise(Ke(c.centre.altitudeDeg,c.centre.azimuthDeg,1)),radiusRad:c.radiusDeg*Math.PI/180,luminance:.2126*u[0]+.7152*u[1]+.0722*u[2]}),r++)}this.shown=r;const a=this.mesh.geometry;a.setDrawRange(0,s),a.getAttribute("position").needsUpdate=!0,a.getAttribute("color").needsUpdate=!0}pushPuff(t,e,i){const n=Ke(e.centre.altitudeDeg,e.centre.azimuthDeg,ai.RADIUS),s=this.normalise(n),r=this.normalise(this.cross({x:0,y:1,z:0},s)),a=this.cross(s,r),c=ai.RADIUS*Math.tan(e.radiusDeg*Math.PI/180),h=(u,d)=>{const f=d/ai.SECTORS*2*Math.PI,p=ai.RINGS[u]*c,g=Math.cos(f)*p,m=Math.sin(f)*p;return{x:n.x+r.x*g+a.x*m,y:n.y+r.y*g+a.y*m,z:n.z+r.z*g+a.z*m}},l=u=>ai.COLUMN[u];for(let u=0;u<ai.SECTORS;u++){const d=(u+1)%ai.SECTORS;t=this.push(t,n,i,l(0)),t=this.push(t,h(1,u),i,l(1)),t=this.push(t,h(1,d),i,l(1));for(let f=1;f<ai.RINGS.length-1;f++){const p=h(f,u),g=h(f,d),m=h(f+1,u),v=h(f+1,d);t=this.push(t,p,i,l(f)),t=this.push(t,g,i,l(f)),t=this.push(t,m,i,l(f+1)),t=this.push(t,g,i,l(f)),t=this.push(t,v,i,l(f+1)),t=this.push(t,m,i,l(f+1))}}return t}pickAt(t,e,i=0){const n=this.normalise(t);let s=0,r;for(const a of this.drawn){const c=Math.max(-1,Math.min(1,n.x*a.direction.x+n.y*a.direction.y+n.z*a.direction.z)),h=Math.max(0,Math.acos(c)-e)/Math.max(a.radiusRad,1e-9),l=a.luminance*ai.profile(h);l<=0||(s+=l,(!r||l>r.light)&&(r={view:a.view,light:l}))}return r&&s>=ai.VISIBLE_CONTRAST*i?r.view:void 0}static profile(t){const e=ai.RINGS;if(t>=e[e.length-1])return 0;let i=0;for(;t>e[i+1];)i++;const n=(t-e[i])/(e[i+1]-e[i]);return ai.COLUMN[i]+(ai.COLUMN[i+1]-ai.COLUMN[i])*n}push(t,e,i,n){const s=t*3;return this.positions[s]=e.x,this.positions[s+1]=e.y,this.positions[s+2]=e.z,this.colors[s]=i[0]*n,this.colors[s+1]=i[1]*n,this.colors[s+2]=i[2]*n,t+1}cross(t,e){return this.normalise({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})}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}}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose(),this.object.removeFromParent()}}class qn{static RADIUS=840;static MAX_SEGMENTS=256;static VERTICES_PER_SEGMENT=12;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;static TRAIN_SHARE=.6;object=new Pe;tiers;trains;positions;colors;shown=0;constructor(){this.object.name="reentries",this.tiers=Po.map(i=>{const n=new Qn(new se,Ot.material(i.size,!1));return Ot.track(n),n.frustumCulled=!1,this.object.add(n),n});const t=qn.MAX_SEGMENTS*qn.VERTICES_PER_SEGMENT;this.positions=new Float32Array(t*3),this.colors=new Float32Array(t*3);const e=new se;e.setAttribute("position",new ce(this.positions,3)),e.setAttribute("color",new ce(this.colors,3)),e.setDrawRange(0,0),this.trains=new xt(e,is.material()),this.trains.frustumCulled=!1,is.track(this.trains),this.object.add(this.trains)}get count(){return this.shown}set(t,e,i,n){const s=this.tiers.map(()=>[]);let r=0,a=0;const c=new st;for(const l of t){const u=i(l.head);if(u<=0)continue;const d=l.magnitude-2.5*Math.log10(u);if(d>e)continue;a++,c.set(l.color);const f=_o(d,e),{x:p,y:g,z:m}=Ke(l.head.altitudeDeg,l.head.azimuthDeg,qn.RADIUS),[v,y,x]=n(l.head,d),M=Math.max(c.r,c.g,c.b)||1;s[Bf(f)].push({x:p,y:g,z:m,r:v*c.r/M,g:y*c.g/M,b:x*c.b/M}),r=this.pushTrain(r,l.train,f,c)}this.shown=a,this.tiers.forEach((l,u)=>{const d=s[u],f=new Float32Array(d.length*3),p=new Float32Array(d.length*3);d.forEach((m,v)=>{f.set([m.x,m.y,m.z],v*3),p.set([m.r,m.g,m.b],v*3)}),l.geometry.dispose();const g=new se;g.setAttribute("position",new ce(f,3)),g.setAttribute("color",new ce(p,3)),l.geometry=g});const h=this.trains.geometry;h.setDrawRange(0,r),h.getAttribute("position").needsUpdate=!0,h.getAttribute("color").needsUpdate=!0}pushTrain(t,e,i,n){const s=e.length-1;for(let r=0;r<s;r++){if(t+qn.VERTICES_PER_SEGMENT>qn.MAX_SEGMENTS*qn.VERTICES_PER_SEGMENT)return t;const a=1-r/s,c=1-(r+1)/s,h=Ke(e[r].altitudeDeg,e[r].azimuthDeg,qn.RADIUS),l=Ke(e[r+1].altitudeDeg,e[r+1].azimuthDeg,qn.RADIUS),u=f=>qn.RADIUS*((qn.MIN_HALF_WIDTH_DEG+qn.BRIGHT_HALF_WIDTH_DEG*i*f)*Math.PI/180),d=f=>qn.TRAIN_SHARE*i*f**1.6;t=this.pushRibbon(t,h,l,u(a),u(c),d(a),d(c),n)}return t}pushRibbon(t,e,i,n,s,r,a,c){const h={x:i.x-e.x,y:i.y-e.y,z:i.z-e.z};if(Math.hypot(h.x,h.y,h.z)<1e-9)return t;const l=this.normalise(this.cross(this.normalise(e),this.normalise(h)));for(const[u,d]of[[-1,0],[0,1]]){const f=this.across(e,l,n,u),p=this.across(i,l,s,u),g=this.across(e,l,n,d),m=this.across(i,l,s,d),v=(y,x)=>y===0?x:0;t=this.push(t,f,v(u,r),c),t=this.push(t,p,v(u,a),c),t=this.push(t,g,v(d,r),c),t=this.push(t,p,v(u,a),c),t=this.push(t,m,v(d,a),c),t=this.push(t,g,v(d,r),c)}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i,n){const s=t*3;this.positions[s]=e.x,this.positions[s+1]=e.y,this.positions[s+2]=e.z;const r=Pt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[s]=r*n.r,this.colors[s+1]=r*n.g,this.colors[s+2]=r*n.b,t+1}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}}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}}dispose(){for(const t of this.tiers)t.geometry.dispose(),t.material.dispose();this.trains.geometry.dispose(),this.trains.material.dispose(),this.object.removeFromParent()}}class Yf{constructor(t){this.state=t}next(){this.state=this.state+1831565813|0;let t=this.state;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}between(t,e){return t+this.next()*(e-t)}}class Ws{static MIN_DURATION_MS=250;static MAX_DURATION_MS=1400;static schedule(t){const{ratePerHour:e,durationMs:i,velocityKmS:n,seed:s}=t;if(e<=0||i<=0)return[];const r=e*i/36e5,a=new Yf(s),c=Math.floor(r),h=c+(a.next()<r-c?1:0),l=[];for(let u=0;u<h;u++){const d=Math.min(1,Math.max(0,(n-20)/52)),f=Ws.MAX_DURATION_MS-d*(Ws.MAX_DURATION_MS-Ws.MIN_DURATION_MS),p=a.between(5,70);l.push({t:a.between(0,i),durationMs:f*a.between(.7,1.3),fromRadiantDeg:p,bearingDeg:a.between(0,360),lengthDeg:Math.sin(p*Math.PI/180)*a.between(8,40)*(.6+d),brightness:a.next()**3}),l.sort((g,m)=>g.t-m.t)}return l}static FAINTEST_MAGNITUDE=6.5;static BRIGHTEST_MAGNITUDE=-4;static magnitudeOf(t){return Ws.FAINTEST_MAGNITUDE-(Ws.FAINTEST_MAGNITUDE-Ws.BRIGHTEST_MAGNITUDE)*t.brightness}static aliveAt(t,e){return t.filter(i=>e>=i.t&&e<=i.t+i.durationMs).map(i=>({meteor:i,progress:(e-i.t)/i.durationMs}))}}class _a{object=new Pe;radius;core;glow;flashKey;static CORE_WIDTH_DEG=.06;static GLOW_WIDTH_DEG=.5;static SEGMENTS=28;static CORE_RELATIVE=1e3;constructor(t){this.radius=t,this.object.name="lightning-bolt",this.core=new ss({color:15659775,transparent:!0,opacity:0,blending:sn,depthWrite:!1,fog:!1}),this.glow=new ss({color:10466559,transparent:!0,opacity:0,blending:sn,depthWrite:!1,fog:!1}),this.object.visible=!1,this.object.renderOrder=5.95}set(t,e,i){if(!t||!t.cloudToGround||e<=.01){this.object.visible=!1;return}const n=`${t.channelSeed}:${Math.round(i)}`;n!==this.flashKey&&this.build(t,i,n),this.core.color.setHex(15659775).multiplyScalar(_a.CORE_RELATIVE*Math.min(1,e*1.4)),this.glow.color.setHex(10466559).multiplyScalar(.1*_a.CORE_RELATIVE*e*.35),this.core.opacity=1,this.glow.opacity=1,this.object.visible=!0}build(t,e,i){this.flashKey=i;for(const h of[...this.object.children])h.geometry.dispose(),this.object.remove(h);const n=new Yf(t.channelSeed),s=Math.atan2(e,t.distanceM)*180/Math.PI,r=this.channel(n,t.azimuthDeg,s,0,1),a=[r],c=1+Math.floor(n.next()*2);for(let h=0;h<c;h++){const l=r[Math.floor(n.between(.15,.5)*r.length)];a.push(this.channel(n,l.azimuthDeg,l.altitudeDeg,l.altitudeDeg*n.between(.3,.7),.5))}for(const h of a)this.object.add(new xt(this.ribbon(h,_a.GLOW_WIDTH_DEG),this.glow)),this.object.add(new xt(this.ribbon(h,_a.CORE_WIDTH_DEG),this.core))}channel(t,e,i,n,s){const r=[],a=i-n;let c=e;for(let h=0;h<=_a.SEGMENTS;h++){const l=i-a*h/_a.SEGMENTS;r.push({azimuthDeg:c,altitudeDeg:l}),c+=t.between(-1,1)*a*.06*s}return r}ribbon(t,e){const i=new Float32Array(t.length*2*3),n=[],s=this.radius*Math.tan(e*Math.PI/180)/2,r=t.map(c=>{const{x:h,y:l,z:u}=Ke(c.altitudeDeg,c.azimuthDeg,this.radius);return new R(h,l,u)});r.forEach((c,h)=>{const l=r[Math.min(h+1,r.length-1)],u=r[Math.max(h-1,0)],f=l.clone().sub(u).normalize().cross(c.clone().normalize()).normalize().multiplyScalar(s);if(i.set([c.x+f.x,c.y+f.y,c.z+f.z],h*6),i.set([c.x-f.x,c.y-f.y,c.z-f.z],h*6+3),h<r.length-1){const p=h*2;n.push(p,p+1,p+2,p+1,p+3,p+2)}});const a=new se;return a.setAttribute("position",new ce(i,3)),a.setIndex(n),a}dispose(){for(const t of this.object.children)t.geometry.dispose();this.core.dispose(),this.glow.dispose(),this.object.removeFromParent()}}class Qi{static MIN_INTERVAL_S=8;static MAX_INTERVAL_S=25;static SEVERE_MIN_INTERVAL_S=2;static SEVERE_MAX_INTERVAL_S=8;static CLOUD_TO_GROUND_FRACTION=.25;static MIN_DISTANCE_M=1e3;static MAX_DISTANCE_M=15e3;static INTERSTROKE_MS=60;static STROKE_DECAY_MS=40;static SOUND_SPEED_M_S=343;static schedule(t){const e=new Yf(t.seed),i=[],{minS:n,maxS:s}=Qi.intervalFor(t.intensity??.5);let r=e.between(0,s)*1e3;for(;r<t.durationMs;){const a=e.next()<Qi.CLOUD_TO_GROUND_FRACTION,c=Qi.MIN_DISTANCE_M,h=Qi.MAX_DISTANCE_M,l=Math.sqrt(e.between(c*c,h*h)),u=a?1+Math.floor(e.next()*4):1,d=[];let f=0;for(let p=0;p<u;p++)d.push({offsetMs:f,intensity:p===0?1:e.between(.4,.9)}),f+=Qi.INTERSTROKE_MS*e.between(.5,1.6);i.push({t:r,azimuthDeg:e.between(0,360),distanceM:l,cloudToGround:a,strokes:d,channelSeed:Math.floor(e.next()*2**31)}),r+=e.between(n,s)*1e3}return i}static intervalFor(t){const e=Math.min(1,Math.max(0,(t-.5)/.5));return{minS:Qi.MIN_INTERVAL_S-e*(Qi.MIN_INTERVAL_S-Qi.SEVERE_MIN_INTERVAL_S),maxS:Qi.MAX_INTERVAL_S-e*(Qi.MAX_INTERVAL_S-Qi.SEVERE_MAX_INTERVAL_S)}}static brightnessAt(t,e){let i=0;for(const n of t.strokes){const s=e-t.t-n.offsetMs;s<0||s>Qi.STROKE_DECAY_MS*6||(i+=n.intensity*Math.exp(-s/Qi.STROKE_DECAY_MS))}return Math.min(1,i)}static endOf(t){const e=t.strokes[t.strokes.length-1];return t.t+e.offsetMs+Qi.STROKE_DECAY_MS*6}static thunderDelayMs(t){return t.distanceM/Qi.SOUND_SPEED_M_S*1e3}}class Hc{static ODD_RADIUS_WEDGES_DEG=[28,56,80];static STANDS_OUT=1.5;static NEIGHBOURHOOD_DEG=2.5;static oddRadiiDeg(){const t=(de.ICE_INDEX_RED+de.ICE_INDEX_BLUE)/2;return Hc.ODD_RADIUS_WEDGES_DEG.map(e=>de.minimumDeviationDeg(e,t)).filter(e=>Number.isFinite(e))}static at(t,e,i,n){const s=Math.PI/180,r=t,a=Math.abs(i),c=Math.sin(r*s)*Math.sin(e*s)+Math.cos(r*s)*Math.cos(e*s)*Math.cos(a*s),h=Math.acos(Math.max(-1,Math.min(1,c)))/s,l=Math.atan2(Math.sin(a*s)*Math.cos(e*s),Math.cos(r*s)*Math.sin(e*s)-Math.sin(r*s)*Math.cos(e*s)*Math.cos(a*s))/s,u=Math.abs(e-r),d=()=>{const y=n(e,a);if(!(y>0))return!1;const x=Hc.NEIGHBOURHOOD_DEG,M=1/Math.max(.2,Math.cos(e*s)),b=[n(e+x,a),n(e-x,a),n(e,a+x*M),n(e,Math.max(0,a-x*M))].sort((S,E)=>S-E);return y>b[1]*Hc.STANDS_OUT},f=()=>{const y=x=>{const M=h*s,b=x*s,S=Math.cos(M)*Math.cos(r*s)-Math.sin(M)*Math.cos(b)*Math.sin(r*s),E=Math.sin(M)*Math.sin(b),w=Math.cos(M)*Math.sin(r*s)+Math.sin(M)*Math.cos(b)*Math.cos(r*s);return n(Math.asin(Math.max(-1,Math.min(1,w)))/s,Math.abs(Math.atan2(E,S)/s))};return(y(70)+y(110)+y(250)+y(290))/4},p=(y,x=0)=>{if(d())return x>0&&!(n(e,a)>f()*x)?void 0:y};if(r>0&&r<de.PARHELIA_MAX_SUN_ALTITUDE_DEG&&u<2.5){const y=de.parheliaAzimuthDeg(r);if(y!==void 0&&a>=y-1.2&&a<=y+7){const x=p({id:"parhelion",angleDeg:de.parheliaDistanceDeg(r)},2.5);if(x)return x}}if(r>0&&u<2.5&&Math.abs(a-120)<4){const y=p({id:"parhelion120",angleDeg:120},0);if(y)return y}const g=de.circumzenithalAltitudeDeg(r);if(g!==void 0&&e>g-2&&e<g+4){const y=p({id:"circumzenithal",angleDeg:g});if(y)return y}if(r>de.PLATE_END_FACE_LIMIT_DEG){const y=de.circumzenithalAltitudeDeg(90-r);if(y!==void 0){const x=90-y;if(e>x-4&&e<x+2){const M=p({id:"circumhorizontal",angleDeg:x});if(M)return M}}}if(a<3&&r>0){if(e>r+3&&e<r+25&&r<de.PILLAR_MAX_SOURCE_ALTITUDE_DEG){const y=p({id:"pillar"});if(y)return y}if(Math.abs(e+r)<3){const y=p({id:"subsun"});if(y)return y}}const m=de.halo22();if(h>m.redAngleDeg-.6&&h<m.blueAngleDeg+2.5){const y=Math.abs(l)<50,x=Math.abs(l)>130;if(y||x){const M=p({id:y?"upperTangentArc":"lowerTangentArc",angleDeg:m.angleDeg},1.5);if(M)return M}}for(const y of Hc.oddRadiiDeg())if(h>y-.6&&h<y+1.8){const x=p({id:"oddRadius",angleDeg:y});if(x)return x}if(h>m.redAngleDeg-.6&&h<m.blueAngleDeg+2.5){const y=p({id:"halo22",angleDeg:m.angleDeg});if(y)return y}const v=de.halo46();if(h>v.redAngleDeg-.6&&h<v.blueAngleDeg+3){const y=p({id:"halo46",angleDeg:v.angleDeg});if(y)return y}if(r>0&&u<1.2){const y=n(e,a),x=Math.max(n(e+3,a),n(e-3,a));if(y>0&&y>x*2)return{id:"parhelicCircle",angleDeg:r}}}}class Zn{static RED_NM=656.3;static BLUE_NM=435.8;static ANCHOR_RED=1.3067;static ANCHOR_BLUE=1.317;static B=(Zn.ANCHOR_BLUE-Zn.ANCHOR_RED)/(1/(Zn.BLUE_NM*Zn.BLUE_NM)-1/(Zn.RED_NM*Zn.RED_NM));static A=Zn.ANCHOR_RED-Zn.B/(Zn.RED_NM*Zn.RED_NM);static indexAt(t){return Zn.A+Zn.B/(t*t)}}class fr{static MAX_FACES=20;normals=new Float64Array(fr.MAX_FACES*3);offsets=new Float64Array(fr.MAX_FACES);faceCount=8;radius=1;set(t,e,i,n,s,r,a=0){let c=0,h=0,l=0;Math.abs(i)<.9?(c=-e,h=t,l=0):(c=0,h=-i,l=e);const u=Math.hypot(c,h,l)||1;c/=u,h/=u,l/=u;const d=e*l-i*h,f=i*c-t*l,p=t*h-e*c,g=s/2,m=r/2;for(let v=0;v<6;v++){const y=n+v*Math.PI/3,x=Math.cos(y),M=Math.sin(y);this.normals[v*3]=c*x+d*M,this.normals[v*3+1]=h*x+f*M,this.normals[v*3+2]=l*x+p*M,this.offsets[v]=g}if(this.normals[18]=t,this.normals[19]=e,this.normals[20]=i,this.offsets[6]=m,this.normals[21]=-t,this.normals[22]=-e,this.normals[23]=-i,this.offsets[7]=m,this.faceCount=8,a>0){const v=fr.PYRAMID_TILT,y=Math.cos(v),x=Math.sin(v),M=Math.min(m,a*g*Math.tan(v)),b=m-M,S=y*b+x*g;for(let E=0;E<6;E++){const w=E*3,_=(8+E)*3,D=(14+E)*3;this.normals[_]=y*t+x*this.normals[w],this.normals[_+1]=y*e+x*this.normals[w+1],this.normals[_+2]=y*i+x*this.normals[w+2],this.normals[D]=-y*t+x*this.normals[w],this.normals[D+1]=-y*e+x*this.normals[w+1],this.normals[D+2]=-y*i+x*this.normals[w+2],this.offsets[8+E]=S,this.offsets[14+E]=S}this.faceCount=fr.MAX_FACES}this.radius=Math.hypot(g*2/Math.sqrt(3),m)}static rollToward(t,e,i,n,s,r){let a,c,h;Math.abs(i)<.9?(a=-e,c=t,h=0):(a=0,c=-i,h=e);const l=Math.hypot(a,c,h)||1;a/=l,c/=l,h/=l;const u=e*h-i*c,d=i*a-t*h,f=t*c-e*a;return Math.atan2(n*u+s*d+r*f,n*a+s*c+r*h)}get aimRadius(){return this.radius}trace(t,e,i,n,s,r,a){let c=-e,h=t,l=0,u=Math.hypot(c,h,l);u<1e-6&&(c=1,h=0,l=0,u=1),c/=u,h/=u,l/=u;const d=e*l-i*h,f=i*c-t*l,p=t*h-e*c,g=c*n+d*s-t*this.radius*2,m=h*n+f*s-e*this.radius*2,v=l*n+p*s-i*this.radius*2;let y=-1,x=-1/0,M=1/0;for(let q=0;q<this.faceCount;q++){const et=this.normals[q*3],at=this.normals[q*3+1],$t=this.normals[q*3+2],fe=et*t+at*e+$t*i,Gt=this.offsets[q]-(et*g+at*m+$t*v);if(fe>1e-9){const K=Gt/fe;K<M&&(M=K)}else if(fe<-1e-9){const K=Gt/fe;K>x&&(x=K,y=q)}else if(Gt<0)return 0}if(y<0||x>=M)return 0;let b=0;const S=this.normals[y*3],E=this.normals[y*3+1],w=this.normals[y*3+2],_=-(S*t+E*e+w*i),D=cf.reflectance(_,1,r);a[b].x=t+2*_*S,a[b].y=e+2*_*E,a[b].z=i+2*_*w,a[b].weight=D,b++;const I=1/r,O=Math.sqrt(Math.max(0,1-I*I*(1-_*_)));let L=I*t+(I*_-O)*S,N=I*e+(I*_-O)*E,P=I*i+(I*_-O)*w,z=g+t*x,B=m+e*x,X=v+i*x,J=1-D;for(let q=0;q<fr.MAX_BOUNCES&&J>fr.MIN_WEIGHT;q++){let et=-1,at=1/0;for(let G=0;G<this.faceCount;G++){const kt=this.normals[G*3],Vt=this.normals[G*3+1],Ft=this.normals[G*3+2],Tt=kt*L+Vt*N+Ft*P;if(Tt<=1e-9)continue;const qt=(this.offsets[G]-(kt*z+Vt*B+Ft*X))/Tt;qt>1e-9&&qt<at&&(at=qt,et=G)}if(et<0)break;const $t=this.normals[et*3],fe=this.normals[et*3+1],Gt=this.normals[et*3+2],K=$t*L+fe*N+Gt*P,ot=r*Math.sqrt(Math.max(0,1-K*K));if(z+=L*at,B+=N*at,X+=P*at,ot<1){const G=Math.sqrt(Math.max(0,1-ot*ot)),kt=cf.reflectance(K,r,1);if(a[b].x=r*L-(r*K-G)*$t,a[b].y=r*N-(r*K-G)*fe,a[b].z=r*P-(r*K-G)*Gt,a[b].weight=J*(1-kt),b++,b>=a.length)return b;J*=kt}const rt=2*K;L-=rt*$t,N-=rt*fe,P-=rt*Gt}return b}static MAX_BOUNCES=6;static PYRAMID_TILT=62*Math.PI/180;static MIN_WEIGHT=1e-4}class ke{static AZIMUTH_BINS=512;static ALTITUDE_BINS=512;static DEFAULT_POPULATIONS=[{orientation:"tumbling",widthMicrons:50,lengthMicrons:50,share:.48},{orientation:"plate",widthMicrons:100,lengthMicrons:15,share:.27},{orientation:"column",widthMicrons:40,lengthMicrons:120,share:.18},{orientation:"parry",widthMicrons:40,lengthMicrons:120,share:.02},{orientation:"pyramidal",widthMicrons:40,lengthMicrons:120,share:.03,capFraction:.5},{orientation:"lowitz",widthMicrons:100,lengthMicrons:15,share:.02}];static DEFAULT_RARE_SHARE=Qb;static populationsFor(t){const e=Math.min(.9,Math.max(0,t));if(Math.abs(e-ke.DEFAULT_RARE_SHARE)<1e-9)return ke.DEFAULT_POPULATIONS;const i=(1-e)/(1-ke.DEFAULT_RARE_SHARE);return ke.DEFAULT_POPULATIONS.map(n=>n.orientation==="pyramidal"||n.orientation==="lowitz"?{...n,share:n.share/ke.DEFAULT_RARE_SHARE*e}:{...n,share:n.share*i})}populations=ke.DEFAULT_POPULATIONS;populationTotal=1;static WORST_TILT_DEG=180;static BEST_TILT_DEG=.5;static SOURCE_RADIUS_DEG=.265;static UNDEVIATED_DEG=.6;crystal=new fr;emergent=Array.from({length:fr.MAX_BOUNCES+2},()=>({x:0,y:0,z:0,weight:0}));tally=new Float32Array(ke.AZIMUTH_BINS*ke.ALTITUDE_BINS*3);radiance=new Float32Array(ke.AZIMUTH_BINS*ke.ALTITUDE_BINS*3);scratch=new Float32Array(ke.AZIMUTH_BINS*ke.ALTITUDE_BINS*3);seed=1;spare=0;hasSpare=!1;altitude=0;tilt=0;alignment=0;traced=0;begin(t,e,i=2654435769,n=ke.DEFAULT_POPULATIONS){this.populations=n,this.populationTotal=n.reduce((r,a)=>r+a.share,0)||1,this.seed=i>>>0||1,this.hasSpare=!1,this.tally.fill(0),this.traced=0,this.altitude=t*Math.PI/180,this.alignment=Math.min(1,Math.max(0,e));const s=ke.WORST_TILT_DEG*(ke.BEST_TILT_DEG/ke.WORST_TILT_DEG)**this.alignment;this.tilt=s*Math.PI/180}trace(t){const e=ke.AZIMUTH_BINS,i=ke.ALTITUDE_BINS,n=this.tally,s=ke.SOURCE_RADIUS_DEG*Math.PI/180,r=Math.cos(ke.UNDEVIATED_DEG*Math.PI/180),a=this.altitude;for(let c=0;c<t;c++){const h=this.pickPopulation();this.orient(h,this.tilt);const l=this.random()*2*Math.PI,u=s*Math.sqrt(this.random()),d=a+u*Math.sin(l),f=u*Math.cos(l)/Math.max(.05,Math.cos(a)),p=-Math.cos(d)*Math.cos(f),g=-Math.cos(d)*Math.sin(f),m=-Math.sin(d),v=this.crystal.aimRadius,y=(this.random()*2-1)*v,x=(this.random()*2-1)*v,M=4*v*v,b=en.SAMPLES[this.random()*en.SAMPLES.length|0],S=this.crystal.trace(p,g,m,y,x,Zn.indexAt(b.wavelengthNm),this.emergent);for(let E=0;E<S;E++){const w=this.emergent[E],_=Math.hypot(w.x,w.y,w.z);if(_<1e-9||w.weight<=0)continue;const D=w.x/_,I=w.y/_,O=w.z/_;if(D*p+I*g+O*m>r)continue;const L=Math.asin(Math.max(-1,Math.min(1,-O))),N=Math.abs(Math.atan2(-I,-D)),P=Math.min(e-1,N/Math.PI*e|0),B=(Math.min(i-1,(L+Math.PI/2)/Math.PI*i|0)*e+P)*3,X=w.weight*M*en.SAMPLES.length;n[B]+=X*b.r,n[B+1]+=X*b.g,n[B+2]+=X*b.b}}this.traced+=t}get tracedRays(){return this.traced}harvest(){const t=ke.AZIMUTH_BINS,e=ke.ALTITUDE_BINS;return this.toRadiance(t,e),this.smooth(t,e),{width:t,height:e,data:this.radiance,sourceAltitudeDeg:this.altitude*180/Math.PI,alignment:this.alignment,rays:this.traced}}compute(t,e,i,n,s){return this.begin(t,e,n,s),this.trace(i),this.harvest()}toRadiance(t,e){const i=2*Math.PI/t,n=Math.max(1,this.traced),s=4*ke.REFERENCE_MICRONS*ke.REFERENCE_MICRONS;for(let r=0;r<e;r++){const a=Math.sin(r/e*Math.PI-Math.PI/2),c=Math.sin((r+1)/e*Math.PI-Math.PI/2),h=1/(i*(c-a)*n*s);for(let l=0;l<t;l++){const u=(r*t+l)*3;this.radiance[u]=this.tally[u]*h,this.radiance[u+1]=this.tally[u+1]*h,this.radiance[u+2]=this.tally[u+2]*h}}}static REFERENCE_MICRONS=50;smooth(t,e){const i=this.scratch,n=this.radiance;i.set(n);for(let r=0;r<e;r++){const a=r*t*3;for(let c=0;c<3;c++){let h=i[a+c];for(let l=0;l<t;l++){const u=a+l*3+c,d=l+1<t?i[u+3]:i[u];n[u]=(h+2*i[u]+d)/4,h=i[u]}}}i.set(n);const s=t*3;for(let r=0;r<e;r++){const a=r>0?-s:0,c=r+1<e?s:0,h=r*s;for(let l=h;l<h+s;l++)n[l]=(i[l+a]+2*i[l]+i[l+c])/4}}pickPopulation(){const t=this.random()*this.populationTotal;let e=0;for(const i of this.populations)if(e+=i.share,t<=e)return i;return this.populations[this.populations.length-1]}orient(t,e){const i=this.random()*2*Math.PI;let n=this.random()*2*Math.PI,s=0,r=0,a=1;switch(t.orientation){case"pyramidal":case"tumbling":{a=this.random()*2-1;const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"plate":{a=this.spreadAboutAnAxis(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"column":case"parry":{a=this.spreadAboutAPlane(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i),t.orientation==="parry"&&(n=Math.PI/2+this.gaussian()*e);break}}if(t.orientation==="lowitz"){const c=this.spreadAboutAPlane(e),h=Math.sqrt(Math.max(0,1-c*c)),l=h*Math.cos(i),u=h*Math.sin(i),d=c;let f=-d*l,p=-d*u,g=1-d*d;const m=Math.hypot(f,p,g)||1;f/=m,p/=m,g/=m;const v=u*g-d*p,y=d*f-l*g,x=l*p-u*f,M=this.random()*2*Math.PI;s=f*Math.cos(M)+v*Math.sin(M),r=p*Math.cos(M)+y*Math.sin(M),a=g*Math.cos(M)+x*Math.sin(M),n=fr.rollToward(s,r,a,l,u,d)+Math.PI/6}this.crystal.set(s,r,a,n,t.widthMicrons,t.lengthMicrons,t.capFraction??0)}random(){this.seed=this.seed+1831565813>>>0;let t=this.seed;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}spreadAboutAnAxis(t){const e=1/Math.max(1e-6,t*t),i=Math.max(1e-12,this.random()),n=1+Math.log(i+(1-i)*Math.exp(-2*e))/e;return Math.max(-1,Math.min(1,n))}spreadAboutAPlane(t){for(let e=0;e<8;e++){const i=this.gaussian()*t;if(i>=-1&&i<=1)return i}return this.random()*2-1}gaussian(){if(this.hasSpare)return this.hasSpare=!1,this.spare;const t=Math.sqrt(-2*Math.log(Math.max(1e-12,this.random()))),e=2*Math.PI*this.random();return this.spare=t*Math.sin(e),this.hasSpare=!0,t*Math.cos(e)}}class xC{static fromRadiance(t,e){const i=gs.toHalfFloat(1);for(let n=0,s=0;s<t.length;n+=4,s+=3)e[n]=gs.toHalfFloat(t[s]),e[n+1]=gs.toHalfFloat(t[s+1]),e[n+2]=gs.toHalfFloat(t[s+2]),e[n+3]=i}}class Di{static RADIUS=880;static RAYS=9e5;static RAYS_PER_BATCH=2e3;static BUDGET_MS=6;static URGENT_BUDGET_MS=40;static ALTITUDE_STEP_DEG=1;static ALIGNMENT_STEP=.05;static LEAP_ALTITUDE_DEG=5;static LEAP_ALIGNMENT=.25;static GAIN=.55;setCloudOffset(t){this.material.uniforms.uFieldOffset.value.copy(t)}object;material;sky=new ke;texture;texels;mappedAltitudeDeg=Number.NaN;mappedAlignment=Number.NaN;mappedRare=Number.NaN;tracing=!1;everDisplayed=!1;urgent=!1;workHandle;onRepaint;constructor(){const t=ke.AZIMUTH_BINS,e=ke.ALTITUDE_BINS;this.texels=new Uint16Array(t*e*4),this.texture=new Ms(this.texels,t,e,qi,He),this.texture.minFilter=we,this.texture.magFilter=we,this.texture.wrapS=Oi,this.texture.wrapT=Oi,this.texture.needsUpdate=!0,this.material=new Ae({uniforms:{uSource:{value:new R(0,1,0)},uUp:{value:new R(0,1,0)},uStrength:{value:0},uTint:{value:new R(1,.97,.92)},uIceCover:{value:0},uIceHeight:{value:1},uFieldOffset:{value:new R},uMap:{value:this.texture},uGain:{value:Di.GAIN}},vertexShader:`
|
|
8277
|
+
`,blending:vs,depthTest:!1,depthWrite:!1}),this.quad=new xt(new Wn(2,2),this.copyMaterial),this.quadScene.add(this.quad)}develop(t,e,i,n=1,s,r=!0){const a=t.getRenderTarget();this.readable=r,this.copyMaterial.uniforms.uSource.value=e.scene.texture,this.copyMaterial.uniforms.uGain.value=n,this.draw(t,this.copyMaterial,this.mips);const c=this.ghostMaterial.uniforms;c.uSize.value.set(this.mips.width,this.mips.height);const h=Math.min(i.ghosts.length,Kn.MAX_GHOSTS);c.uCount.value=h;for(let f=0;f<h;f++){const p=i.ghosts[f];c.uScale.value[f]=p.scale||1,c.uShare.value[f]=p.share,c.uBlur.value[f]=p.blur,c.uKind.value[f]=p.cause==="drops"?2:fi.scatters(p)?1:0,c.uOffset.value[f].set(p.offset?.[0]??0,p.offset?.[1]??0),c.uTint.value[f].set(...p.tint??[1,1,1])}c.uBlades.value=i.blades,c.uBladeAngle.value=i.bladeAngleRad,c.uDrops.value=i.drops,c.uImpacts.value=i.impacts;const l=c.uHistory.value;for(let f=0;f<l.length;f++)l[f]=i.history[f]??0;c.uStill.value=i.still?1:0,c.uRunning.value=i.running,c.uBright.value.set(((s?.x??0)+1)/2,((s?.y??0)+1)/2),c.uBrightRadius.value=s?.radius??0;const u=s?.flux??[0,0,0];c.uBrightFlux.value.set(u[0]*n,u[1]*n,u[2]*n),this.draw(t,this.ghostMaterial,this.ghostLayer);const d=this.developMaterial.uniforms;d.uSource.value=e.scene.texture,d.uOverlay.value=e.overlay.texture,d.uGain.value=n,d.uKept.value=1-i.scattered,this.draw(t,this.developMaterial,a)}pickAt(t,e,i,n,s){const r=this.mips.width,a=this.mips.height,c=(d,f)=>({x:Math.round((d+1)/2*r),y:Math.round((f+1)/2*a)}),h=c(e,i),l=this.window(t,h.x,h.y,0);if(!l)return;let u;for(const d of n.ghosts){const f=fi.sourceOf(d,{x:e,y:i});if(Math.abs(f.x)>=1||Math.abs(f.y)>=1)continue;const p=Math.max(2,Math.round(d.blur*a/Math.abs(d.scale))),g=Math.min(1+f.x,1-f.x)/2*r/a,m=Math.min(1+f.y,1-f.y)/2,v=Math.max(2*d.blur*a/Math.abs(d.scale),2)/a,y=Kn.smoothstep(0,v,g)*Kn.smoothstep(0,v,m),x=c(f.x,f.y),M=this.window(t,x.x,x.y,p);if(!M)continue;const b=y*d.share*M.mean/(d.scale*d.scale),S=.18*b*s;S<Kn.VISIBLE_RESPONSE||b<.3*l.mean||(!u||S>u.score)&&(u={score:S,hit:{ghost:d,source:{x:M.brightest.x/r*2-1,y:M.brightest.y/a*2-1}}})}return u?.hit}holdsPictureAt(t,e,i){if(!this.readable)return!1;const n=this.window(t,Math.round((e+1)/2*this.mips.width),Math.round((i+1)/2*this.mips.height),4);return n!==void 0&&n.mean>0}dropAt(t,e,i){const n=Math.round((e+1)/2*this.ghostLayer.width),s=Math.round((i+1)/2*this.ghostLayer.height);if(n<0||s<0||n>=this.ghostLayer.width||s>=this.ghostLayer.height)return 0;const r=new Uint16Array(4);return t.readRenderTargetPixels(this.ghostLayer,n,s,1,1,r),Kn.half(r[3])}window(t,e,i,n){const s=Math.max(1,Math.ceil(n/24)),r={x:Math.max(0,e-n),y:Math.max(0,i-n)},a={x:Math.min(this.mips.width-1,e+n),y:Math.min(this.mips.height-1,i+n)};if(r.x>a.x||r.y>a.y)return;const c=a.x-r.x+1,h=a.y-r.y+1,l=new Uint16Array(c*h*4);t.readRenderTargetPixels(this.mips,r.x,r.y,c,h,l);let u=0,d=0,f=-1,p={x:e,y:i};for(let g=r.y;g<=a.y;g+=s){const m=(g-r.y)*c*4;for(let v=0;v<c;v+=s){const y=.2126*Kn.half(l[m+v*4])+.7152*Kn.half(l[m+v*4+1])+.0722*Kn.half(l[m+v*4+2]);u+=y,d++,y>f&&(f=y,p={x:r.x+v,y:g})}}return{mean:d>0?u/d:0,brightest:p}}draw(t,e,i){this.quad.material=e,t.setRenderTarget(i),t.render(this.quadScene,this.quadCamera)}static half(t){const e=t>>10&31,i=t&1023,n=t&32768?-1:1;return e===0?n*i*2**-24:e===31?0:n*(1+i/1024)*2**(e-15)}static smoothstep(t,e,i){const n=Math.max(0,Math.min(1,(i-t)/(e-t)));return n*n*(3-2*n)}resize(t,e){const i=Math.max(1,t),n=Math.max(1,e);(this.mips.width!==Math.ceil(i/2)||this.mips.height!==Math.ceil(n/2))&&(this.readable=!1),this.frame.scene.setSize(i,n),this.frame.overlay.setSize(i,n),this.mips.setSize(Math.ceil(i/2),Math.ceil(n/2)),this.ghostLayer.setSize(Math.ceil(i/2),Math.ceil(n/2))}dispose(){this.frame.scene.dispose(),this.frame.overlay.dispose(),this.mips.dispose(),this.ghostLayer.dispose(),this.copyMaterial.dispose(),this.ghostMaterial.dispose(),this.developMaterial.dispose(),this.quad.geometry.dispose(),this.quadScene.clear()}}class rs{static IDENTITY=[1,0,0,0,1,0,0,0,1];static NONE={colorMatrix:rs.IDENTITY,contrastGain:1};static combine(t,e){const[i,n,s,r,a,c,h,l,u]=t.colorMatrix,[d,f,p,g,m,v,y,x,M]=e.colorMatrix;return{colorMatrix:[d*i+f*r+p*h,d*n+f*a+p*l,d*s+f*c+p*u,g*i+m*r+v*h,g*n+m*a+v*l,g*s+m*c+v*u,y*i+x*r+M*h,y*n+x*a+M*l,y*s+x*c+M*u],contrastGain:t.contrastGain*e.contrastGain}}static isNone(t){return t.contrastGain===1&&t.colorMatrix.every((e,i)=>e===rs.IDENTITY[i])}}class ze{static MIN_RATIO=1;static STEP=.25;static MIN_SHARE_OF_DISPLAY=.75;static GPU_LATE_MS=12;static GPU_ROOM_MS=6;static INTERVAL_LATE_MS=21;static LOWER_COOLDOWN_MS=750;static RAISE_COOLDOWN_MS=2e3;static PROBE_WATCH_MS=2e3;static PROBE_EVERY_MS=6e3;static PROBE_BACKOFF_MS=3e4;ratio;maxRatio;timer;intervalMs;lastChangeMs=-1/0;nextProbeMs=0;probe;constructor(t,e){this.maxRatio=ze.clamp(t),this.ratio=this.maxRatio,this.timer=e?gf.create(e):void 0}get pixelRatio(){return this.ratio}static SETTLE_MS=400;static SUSTAINED_MS=100;lastEditMs=-1/0;editStreakStartMs=-1/0;wasChanging=!1;noteChange(t){t-this.lastEditMs>ze.SETTLE_MS&&(this.editStreakStartMs=t),this.lastEditMs=t}changing(t){return t-this.lastEditMs<=ze.SETTLE_MS&&this.lastEditMs-this.editStreakStartMs>=ze.SUSTAINED_MS}ratioFor(t,e){return this.changing(t)?this.wasChanging?(this.update(t,e),this.ratio):(this.wasChanging=!0,this.reset(),this.ratio):(this.wasChanging=!1,this.maxRatio)}get timesGpu(){return this.timer!==void 0}set maximum(t){this.maxRatio=ze.clamp(t),this.ratio>this.maxRatio&&(this.ratio=this.maxRatio),this.ratio<this.minimum&&(this.ratio=Math.min(this.maxRatio,this.minimum))}get minimum(){const t=Math.floor(this.maxRatio*ze.MIN_SHARE_OF_DISPLAY/ze.STEP)*ze.STEP;return Math.max(ze.MIN_RATIO,t)}get maximum(){return this.maxRatio}beginDrawing(){this.timer?.begin()}endDrawing(){this.timer?.end()}reset(){this.intervalMs=void 0,this.probe=void 0,this.timer?.reset()}update(t,e){const i=this.timer?.poll();if(!(this.timer&&i===void 0))return i!==void 0?this.followGpu(t,i):this.followIntervals(t,e)}followGpu(t,e){if(e>ze.GPU_LATE_MS)return this.lower(t,ze.LOWER_COOLDOWN_MS);if(e<ze.GPU_ROOM_MS)return this.raise(t,ze.RAISE_COOLDOWN_MS)}followIntervals(t,e){if(!(e>0)||e>1e3)return;this.intervalMs=this.intervalMs===void 0?e:this.intervalMs*.9+e*.1;const i=this.intervalMs>ze.INTERVAL_LATE_MS;if(this.probe){if(i)return this.ratio=this.probe.ratioBefore,this.probe=void 0,this.lastChangeMs=t,this.nextProbeMs=t+ze.PROBE_BACKOFF_MS,this.ratio;t-this.probe.sinceMs>=ze.PROBE_WATCH_MS&&(this.probe=void 0,this.nextProbeMs=t+ze.PROBE_EVERY_MS);return}if(i){const n=this.lower(t,ze.LOWER_COOLDOWN_MS);return n!==void 0&&(this.nextProbeMs=t+ze.PROBE_EVERY_MS),n}if(this.ratio<this.maxRatio&&t>=this.nextProbeMs&&t-this.lastChangeMs>=ze.RAISE_COOLDOWN_MS){const n=this.ratio,s=this.raise(t,0);return s!==void 0&&(this.probe={sinceMs:t,ratioBefore:n}),s}}lower(t,e){if(!(this.ratio<=this.minimum||t-this.lastChangeMs<e))return this.ratio=Math.max(this.minimum,ze.clamp(this.ratio-ze.STEP)),this.lastChangeMs=t,this.ratio}raise(t,e){if(!(this.ratio>=this.maxRatio||t-this.lastChangeMs<e))return this.ratio=Math.min(this.maxRatio,ze.clamp(this.ratio+ze.STEP)),this.lastChangeMs=t,this.ratio}static clamp(t){return Number.isFinite(t)?Math.max(ze.MIN_RATIO,Math.round(t/ze.STEP)*ze.STEP):ze.MIN_RATIO}}class gf{constructor(t,e){this.gl=t,this.extension=e}static IN_FLIGHT_MAX=8;static create(t){if(!(t instanceof WebGL2RenderingContext))return;const e=t.getExtension("EXT_disjoint_timer_query_webgl2");return e?new gf(t,e):void 0}pending=[];active;smoothedMs;begin(){if(!(this.active||this.pending.length>=gf.IN_FLIGHT_MAX))try{const t=this.gl.createQuery();if(!t)return;this.gl.beginQuery(this.extension.TIME_ELAPSED_EXT,t),this.active=t}catch{this.active=void 0}}end(){if(this.active){try{this.gl.endQuery(this.extension.TIME_ELAPSED_EXT),this.pending.push(this.active)}catch{}this.active=void 0}}poll(){const t=this.gl;try{for(let e=0;e<this.pending.length;e++){const i=this.pending[e];if(!t.getQueryParameter(i,t.QUERY_RESULT_AVAILABLE))continue;if(!t.getParameter(this.extension.GPU_DISJOINT_EXT)){const s=t.getQueryParameter(i,t.QUERY_RESULT)/1e6;this.smoothedMs=this.smoothedMs===void 0?s:this.smoothedMs*.8+s*.2}t.deleteQuery(i),this.pending.splice(e,1),e--}}catch{this.pending.length=0}return this.smoothedMs}reset(){this.smoothedMs=void 0}}class de{static ICE_INDEX_RED=1.3067;static ICE_INDEX_BLUE=1.317;static SIDE_PRISM_ANGLE_DEG=60;static END_PRISM_ANGLE_DEG=90;static get PARHELIA_MAX_SUN_ALTITUDE_DEG(){const t=de.ICE_INDEX_RED,e=Math.sqrt((4-t*t)/3);return Math.asin(Math.min(1,e))*180/Math.PI}static minimumDeviationDeg(t,e){const i=t*Math.PI/180,n=e*Math.sin(i/2);return n>1?Number.NaN:(2*Math.asin(n)-i)*180/Math.PI}static effectiveIndex(t,e){const i=e*Math.PI/180,n=Math.cos(i);return n<=0?Number.POSITIVE_INFINITY:Math.sqrt(t*t-Math.sin(i)**2)/n}static parheliaAzimuthDeg(t,e=de.ICE_INDEX_RED){const i=de.minimumDeviationDeg(de.SIDE_PRISM_ANGLE_DEG,de.effectiveIndex(e,t));return Number.isFinite(i)?i:void 0}static parheliaDistanceDeg(t,e=de.ICE_INDEX_RED){const i=de.parheliaAzimuthDeg(t,e);if(i===void 0)return;const n=t*Math.PI/180,s=Math.sin(n)**2,r=Math.cos(n)**2*Math.cos(i*Math.PI/180);return Math.acos(Math.max(-1,Math.min(1,s+r)))*180/Math.PI}static get PLATE_END_FACE_LIMIT_DEG(){const t=de.ICE_INDEX_RED;return Math.asin(Math.min(1,Math.sqrt(t*t-1)))*180/Math.PI}static circumzenithalAltitudeDeg(t,e=de.ICE_INDEX_RED){if(t<0||t>90-de.PLATE_END_FACE_LIMIT_DEG)return;const i=Math.cos(t*Math.PI/180),n=Math.sqrt(e*e-i*i);if(!(n>=1))return Math.asin(n)*180/Math.PI}static DECK_HEIGHT_M=8e3;static deckLitUntilDeg(t){return Math.acos(6371e3/(6371e3+Math.max(0,t)))*180/Math.PI}static halo22(){return de.ringOf("halo22",de.SIDE_PRISM_ANGLE_DEG)}static halo46(){return de.ringOf("halo46",de.END_PRISM_ANGLE_DEG)}static ringOf(t,e){const i=de.minimumDeviationDeg(e,de.ICE_INDEX_RED),n=de.minimumDeviationDeg(e,de.ICE_INDEX_BLUE);return{id:t,angleDeg:(i+n)/2,redAngleDeg:i,blueAngleDeg:n}}static strength(t,e,i=90,n=0){const s=Math.max(0,Math.min(1,t)),r=Math.max(0,1-Math.max(0,Math.min(1,e))),a=i>=0?1:n<=0?0:Math.max(0,1+i/n);return s*r*a}static formsAt(t,e=0){if(t<=-e)return[];const i=[de.halo22(),de.halo46()],n=t>0?de.parheliaDistanceDeg(t):void 0;n!==void 0&&i.push({id:"parhelia",angleDeg:n,redAngleDeg:n,blueAngleDeg:de.parheliaDistanceDeg(t,de.ICE_INDEX_BLUE)}),i.push({id:"tangentArc",angleDeg:de.halo22().angleDeg}),t>0&&i.push({id:"parhelicCircle",angleDeg:t});const s=de.circumzenithalAltitudeDeg(t);return s!==void 0&&i.push({id:"circumzenithal",angleDeg:s}),t>de.PLATE_END_FACE_LIMIT_DEG&&i.push({id:"circumhorizontal"}),t<de.PILLAR_MAX_SOURCE_ALTITUDE_DEG&&i.push({id:"pillar"}),i}static PILLAR_MAX_SOURCE_ALTITUDE_DEG=20}class ls{static get WATER_INDEX_RED(){return hn.indexAt(hn.RED_NM)}static get WATER_INDEX_BLUE(){return hn.indexAt(hn.BLUE_NM)}static radiusDeg(t,e){const i=(e*e-1)/(t*t-1);if(i<0||i>1)return Number.NaN;const n=Math.acos(Math.sqrt(i)),s=Math.asin(Math.sin(n)/e),r=2*(n-s)+(t-1)*(Math.PI-2*s),a=2*Math.PI;let c=r%a;return c<0&&(c+=a),c>Math.PI&&(c=a-c),180-c*180/Math.PI}static primary(){return ls.bowOf("primary",2,0)}static secondary(){return ls.bowOf("secondary",3,0)}static bowOf(t,e,i){const n=ls.radiusDeg(e,ls.WATER_INDEX_RED),s=ls.radiusDeg(e,ls.WATER_INDEX_BLUE),r=(n+s)/2;return{id:t,radiusDeg:r,redRadiusDeg:n,violetRadiusDeg:s,topAltitudeDeg:r-i}}static alexandersBandDeg(){return{fromDeg:ls.primary().redRadiusDeg,toDeg:ls.secondary().redRadiusDeg}}static formsAt(t){return t<0?[]:[ls.bowOf("primary",2,t),ls.bowOf("secondary",3,t)].filter(e=>e.topAltitudeDeg>0)}static FULL_MOON_MAGNITUDE=-12.7;static moonlightShare(t){return Math.min(1,10**(-.4*(t-ls.FULL_MOON_MAGNITUDE)))}static strength(t,e,i){if(i<=0)return 0;const n=Math.max(0,Math.min(1,t)),s=Math.max(0,1-Math.max(0,Math.min(1,e)));return n*s}}class us{constructor(t){this.radius=t;const e=us.SEGMENTS*us.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const i=new se;i.setAttribute("position",new ce(this.positions,3)),i.setAttribute("color",new ce(this.colors,3)),i.setDrawRange(0,0),this.object=new xt(i,is.material()),this.object.frustumCulled=!1,is.track(this.object)}static POINTS=24;static SEGMENTS=us.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(us.ACROSS-1)*6;static HEAD_HALF_WIDTH_DEG=.15;static SPREAD_FRACTION=.05;static FADE_POWER=1.8;object;positions;colors;head;tip;brightness=0;set(t,e,i){this.head=t&&Ke(t.altitudeDeg,t.azimuthDeg,1),this.tip=e&&Ke(e.altitudeDeg,e.azimuthDeg,1),this.brightness=i,this.rebuild()}rebuild(){const t=this.object.geometry,e=this.head,i=this.tip;if(!e||!i||this.brightness<=0){t.setDrawRange(0,0);return}const n=this.angleBetween(e,i);if(n<=0){t.setDrawRange(0,0);return}const s=n*us.SPREAD_FRACTION*Math.PI/180,r=l=>this.scale(this.slerp(e,i,l),this.radius),a=l=>this.radius*(us.HEAD_HALF_WIDTH_DEG*Math.PI/180+s*l),c=l=>this.brightness*(1-l)**us.FADE_POWER;let h=0;for(let l=1;l<us.POINTS;l++){const u=(l-1)/us.SEGMENTS,d=l/us.SEGMENTS;h=this.pushBand(h,r(u),r(d),a(u),a(d),c(u),c(d))}t.setDrawRange(0,h),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}pushBand(t,e,i,n,s,r,a){const c=this.normalise(this.cross(this.normalise(e),this.normalise(this.subtract(i,e))));for(let h=0;h<us.ACROSS-1;h++){const l=h-1,u=h,d=this.across(e,c,n,l),f=this.across(i,c,s,l),p=this.across(e,c,n,u),g=this.across(i,c,s,u),m=(v,y)=>v===0?y:0;t=this.push(t,d,m(l,r)),t=this.push(t,f,m(l,a)),t=this.push(t,p,m(u,r)),t=this.push(t,f,m(l,a)),t=this.push(t,g,m(u,a)),t=this.push(t,p,m(u,r))}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i){const n=t*3;this.positions[n]=e.x,this.positions[n+1]=e.y,this.positions[n+2]=e.z;const s=Pt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.55,this.colors[n+1]=s*.75,this.colors[n+2]=s,t+1}slerp(t,e,i){const n=this.angleBetweenRadians(t,e);if(n<1e-9)return t;const s=Math.sin(n),r=Math.sin((1-i)*n)/s,a=Math.sin(i*n)/s;return{x:t.x*r+e.x*a,y:t.y*r+e.y*a,z:t.z*r+e.z*a}}angleBetween(t,e){return this.angleBetweenRadians(t,e)*180/Math.PI}angleBetweenRadians(t,e){const i=t.x*e.x+t.y*e.y+t.z*e.z;return Math.acos(Math.min(1,Math.max(-1,i)))}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}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}}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}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class MC{object=new Pe;radius;tiers;drawn=[];constructor(t){this.radius=t,this.object.name="satellites",this.tiers=Po.map(e=>{const i=new Qn(new se,Ot.material(e.size));return Ot.track(i),i.frustumCulled=!1,this.object.add(i),i})}set(t,e,i,n){const s=this.tiers.map(()=>[]);this.drawn=[];for(const r of t){if(r.magnitude>e)continue;const a=i(r.position);if(a<=0)continue;const c=r.magnitude-2.5*Math.log10(a);if(c>e)continue;const h=_o(c,e),l=Bf(h),{x:u,y:d,z:f}=Ke(r.position.altitudeDeg,r.position.azimuthDeg,this.radius),[p,g,m]=n(r.position,c);s[l].push({x:u,y:d,z:f,r:p,g,b:m,seed:r.norad*.6180339887%1}),this.drawn.push({satellite:r,direction:new R(u,d,f).normalize()})}this.tiers.forEach((r,a)=>{const c=s[a],h=new Float32Array(c.length*3),l=new Float32Array(c.length*3),u=new Float32Array(c.length);c.forEach((f,p)=>{h.set([f.x,f.y,f.z],p*3),l.set([f.r,f.g,f.b],p*3),u[p]=f.seed}),r.geometry.dispose();const d=new se;d.setAttribute("position",new ce(h,3)),d.setAttribute("color",new ce(l,3)),d.setAttribute("seed",new ce(u,1)),r.geometry=d})}get count(){return this.drawn.length}nearest(t,e){let i,n=e;for(const s of this.drawn){const r=s.direction.dot(t);r>n&&(n=r,i=s.satellite)}return i}dispose(){for(const t of this.tiers)t.geometry.dispose(),t.material.dispose();this.object.removeFromParent(),this.drawn=[]}}class ds{static MU=398600.4418;static OMEGA=72921159e-12;static EARTH_RADIUS_KM=6371;static STEP_S=1;static DENSITY=[[0,1.225],[20,.0889],[40,.004],[60,31e-5],[80,185e-7],[100,56e-8],[120,222e-10],[150,208e-11],[200,254e-12],[250,607e-13],[300,192e-13],[400,28e-13],[500,522e-15],[600,114e-15],[700,307e-16],[800,114e-16],[900,576e-17],[1e3,356e-17]];static FREE_PATH_TIMES_DENSITY=68e-9;static ICE_DENSITY=917;static airDensity(t){const e=ds.DENSITY;if(t<=e[0][0])return e[0][1];let i=0;for(;i<e.length-2&&e[i+1][0]<t;)i++;const[n,s]=e[i],[r,a]=e[i+1];return s*Math.exp(Math.log(a/s)*(t-n)/(r-n))}static dragPerKm(t,e,i,n=.5){const s=ds.airDensity(t),r=ds.FREE_PATH_TIMES_DENSITY/s/1e3,a=Math.exp(-r/e),c=s*1e9*Math.PI*e*e/Math.max(i,1e-9),h=3*s/(4*n*1e-6*ds.ICE_DENSITY)*1e3;return a*c+(1-a)*h}static step(t,e,i,n,s){const[r,a,c,h,l,u]=t,d=Math.hypot(r,a,c),f=ds.OMEGA,p=-398600.4418/(d*d*d),g=p*r+2*f*l+f*f*r,m=p*a-2*f*h+f*f*a,v=p*c,y=Math.hypot(h,l,u),M=1/(1+ds.dragPerKm(d-ds.EARTH_RADIUS_KM,i,n,s)*y*e);t[3]=(h+g*e)*M,t[4]=(l+m*e)*M,t[5]=(u+v*e)*M,t[0]=r+t[3]*e,t[1]=a+t[4]*e,t[2]=c+t[5]*e;const b=Math.hypot(t[0],t[1],t[2]);if(b<ds.EARTH_RADIUS_KM){const S=ds.EARTH_RADIUS_KM/b;t[0]*=S,t[1]*=S,t[2]*=S,t[3]=t[4]=t[5]=0}}}class yC{constructor(t,e,i,n,s=.5){this.massKg=i,this.radiusAt=n,this.particleRadiusUm=s,this.state=Float64Array.of(...t,...e),this.positions=new Float64Array(192),this.positions.set(t,0)}positions;steps=0;state;at(t){const e=ds.STEP_S,i=Math.max(0,t/e),n=Math.ceil(i);for(;this.steps<n;){if(ds.step(this.state,e,this.radiusAt(this.steps*e),this.massKg,this.particleRadiusUm),this.steps++,3*(this.steps+1)>this.positions.length){const c=new Float64Array(this.positions.length*2);c.set(this.positions),this.positions=c}this.positions.set(this.state.subarray(0,3),3*this.steps)}const s=Math.floor(i),r=i-s,a=this.positions;return r===0||s>=this.steps?[a[3*s],a[3*s+1],a[3*s+2]]:[0,1,2].map(c=>a[3*s+c]+(a[3*s+3+c]-a[3*s+c])*r)}}class _e{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=1.5;static FADE_MS=600;static TRAIN_POINTS=8;static leadAt(t,e){const i=t.track;if(i.length<2||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<e;)n++;const s=i[n],r=i[n+1],a=r.t-s.t,c=a>0?(e-s.t)/a:0,[h,l]=_e.alongGreatCircle(s,r,c);return{lat:h,lng:l,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*c)*1e3}}static viewsAt(t,e,i){const n=[];for(const s of t){const r=s.track[0]?.t??0,a=s.track[s.track.length-1]?.t??0;s.fragments.forEach((c,h)=>{const l=c.fromT??r,u=c.untilT??a;if(e<l||e>u)return;const d=(c.lagS??0)*1e3,f=_e.leadAt(s,e-d);if(!f)return;const p=_e.seenFrom(i,f);if(p.altitudeDeg<0)return;const g=Math.min(_e.FADE_MS,(u-l)/4),m=g>0?Math.min(1,(e-l)/g,(u-e)/g):1,v=-2.5*Math.log10(Math.max(m,.001)),y=c.absoluteMagnitude+5*Math.log10(p.distanceKm/_e.STANDARD_DISTANCE_KM)+v,x=[p],M=(c.trainS??_e.DEFAULT_TRAIN_S)*1e3;for(let b=1;b<=_e.TRAIN_POINTS;b++){const S=Math.min(M*b/_e.TRAIN_POINTS,e-l),E=_e.leadAt(s,e-d-S);if(!E||(x.push(_e.seenFrom(i,E)),S>=e-l))break}n.push({reentryId:s.id,fragmentId:c.id??String(h),head:p,magnitude:y,color:c.color??_e.DEFAULT_COLOR,train:x})})}return n}static seenFrom(t,e){const i=_e.ecef(t),n=_e.ecef(e),s=n[0]-i[0],r=n[1]-i[1],a=n[2]-i[2],c=t.lat*_e.DEG,h=t.lng*_e.DEG,l=-Math.sin(h)*s+Math.cos(h)*r,u=-Math.sin(c)*Math.cos(h)*s-Math.sin(c)*Math.sin(h)*r+Math.cos(c)*a,d=Math.cos(c)*Math.cos(h)*s+Math.cos(c)*Math.sin(h)*r+Math.sin(c)*a,f=Math.hypot(l,u,d);return{altitudeDeg:Math.asin(d/f)/_e.DEG,azimuthDeg:(Math.atan2(l,u)/_e.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*_e.DEG,i=t.lng*_e.DEG,n=Math.sin(e),s=_e.A/Math.sqrt(1-_e.E2*n*n);return[(s+t.heightM)*Math.cos(e)*Math.cos(i),(s+t.heightM)*Math.cos(e)*Math.sin(i),(s*(1-_e.E2)+t.heightM)*n]}static alongGreatCircle(t,e,i){const n=l=>{const u=l.lat*_e.DEG,d=l.lng*_e.DEG;return[Math.cos(u)*Math.cos(d),Math.cos(u)*Math.sin(d),Math.sin(u)]},s=n(t),r=n(e),a=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),c=Math.acos(a);let h;if(c<1e-12)h=s;else{const l=Math.sin((1-i)*c)/Math.sin(c),u=Math.sin(i*c)/Math.sin(c);h=[s[0]*l+r[0]*u,s[1]*l+r[1]*u,s[2]*l+r[2]*u]}return[Math.atan2(h[2],Math.hypot(h[0],h[1]))/_e.DEG,Math.atan2(h[1],h[0])/_e.DEG]}}class It{static EARTH_RADIUS_KM=6371;static SHADOW_RADIUS_KM=It.EARTH_RADIUS_KM+15;static PENUMBRA_KM=10;static SUN_ILLUMINANCE_LUX=127e3;static RAYLEIGH_PER_M=[58e-7,135e-7,331e-7];static SCALE_HEIGHT_M=8e3;static OZONE_GRAZING_DEPTH=[2.4,1.8,.24];static ANISOTROPY=.7;static ALBEDO=.99;static WAVELENGTHS_UM=[.61,.55,.465];static ICE_INDEX=1.31;static DEFAULTS={exhaustKgPerS:273,condensedShare:.065,particleRadiusUm:.5,expansionKmPerS:.15,initialRadiusKm:.5,lifetimeS:420,collarShare:.85,collarExpansionKmPerS:2.5,collarLifetimeS:20};static PROPELLANTS={"rp1-lox":{condensedShare:.065,particleRadiusUm:.5},"methane-lox":{condensedShare:.09,particleRadiusUm:.5},"hydrogen-lox":{condensedShare:.13,particleRadiusUm:.5},hypergolic:{condensedShare:.079,particleRadiusUm:.4},solid:{condensedShare:.27,particleRadiusUm:.8}};static G0=9.80665;static COLLAR_SPREAD_OF_EXHAUST_VELOCITY=.735;static plumeOf(t){const e={},i=t.vehicle?.engine;if(i){const n=i.specificImpulseS===void 0?void 0:i.specificImpulseS*It.G0;i.thrustKN!==void 0&&n&&(e.exhaustKgPerS=i.thrustKN*1e3/n),n&&(e.collarExpansionKmPerS=n/1e3*It.COLLAR_SPREAD_OF_EXHAUST_VELOCITY),i.propellant&&Object.assign(e,It.PROPELLANTS[i.propellant])}return{...It.DEFAULTS,...e,...t.plume}}static PUFF_EVERY_S=.5;static SIGMA_OF_RADIUS=.5;static MAX_PUFFS=320;static DEG=Math.PI/180;static EARTH_ROTATION=72921159e-12;static VENT_DEFAULTS={speedKmPerS:.7,massKgPerS:20,condensedShare:.5,particleRadiusUm:.5,expansionKmPerS:.1,initialRadiusKm:.2,lifetimeS:600};static paths=new WeakMap;static exhaustVelocityKmPerS(t){return(t.vehicle?.engine?.specificImpulseS??348)*It.G0/1e3}static releasesOf(t){const e=[],i=t.jets??[];if(i.length===0||t.burnFromT!==void 0||t.burnUntilT!==void 0){const n=t.track[0]?.t??0,s=t.track[t.track.length-1]?.t??0;e.push(It.engineRelease(t,"burn",{fromT:t.burnFromT??n,untilT:t.burnUntilT??s}))}return i.forEach((n,s)=>e.push(It.releaseOf(t,n,s))),e}static releaseOf(t,e,i){const n=`jet:${e.id??i}`;if((e.kind??"burn")==="burn")return It.engineRelease(t,n,e);const s=It.VENT_DEFAULTS;return{key:n,fromT:e.fromT,untilT:e.untilT,angleDeg:e.angleDeg??0,azimuthDeg:e.azimuthDeg??0,spinPeriodS:e.spinPeriodS,speedKmPerS:e.speedKmPerS??s.speedKmPerS,massKgPerS:e.massKgPerS??s.massKgPerS,condensedShare:e.condensedShare??s.condensedShare,particleRadiusUm:e.particleRadiusUm??s.particleRadiusUm,initialRadiusKm:e.initialRadiusKm??s.initialRadiusKm,populations:[{share:1,expansionKmPerS:e.expansionKmPerS??s.expansionKmPerS,lifetimeS:e.lifetimeS??s.lifetimeS}]}}static engineRelease(t,e,i){const n=It.plumeOf(t);return{key:e,fromT:i.fromT,untilT:i.untilT,angleDeg:i.angleDeg??0,azimuthDeg:i.azimuthDeg??0,spinPeriodS:i.spinPeriodS,speedKmPerS:i.speedKmPerS??It.exhaustVelocityKmPerS(t),massKgPerS:i.massKgPerS??n.exhaustKgPerS,condensedShare:i.condensedShare??n.condensedShare,particleRadiusUm:i.particleRadiusUm??n.particleRadiusUm,initialRadiusKm:i.initialRadiusKm??n.initialRadiusKm,populations:[{share:1-n.collarShare,expansionKmPerS:i.expansionKmPerS??n.expansionKmPerS,lifetimeS:i.lifetimeS??n.lifetimeS},{share:n.collarShare,expansionKmPerS:n.collarExpansionKmPerS,lifetimeS:n.collarLifetimeS}]}}static extinctionEfficiency(t,e){const i=2*Math.PI*t/e,n=It.ICE_INDEX**2,s=8/3*i**4*((n-1)/(n+2))**2,r=2*i*(It.ICE_INDEX-1),a=r<.001?r*r/2:2-4/r*Math.sin(r)+4/(r*r)*(1-Math.cos(r));return Math.min(s,a)}static scatteringColour(t){const e=It.extinctionEfficiency(t,It.WAVELENGTHS_UM[1]);return It.WAVELENGTHS_UM.map(i=>It.extinctionEfficiency(t,i)/e)}static sunDirectionAt(t){const e=new ea(0,0,-6378137),i=vh(ut.Sun,t,e,!0,!0),n=(i.ra-tb(t))*15*It.DEG,s=i.dec*It.DEG;return[Math.cos(s)*Math.cos(n),Math.cos(s)*Math.sin(n),Math.sin(s)]}static puffsAt(t,e){const i=[];for(const n of t){let s=It.paths.get(n);s||It.paths.set(n,s=new Map);for(const r of It.releasesOf(n)){const a=Math.min(r.untilT,e);if(a<=r.fromT)continue;const c=Math.max(It.PUFF_EVERY_S*1e3,(r.untilT-r.fromT)/It.MAX_PUFFS),h=[];for(let p=r.fromT;p<a;p+=c)h.push(p);h.push(a);const l=r.massKgPerS*(c/1e3),d=3*It.extinctionEfficiency(r.particleRadiusUm,It.WAVELENGTHS_UM[1])/(4*917*r.particleRadiusUm*1e-6),f=It.scatteringColour(r.particleRadiusUm);r.populations.forEach((p,g)=>{if(p.share<=0)return;const m=y=>r.initialRadiusKm+p.expansionKmPerS*y,v=[];for(const y of h){const x=(e-y)/1e3;if(x>p.lifetimeS)continue;const M=y!==a||a===r.untilT,b=`${r.key}|${g}|${y}`;let S=M?s.get(b):void 0;if(!S){if(S=It.launchPuff(n,r,y,l*p.share,m),!S)continue;M&&s.set(b,S)}v.push({ageS:x,position:S.at(x)})}for(let y=v.length-1;y>=0;y--){const{ageS:x,position:M}=v[y],b=v[y-1]??v[y+1],S=b?Math.hypot(M[0]-b.position[0],M[1]-b.position[1],M[2]-b.position[2]):0,E=m(x)+S/2,w=It.SIGMA_OF_RADIUS*E*1e3,_=l*r.condensedShare*p.share*d/(2*Math.PI*w*w),D=Math.max(0,1-(x/p.lifetimeS)**2);_*D<=0||i.push({launchId:n.id,release:r.key,at:It.geoPoint(M),radiusKm:E,opticalDepth:_*D,colour:f,ageS:x})}})}}return i}static viewsAt(t,e,i,n){const s=[];for(const r of It.puffsAt(t,e)){const a=_e.seenFrom(i,r.at);if(a.altitudeDeg<0)continue;const c=It.sunlightAt(r.at,n);if(c.lit<=0)continue;const h=It.scatteringPhase(i,r.at,n),l=It.SUN_ILLUMINANCE_LUX*It.ALBEDO*h*r.opticalDepth*c.lit;l<=0||s.push({launchId:r.launchId,release:r.release,heightKm:r.at.heightM/1e3,centre:a,radiusDeg:Math.atan2(r.radiusKm,a.distanceKm)/It.DEG,luminanceCdM2:l,sunTransmittance:c.transmittance,colour:r.colour,lit:c.lit,ageS:r.ageS})}return s}static launchPuff(t,e,i,n,s){const r={id:t.id,track:t.track,fragments:[]},a=_e.leadAt(r,i);if(!a)return;const c=t.track[0].t,h=t.track[t.track.length-1].t,l=Math.max(c,i-500),u=Math.min(h,i+500),d=It.earthCentred(a),f=It.earthCentred(_e.leadAt(r,l)),p=It.earthCentred(_e.leadAt(r,u)),g=Math.max(.001,(u-l)/1e3),m=[0,1,2].map(N=>(p[N]-f[N])/g),v=It.EARTH_ROTATION,y=[m[0]-v*d[1],m[1]+v*d[0],m[2]],x=N=>{const P=Math.hypot(N[0],N[1],N[2])||1;return N.map(z=>z/P)},M=x(y),b=x(d),S=b[0]*M[0]+b[1]*M[1]+b[2]*M[2];let E=[b[0]-S*M[0],b[1]-S*M[1],b[2]-S*M[2]];Math.hypot(E[0],E[1],E[2])<1e-6&&(E=[-M[2]*M[0],-M[2]*M[1],1-M[2]*M[2]]),E=x(E);const w=[M[1]*E[2]-M[2]*E[1],M[2]*E[0]-M[0]*E[2],M[0]*E[1]-M[1]*E[0]],_=e.spinPeriodS?360*((i-e.fromT)/1e3)/e.spinPeriodS:0,D=(e.azimuthDeg+_)*It.DEG,I=e.angleDeg*It.DEG,O=[0,1,2].map(N=>-M[N]*Math.cos(I)+Math.sin(I)*(Math.cos(D)*E[N]+Math.sin(D)*w[N])),L=[0,1,2].map(N=>m[N]+e.speedKmPerS*O[N]);return new yC(d,L,n,s,e.particleRadiusUm)}static geoPoint(t){const e=Math.hypot(t[0],t[1],t[2]);return{lat:Math.asin(t[2]/e)/It.DEG,lng:Math.atan2(t[1],t[0])/It.DEG,heightM:(e-ds.EARTH_RADIUS_KM)*1e3}}static sunlightAt(t,e){const i=It.earthCentred(t),n=i[0]*e[0]+i[1]*e[1]+i[2]*e[2];if(n>=0)return{lit:1,transmittance:[1,1,1]};const s=Math.hypot(i[0]-n*e[0],i[1]-n*e[1],i[2]-n*e[2]),r=It.PENUMBRA_KM,a=Math.min(1,Math.max(0,(s-(It.SHADOW_RADIUS_KM-r/2))/r));if(a<=0)return{lit:0,transmittance:[0,0,0]};const c=Math.max(0,(s-It.EARTH_RADIUS_KM)*1e3),h=Math.exp(-c/It.SCALE_HEIGHT_M),l=Math.sqrt(2*Math.PI*It.EARTH_RADIUS_KM*1e3*It.SCALE_HEIGHT_M),u=Math.exp(-(((c/1e3-25)/15)**2)),d=[0,1,2].map(f=>Math.exp(-It.RAYLEIGH_PER_M[f]*h*l-It.OZONE_GRAZING_DEPTH[f]*u));return{lit:a,transmittance:d}}static scatteringPhase(t,e,i){const n=It.earthCentred(t),s=It.earthCentred(e),r=[n[0]-s[0],n[1]-s[1],n[2]-s[2]],a=Math.hypot(r[0],r[1],r[2])||1,c=-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])/a,h=It.ANISOTROPY;return(1-h*h)/(4*Math.PI*(1+h*h-2*h*c)**1.5)}static earthCentred(t){const e=t.lat*It.DEG,i=t.lng*It.DEG,n=It.EARTH_RADIUS_KM+t.heightM/1e3;return[n*Math.cos(e)*Math.cos(i),n*Math.cos(e)*Math.sin(i),n*Math.sin(e)]}}class ai{static RADIUS=840;static MAX_PUFFS=1e3;static RINGS=[0,.25,.5,.75,1,1.25];static COLUMN=ai.RINGS.map(t=>{const e=n=>Math.exp(-((n/It.SIGMA_OF_RADIUS)**2)/2),i=e(ai.RINGS[ai.RINGS.length-1]);return Math.max(0,(e(t)-i)/(1-i))});static SECTORS=12;static VERTICES_PER_PUFF=ai.SECTORS*(3+6*(ai.RINGS.length-2));static BRIGHTEST_RELATIVE=6e4;object=new Pe;mesh;positions=new Float32Array(ai.MAX_PUFFS*ai.VERTICES_PER_PUFF*3);colors=new Float32Array(ai.MAX_PUFFS*ai.VERTICES_PER_PUFF*3);shown=0;drawn=[];static VISIBLE_CONTRAST=.1;constructor(){this.object.name="plumes";const t=new se;t.setAttribute("position",new ce(this.positions,3)),t.setAttribute("color",new ce(this.colors,3)),t.setDrawRange(0,0),this.mesh=new xt(t,is.material()),this.mesh.frustumCulled=!1,is.track(this.mesh),this.object.add(this.mesh)}get count(){return this.shown}set(t,e,i,n){let s=0,r=0;this.drawn=[];for(const c of t){if(r>=ai.MAX_PUFFS)break;const h=n(c.centre);if(h<=0)continue;const l=i(c.centre),u=[0,1,2].map(d=>Math.min(ai.BRIGHTEST_RELATIVE,c.luminanceCdM2*(c.colour?.[d]??1)*e*c.sunTransmittance[d]*l[d]*h));Math.max(...u)<=0||(s=this.pushPuff(s,c,u),this.drawn.push({view:c,direction:this.normalise(Ke(c.centre.altitudeDeg,c.centre.azimuthDeg,1)),radiusRad:c.radiusDeg*Math.PI/180,luminance:.2126*u[0]+.7152*u[1]+.0722*u[2]}),r++)}this.shown=r;const a=this.mesh.geometry;a.setDrawRange(0,s),a.getAttribute("position").needsUpdate=!0,a.getAttribute("color").needsUpdate=!0}pushPuff(t,e,i){const n=Ke(e.centre.altitudeDeg,e.centre.azimuthDeg,ai.RADIUS),s=this.normalise(n),r=this.normalise(this.cross({x:0,y:1,z:0},s)),a=this.cross(s,r),c=ai.RADIUS*Math.tan(e.radiusDeg*Math.PI/180),h=(u,d)=>{const f=d/ai.SECTORS*2*Math.PI,p=ai.RINGS[u]*c,g=Math.cos(f)*p,m=Math.sin(f)*p;return{x:n.x+r.x*g+a.x*m,y:n.y+r.y*g+a.y*m,z:n.z+r.z*g+a.z*m}},l=u=>ai.COLUMN[u];for(let u=0;u<ai.SECTORS;u++){const d=(u+1)%ai.SECTORS;t=this.push(t,n,i,l(0)),t=this.push(t,h(1,u),i,l(1)),t=this.push(t,h(1,d),i,l(1));for(let f=1;f<ai.RINGS.length-1;f++){const p=h(f,u),g=h(f,d),m=h(f+1,u),v=h(f+1,d);t=this.push(t,p,i,l(f)),t=this.push(t,g,i,l(f)),t=this.push(t,m,i,l(f+1)),t=this.push(t,g,i,l(f)),t=this.push(t,v,i,l(f+1)),t=this.push(t,m,i,l(f+1))}}return t}pickAt(t,e,i=0){const n=this.normalise(t);let s=0,r;for(const a of this.drawn){const c=Math.max(-1,Math.min(1,n.x*a.direction.x+n.y*a.direction.y+n.z*a.direction.z)),h=Math.max(0,Math.acos(c)-e)/Math.max(a.radiusRad,1e-9),l=a.luminance*ai.profile(h);l<=0||(s+=l,(!r||l>r.light)&&(r={view:a.view,light:l}))}return r&&s>=ai.VISIBLE_CONTRAST*i?r.view:void 0}static profile(t){const e=ai.RINGS;if(t>=e[e.length-1])return 0;let i=0;for(;t>e[i+1];)i++;const n=(t-e[i])/(e[i+1]-e[i]);return ai.COLUMN[i]+(ai.COLUMN[i+1]-ai.COLUMN[i])*n}push(t,e,i,n){const s=t*3;return this.positions[s]=e.x,this.positions[s+1]=e.y,this.positions[s+2]=e.z,this.colors[s]=i[0]*n,this.colors[s+1]=i[1]*n,this.colors[s+2]=i[2]*n,t+1}cross(t,e){return this.normalise({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})}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}}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose(),this.object.removeFromParent()}}class qn{static RADIUS=840;static MAX_SEGMENTS=256;static VERTICES_PER_SEGMENT=12;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;static TRAIN_SHARE=.6;object=new Pe;tiers;trains;positions;colors;shown=0;constructor(){this.object.name="reentries",this.tiers=Po.map(i=>{const n=new Qn(new se,Ot.material(i.size,!1));return Ot.track(n),n.frustumCulled=!1,this.object.add(n),n});const t=qn.MAX_SEGMENTS*qn.VERTICES_PER_SEGMENT;this.positions=new Float32Array(t*3),this.colors=new Float32Array(t*3);const e=new se;e.setAttribute("position",new ce(this.positions,3)),e.setAttribute("color",new ce(this.colors,3)),e.setDrawRange(0,0),this.trains=new xt(e,is.material()),this.trains.frustumCulled=!1,is.track(this.trains),this.object.add(this.trains)}get count(){return this.shown}set(t,e,i,n){const s=this.tiers.map(()=>[]);let r=0,a=0;const c=new st;for(const l of t){const u=i(l.head);if(u<=0)continue;const d=l.magnitude-2.5*Math.log10(u);if(d>e)continue;a++,c.set(l.color);const f=_o(d,e),{x:p,y:g,z:m}=Ke(l.head.altitudeDeg,l.head.azimuthDeg,qn.RADIUS),[v,y,x]=n(l.head,d),M=Math.max(c.r,c.g,c.b)||1;s[Bf(f)].push({x:p,y:g,z:m,r:v*c.r/M,g:y*c.g/M,b:x*c.b/M}),r=this.pushTrain(r,l.train,f,c)}this.shown=a,this.tiers.forEach((l,u)=>{const d=s[u],f=new Float32Array(d.length*3),p=new Float32Array(d.length*3);d.forEach((m,v)=>{f.set([m.x,m.y,m.z],v*3),p.set([m.r,m.g,m.b],v*3)}),l.geometry.dispose();const g=new se;g.setAttribute("position",new ce(f,3)),g.setAttribute("color",new ce(p,3)),l.geometry=g});const h=this.trains.geometry;h.setDrawRange(0,r),h.getAttribute("position").needsUpdate=!0,h.getAttribute("color").needsUpdate=!0}pushTrain(t,e,i,n){const s=e.length-1;for(let r=0;r<s;r++){if(t+qn.VERTICES_PER_SEGMENT>qn.MAX_SEGMENTS*qn.VERTICES_PER_SEGMENT)return t;const a=1-r/s,c=1-(r+1)/s,h=Ke(e[r].altitudeDeg,e[r].azimuthDeg,qn.RADIUS),l=Ke(e[r+1].altitudeDeg,e[r+1].azimuthDeg,qn.RADIUS),u=f=>qn.RADIUS*((qn.MIN_HALF_WIDTH_DEG+qn.BRIGHT_HALF_WIDTH_DEG*i*f)*Math.PI/180),d=f=>qn.TRAIN_SHARE*i*f**1.6;t=this.pushRibbon(t,h,l,u(a),u(c),d(a),d(c),n)}return t}pushRibbon(t,e,i,n,s,r,a,c){const h={x:i.x-e.x,y:i.y-e.y,z:i.z-e.z};if(Math.hypot(h.x,h.y,h.z)<1e-9)return t;const l=this.normalise(this.cross(this.normalise(e),this.normalise(h)));for(const[u,d]of[[-1,0],[0,1]]){const f=this.across(e,l,n,u),p=this.across(i,l,s,u),g=this.across(e,l,n,d),m=this.across(i,l,s,d),v=(y,x)=>y===0?x:0;t=this.push(t,f,v(u,r),c),t=this.push(t,p,v(u,a),c),t=this.push(t,g,v(d,r),c),t=this.push(t,p,v(u,a),c),t=this.push(t,m,v(d,a),c),t=this.push(t,g,v(d,r),c)}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i,n){const s=t*3;this.positions[s]=e.x,this.positions[s+1]=e.y,this.positions[s+2]=e.z;const r=Pt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[s]=r*n.r,this.colors[s+1]=r*n.g,this.colors[s+2]=r*n.b,t+1}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}}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}}dispose(){for(const t of this.tiers)t.geometry.dispose(),t.material.dispose();this.trains.geometry.dispose(),this.trains.material.dispose(),this.object.removeFromParent()}}class Yf{constructor(t){this.state=t}next(){this.state=this.state+1831565813|0;let t=this.state;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}between(t,e){return t+this.next()*(e-t)}}class Ws{static MIN_DURATION_MS=250;static MAX_DURATION_MS=1400;static schedule(t){const{ratePerHour:e,durationMs:i,velocityKmS:n,seed:s}=t;if(e<=0||i<=0)return[];const r=e*i/36e5,a=new Yf(s),c=Math.floor(r),h=c+(a.next()<r-c?1:0),l=[];for(let u=0;u<h;u++){const d=Math.min(1,Math.max(0,(n-20)/52)),f=Ws.MAX_DURATION_MS-d*(Ws.MAX_DURATION_MS-Ws.MIN_DURATION_MS),p=a.between(5,70);l.push({t:a.between(0,i),durationMs:f*a.between(.7,1.3),fromRadiantDeg:p,bearingDeg:a.between(0,360),lengthDeg:Math.sin(p*Math.PI/180)*a.between(8,40)*(.6+d),brightness:a.next()**3}),l.sort((g,m)=>g.t-m.t)}return l}static FAINTEST_MAGNITUDE=6.5;static BRIGHTEST_MAGNITUDE=-4;static magnitudeOf(t){return Ws.FAINTEST_MAGNITUDE-(Ws.FAINTEST_MAGNITUDE-Ws.BRIGHTEST_MAGNITUDE)*t.brightness}static aliveAt(t,e){return t.filter(i=>e>=i.t&&e<=i.t+i.durationMs).map(i=>({meteor:i,progress:(e-i.t)/i.durationMs}))}}class _a{object=new Pe;radius;core;glow;flashKey;static CORE_WIDTH_DEG=.06;static GLOW_WIDTH_DEG=.5;static SEGMENTS=28;static CORE_RELATIVE=1e3;constructor(t){this.radius=t,this.object.name="lightning-bolt",this.core=new ss({color:15659775,transparent:!0,opacity:0,blending:sn,depthWrite:!1,fog:!1}),this.glow=new ss({color:10466559,transparent:!0,opacity:0,blending:sn,depthWrite:!1,fog:!1}),this.object.visible=!1,this.object.renderOrder=5.95}set(t,e,i){if(!t||!t.cloudToGround||e<=.01){this.object.visible=!1;return}const n=`${t.channelSeed}:${Math.round(i)}`;n!==this.flashKey&&this.build(t,i,n),this.core.color.setHex(15659775).multiplyScalar(_a.CORE_RELATIVE*Math.min(1,e*1.4)),this.glow.color.setHex(10466559).multiplyScalar(.1*_a.CORE_RELATIVE*e*.35),this.core.opacity=1,this.glow.opacity=1,this.object.visible=!0}build(t,e,i){this.flashKey=i;for(const h of[...this.object.children])h.geometry.dispose(),this.object.remove(h);const n=new Yf(t.channelSeed),s=Math.atan2(e,t.distanceM)*180/Math.PI,r=this.channel(n,t.azimuthDeg,s,0,1),a=[r],c=1+Math.floor(n.next()*2);for(let h=0;h<c;h++){const l=r[Math.floor(n.between(.15,.5)*r.length)];a.push(this.channel(n,l.azimuthDeg,l.altitudeDeg,l.altitudeDeg*n.between(.3,.7),.5))}for(const h of a)this.object.add(new xt(this.ribbon(h,_a.GLOW_WIDTH_DEG),this.glow)),this.object.add(new xt(this.ribbon(h,_a.CORE_WIDTH_DEG),this.core))}channel(t,e,i,n,s){const r=[],a=i-n;let c=e;for(let h=0;h<=_a.SEGMENTS;h++){const l=i-a*h/_a.SEGMENTS;r.push({azimuthDeg:c,altitudeDeg:l}),c+=t.between(-1,1)*a*.06*s}return r}ribbon(t,e){const i=new Float32Array(t.length*2*3),n=[],s=this.radius*Math.tan(e*Math.PI/180)/2,r=t.map(c=>{const{x:h,y:l,z:u}=Ke(c.altitudeDeg,c.azimuthDeg,this.radius);return new R(h,l,u)});r.forEach((c,h)=>{const l=r[Math.min(h+1,r.length-1)],u=r[Math.max(h-1,0)],f=l.clone().sub(u).normalize().cross(c.clone().normalize()).normalize().multiplyScalar(s);if(i.set([c.x+f.x,c.y+f.y,c.z+f.z],h*6),i.set([c.x-f.x,c.y-f.y,c.z-f.z],h*6+3),h<r.length-1){const p=h*2;n.push(p,p+1,p+2,p+1,p+3,p+2)}});const a=new se;return a.setAttribute("position",new ce(i,3)),a.setIndex(n),a}dispose(){for(const t of this.object.children)t.geometry.dispose();this.core.dispose(),this.glow.dispose(),this.object.removeFromParent()}}class Qi{static MIN_INTERVAL_S=8;static MAX_INTERVAL_S=25;static SEVERE_MIN_INTERVAL_S=2;static SEVERE_MAX_INTERVAL_S=8;static CLOUD_TO_GROUND_FRACTION=.25;static MIN_DISTANCE_M=1e3;static MAX_DISTANCE_M=15e3;static INTERSTROKE_MS=60;static STROKE_DECAY_MS=40;static SOUND_SPEED_M_S=343;static schedule(t){const e=new Yf(t.seed),i=[],{minS:n,maxS:s}=Qi.intervalFor(t.intensity??.5);let r=e.between(0,s)*1e3;for(;r<t.durationMs;){const a=e.next()<Qi.CLOUD_TO_GROUND_FRACTION,c=Qi.MIN_DISTANCE_M,h=Qi.MAX_DISTANCE_M,l=Math.sqrt(e.between(c*c,h*h)),u=a?1+Math.floor(e.next()*4):1,d=[];let f=0;for(let p=0;p<u;p++)d.push({offsetMs:f,intensity:p===0?1:e.between(.4,.9)}),f+=Qi.INTERSTROKE_MS*e.between(.5,1.6);i.push({t:r,azimuthDeg:e.between(0,360),distanceM:l,cloudToGround:a,strokes:d,channelSeed:Math.floor(e.next()*2**31)}),r+=e.between(n,s)*1e3}return i}static intervalFor(t){const e=Math.min(1,Math.max(0,(t-.5)/.5));return{minS:Qi.MIN_INTERVAL_S-e*(Qi.MIN_INTERVAL_S-Qi.SEVERE_MIN_INTERVAL_S),maxS:Qi.MAX_INTERVAL_S-e*(Qi.MAX_INTERVAL_S-Qi.SEVERE_MAX_INTERVAL_S)}}static brightnessAt(t,e){let i=0;for(const n of t.strokes){const s=e-t.t-n.offsetMs;s<0||s>Qi.STROKE_DECAY_MS*6||(i+=n.intensity*Math.exp(-s/Qi.STROKE_DECAY_MS))}return Math.min(1,i)}static endOf(t){const e=t.strokes[t.strokes.length-1];return t.t+e.offsetMs+Qi.STROKE_DECAY_MS*6}static thunderDelayMs(t){return t.distanceM/Qi.SOUND_SPEED_M_S*1e3}}class Hc{static ODD_RADIUS_WEDGES_DEG=[28,56,80];static STANDS_OUT=1.5;static NEIGHBOURHOOD_DEG=2.5;static oddRadiiDeg(){const t=(de.ICE_INDEX_RED+de.ICE_INDEX_BLUE)/2;return Hc.ODD_RADIUS_WEDGES_DEG.map(e=>de.minimumDeviationDeg(e,t)).filter(e=>Number.isFinite(e))}static at(t,e,i,n){const s=Math.PI/180,r=t,a=Math.abs(i),c=Math.sin(r*s)*Math.sin(e*s)+Math.cos(r*s)*Math.cos(e*s)*Math.cos(a*s),h=Math.acos(Math.max(-1,Math.min(1,c)))/s,l=Math.atan2(Math.sin(a*s)*Math.cos(e*s),Math.cos(r*s)*Math.sin(e*s)-Math.sin(r*s)*Math.cos(e*s)*Math.cos(a*s))/s,u=Math.abs(e-r),d=()=>{const y=n(e,a);if(!(y>0))return!1;const x=Hc.NEIGHBOURHOOD_DEG,M=1/Math.max(.2,Math.cos(e*s)),b=[n(e+x,a),n(e-x,a),n(e,a+x*M),n(e,Math.max(0,a-x*M))].sort((S,E)=>S-E);return y>b[1]*Hc.STANDS_OUT},f=()=>{const y=x=>{const M=h*s,b=x*s,S=Math.cos(M)*Math.cos(r*s)-Math.sin(M)*Math.cos(b)*Math.sin(r*s),E=Math.sin(M)*Math.sin(b),w=Math.cos(M)*Math.sin(r*s)+Math.sin(M)*Math.cos(b)*Math.cos(r*s);return n(Math.asin(Math.max(-1,Math.min(1,w)))/s,Math.abs(Math.atan2(E,S)/s))};return(y(70)+y(110)+y(250)+y(290))/4},p=(y,x=0)=>{if(d())return x>0&&!(n(e,a)>f()*x)?void 0:y};if(r>0&&r<de.PARHELIA_MAX_SUN_ALTITUDE_DEG&&u<2.5){const y=de.parheliaAzimuthDeg(r);if(y!==void 0&&a>=y-1.2&&a<=y+7){const x=p({id:"parhelion",angleDeg:de.parheliaDistanceDeg(r)},2.5);if(x)return x}}if(r>0&&u<2.5&&Math.abs(a-120)<4){const y=p({id:"parhelion120",angleDeg:120},0);if(y)return y}const g=de.circumzenithalAltitudeDeg(r);if(g!==void 0&&e>g-2&&e<g+4){const y=p({id:"circumzenithal",angleDeg:g});if(y)return y}if(r>de.PLATE_END_FACE_LIMIT_DEG){const y=de.circumzenithalAltitudeDeg(90-r);if(y!==void 0){const x=90-y;if(e>x-4&&e<x+2){const M=p({id:"circumhorizontal",angleDeg:x});if(M)return M}}}if(a<3&&r>0){if(e>r+3&&e<r+25&&r<de.PILLAR_MAX_SOURCE_ALTITUDE_DEG){const y=p({id:"pillar"});if(y)return y}if(Math.abs(e+r)<3){const y=p({id:"subsun"});if(y)return y}}const m=de.halo22();if(h>m.redAngleDeg-.6&&h<m.blueAngleDeg+2.5){const y=Math.abs(l)<50,x=Math.abs(l)>130;if(y||x){const M=p({id:y?"upperTangentArc":"lowerTangentArc",angleDeg:m.angleDeg},1.5);if(M)return M}}for(const y of Hc.oddRadiiDeg())if(h>y-.6&&h<y+1.8){const x=p({id:"oddRadius",angleDeg:y});if(x)return x}if(h>m.redAngleDeg-.6&&h<m.blueAngleDeg+2.5){const y=p({id:"halo22",angleDeg:m.angleDeg});if(y)return y}const v=de.halo46();if(h>v.redAngleDeg-.6&&h<v.blueAngleDeg+3){const y=p({id:"halo46",angleDeg:v.angleDeg});if(y)return y}if(r>0&&u<1.2){const y=n(e,a),x=Math.max(n(e+3,a),n(e-3,a));if(y>0&&y>x*2)return{id:"parhelicCircle",angleDeg:r}}}}class Zn{static RED_NM=656.3;static BLUE_NM=435.8;static ANCHOR_RED=1.3067;static ANCHOR_BLUE=1.317;static B=(Zn.ANCHOR_BLUE-Zn.ANCHOR_RED)/(1/(Zn.BLUE_NM*Zn.BLUE_NM)-1/(Zn.RED_NM*Zn.RED_NM));static A=Zn.ANCHOR_RED-Zn.B/(Zn.RED_NM*Zn.RED_NM);static indexAt(t){return Zn.A+Zn.B/(t*t)}}class fr{static MAX_FACES=20;normals=new Float64Array(fr.MAX_FACES*3);offsets=new Float64Array(fr.MAX_FACES);faceCount=8;radius=1;set(t,e,i,n,s,r,a=0){let c=0,h=0,l=0;Math.abs(i)<.9?(c=-e,h=t,l=0):(c=0,h=-i,l=e);const u=Math.hypot(c,h,l)||1;c/=u,h/=u,l/=u;const d=e*l-i*h,f=i*c-t*l,p=t*h-e*c,g=s/2,m=r/2;for(let v=0;v<6;v++){const y=n+v*Math.PI/3,x=Math.cos(y),M=Math.sin(y);this.normals[v*3]=c*x+d*M,this.normals[v*3+1]=h*x+f*M,this.normals[v*3+2]=l*x+p*M,this.offsets[v]=g}if(this.normals[18]=t,this.normals[19]=e,this.normals[20]=i,this.offsets[6]=m,this.normals[21]=-t,this.normals[22]=-e,this.normals[23]=-i,this.offsets[7]=m,this.faceCount=8,a>0){const v=fr.PYRAMID_TILT,y=Math.cos(v),x=Math.sin(v),M=Math.min(m,a*g*Math.tan(v)),b=m-M,S=y*b+x*g;for(let E=0;E<6;E++){const w=E*3,_=(8+E)*3,D=(14+E)*3;this.normals[_]=y*t+x*this.normals[w],this.normals[_+1]=y*e+x*this.normals[w+1],this.normals[_+2]=y*i+x*this.normals[w+2],this.normals[D]=-y*t+x*this.normals[w],this.normals[D+1]=-y*e+x*this.normals[w+1],this.normals[D+2]=-y*i+x*this.normals[w+2],this.offsets[8+E]=S,this.offsets[14+E]=S}this.faceCount=fr.MAX_FACES}this.radius=Math.hypot(g*2/Math.sqrt(3),m)}static rollToward(t,e,i,n,s,r){let a,c,h;Math.abs(i)<.9?(a=-e,c=t,h=0):(a=0,c=-i,h=e);const l=Math.hypot(a,c,h)||1;a/=l,c/=l,h/=l;const u=e*h-i*c,d=i*a-t*h,f=t*c-e*a;return Math.atan2(n*u+s*d+r*f,n*a+s*c+r*h)}get aimRadius(){return this.radius}trace(t,e,i,n,s,r,a){let c=-e,h=t,l=0,u=Math.hypot(c,h,l);u<1e-6&&(c=1,h=0,l=0,u=1),c/=u,h/=u,l/=u;const d=e*l-i*h,f=i*c-t*l,p=t*h-e*c,g=c*n+d*s-t*this.radius*2,m=h*n+f*s-e*this.radius*2,v=l*n+p*s-i*this.radius*2;let y=-1,x=-1/0,M=1/0;for(let q=0;q<this.faceCount;q++){const et=this.normals[q*3],at=this.normals[q*3+1],$t=this.normals[q*3+2],fe=et*t+at*e+$t*i,Gt=this.offsets[q]-(et*g+at*m+$t*v);if(fe>1e-9){const K=Gt/fe;K<M&&(M=K)}else if(fe<-1e-9){const K=Gt/fe;K>x&&(x=K,y=q)}else if(Gt<0)return 0}if(y<0||x>=M)return 0;let b=0;const S=this.normals[y*3],E=this.normals[y*3+1],w=this.normals[y*3+2],_=-(S*t+E*e+w*i),D=cf.reflectance(_,1,r);a[b].x=t+2*_*S,a[b].y=e+2*_*E,a[b].z=i+2*_*w,a[b].weight=D,b++;const I=1/r,O=Math.sqrt(Math.max(0,1-I*I*(1-_*_)));let L=I*t+(I*_-O)*S,N=I*e+(I*_-O)*E,P=I*i+(I*_-O)*w,z=g+t*x,B=m+e*x,X=v+i*x,J=1-D;for(let q=0;q<fr.MAX_BOUNCES&&J>fr.MIN_WEIGHT;q++){let et=-1,at=1/0;for(let G=0;G<this.faceCount;G++){const kt=this.normals[G*3],Vt=this.normals[G*3+1],Ft=this.normals[G*3+2],Tt=kt*L+Vt*N+Ft*P;if(Tt<=1e-9)continue;const qt=(this.offsets[G]-(kt*z+Vt*B+Ft*X))/Tt;qt>1e-9&&qt<at&&(at=qt,et=G)}if(et<0)break;const $t=this.normals[et*3],fe=this.normals[et*3+1],Gt=this.normals[et*3+2],K=$t*L+fe*N+Gt*P,ot=r*Math.sqrt(Math.max(0,1-K*K));if(z+=L*at,B+=N*at,X+=P*at,ot<1){const G=Math.sqrt(Math.max(0,1-ot*ot)),kt=cf.reflectance(K,r,1);if(a[b].x=r*L-(r*K-G)*$t,a[b].y=r*N-(r*K-G)*fe,a[b].z=r*P-(r*K-G)*Gt,a[b].weight=J*(1-kt),b++,b>=a.length)return b;J*=kt}const rt=2*K;L-=rt*$t,N-=rt*fe,P-=rt*Gt}return b}static MAX_BOUNCES=6;static PYRAMID_TILT=62*Math.PI/180;static MIN_WEIGHT=1e-4}class ke{static AZIMUTH_BINS=512;static ALTITUDE_BINS=512;static DEFAULT_POPULATIONS=[{orientation:"tumbling",widthMicrons:50,lengthMicrons:50,share:.48},{orientation:"plate",widthMicrons:100,lengthMicrons:15,share:.27},{orientation:"column",widthMicrons:40,lengthMicrons:120,share:.18},{orientation:"parry",widthMicrons:40,lengthMicrons:120,share:.02},{orientation:"pyramidal",widthMicrons:40,lengthMicrons:120,share:.03,capFraction:.5},{orientation:"lowitz",widthMicrons:100,lengthMicrons:15,share:.02}];static DEFAULT_RARE_SHARE=Qb;static populationsFor(t){const e=Math.min(.9,Math.max(0,t));if(Math.abs(e-ke.DEFAULT_RARE_SHARE)<1e-9)return ke.DEFAULT_POPULATIONS;const i=(1-e)/(1-ke.DEFAULT_RARE_SHARE);return ke.DEFAULT_POPULATIONS.map(n=>n.orientation==="pyramidal"||n.orientation==="lowitz"?{...n,share:n.share/ke.DEFAULT_RARE_SHARE*e}:{...n,share:n.share*i})}populations=ke.DEFAULT_POPULATIONS;populationTotal=1;static WORST_TILT_DEG=180;static BEST_TILT_DEG=.5;static SOURCE_RADIUS_DEG=.265;static UNDEVIATED_DEG=.6;crystal=new fr;emergent=Array.from({length:fr.MAX_BOUNCES+2},()=>({x:0,y:0,z:0,weight:0}));tally=new Float32Array(ke.AZIMUTH_BINS*ke.ALTITUDE_BINS*3);radiance=new Float32Array(ke.AZIMUTH_BINS*ke.ALTITUDE_BINS*3);scratch=new Float32Array(ke.AZIMUTH_BINS*ke.ALTITUDE_BINS*3);seed=1;spare=0;hasSpare=!1;altitude=0;tilt=0;alignment=0;traced=0;begin(t,e,i=2654435769,n=ke.DEFAULT_POPULATIONS){this.populations=n,this.populationTotal=n.reduce((r,a)=>r+a.share,0)||1,this.seed=i>>>0||1,this.hasSpare=!1,this.tally.fill(0),this.traced=0,this.altitude=t*Math.PI/180,this.alignment=Math.min(1,Math.max(0,e));const s=ke.WORST_TILT_DEG*(ke.BEST_TILT_DEG/ke.WORST_TILT_DEG)**this.alignment;this.tilt=s*Math.PI/180}trace(t){const e=ke.AZIMUTH_BINS,i=ke.ALTITUDE_BINS,n=this.tally,s=ke.SOURCE_RADIUS_DEG*Math.PI/180,r=Math.cos(ke.UNDEVIATED_DEG*Math.PI/180),a=this.altitude;for(let c=0;c<t;c++){const h=this.pickPopulation();this.orient(h,this.tilt);const l=this.random()*2*Math.PI,u=s*Math.sqrt(this.random()),d=a+u*Math.sin(l),f=u*Math.cos(l)/Math.max(.05,Math.cos(a)),p=-Math.cos(d)*Math.cos(f),g=-Math.cos(d)*Math.sin(f),m=-Math.sin(d),v=this.crystal.aimRadius,y=(this.random()*2-1)*v,x=(this.random()*2-1)*v,M=4*v*v,b=en.SAMPLES[this.random()*en.SAMPLES.length|0],S=this.crystal.trace(p,g,m,y,x,Zn.indexAt(b.wavelengthNm),this.emergent);for(let E=0;E<S;E++){const w=this.emergent[E],_=Math.hypot(w.x,w.y,w.z);if(_<1e-9||w.weight<=0)continue;const D=w.x/_,I=w.y/_,O=w.z/_;if(D*p+I*g+O*m>r)continue;const L=Math.asin(Math.max(-1,Math.min(1,-O))),N=Math.abs(Math.atan2(-I,-D)),P=Math.min(e-1,N/Math.PI*e|0),B=(Math.min(i-1,(L+Math.PI/2)/Math.PI*i|0)*e+P)*3,X=w.weight*M*en.SAMPLES.length;n[B]+=X*b.r,n[B+1]+=X*b.g,n[B+2]+=X*b.b}}this.traced+=t}get tracedRays(){return this.traced}harvest(){const t=ke.AZIMUTH_BINS,e=ke.ALTITUDE_BINS;return this.toRadiance(t,e),this.smooth(t,e),{width:t,height:e,data:this.radiance,sourceAltitudeDeg:this.altitude*180/Math.PI,alignment:this.alignment,rays:this.traced}}compute(t,e,i,n,s){return this.begin(t,e,n,s),this.trace(i),this.harvest()}toRadiance(t,e){const i=2*Math.PI/t,n=Math.max(1,this.traced),s=4*ke.REFERENCE_MICRONS*ke.REFERENCE_MICRONS;for(let r=0;r<e;r++){const a=Math.sin(r/e*Math.PI-Math.PI/2),c=Math.sin((r+1)/e*Math.PI-Math.PI/2),h=1/(i*(c-a)*n*s);for(let l=0;l<t;l++){const u=(r*t+l)*3;this.radiance[u]=this.tally[u]*h,this.radiance[u+1]=this.tally[u+1]*h,this.radiance[u+2]=this.tally[u+2]*h}}}static REFERENCE_MICRONS=50;smooth(t,e){const i=this.scratch,n=this.radiance;i.set(n);for(let r=0;r<e;r++){const a=r*t*3;for(let c=0;c<3;c++){let h=i[a+c];for(let l=0;l<t;l++){const u=a+l*3+c,d=l+1<t?i[u+3]:i[u];n[u]=(h+2*i[u]+d)/4,h=i[u]}}}i.set(n);const s=t*3;for(let r=0;r<e;r++){const a=r>0?-s:0,c=r+1<e?s:0,h=r*s;for(let l=h;l<h+s;l++)n[l]=(i[l+a]+2*i[l]+i[l+c])/4}}pickPopulation(){const t=this.random()*this.populationTotal;let e=0;for(const i of this.populations)if(e+=i.share,t<=e)return i;return this.populations[this.populations.length-1]}orient(t,e){const i=this.random()*2*Math.PI;let n=this.random()*2*Math.PI,s=0,r=0,a=1;switch(t.orientation){case"pyramidal":case"tumbling":{a=this.random()*2-1;const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"plate":{a=this.spreadAboutAnAxis(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"column":case"parry":{a=this.spreadAboutAPlane(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i),t.orientation==="parry"&&(n=Math.PI/2+this.gaussian()*e);break}}if(t.orientation==="lowitz"){const c=this.spreadAboutAPlane(e),h=Math.sqrt(Math.max(0,1-c*c)),l=h*Math.cos(i),u=h*Math.sin(i),d=c;let f=-d*l,p=-d*u,g=1-d*d;const m=Math.hypot(f,p,g)||1;f/=m,p/=m,g/=m;const v=u*g-d*p,y=d*f-l*g,x=l*p-u*f,M=this.random()*2*Math.PI;s=f*Math.cos(M)+v*Math.sin(M),r=p*Math.cos(M)+y*Math.sin(M),a=g*Math.cos(M)+x*Math.sin(M),n=fr.rollToward(s,r,a,l,u,d)+Math.PI/6}this.crystal.set(s,r,a,n,t.widthMicrons,t.lengthMicrons,t.capFraction??0)}random(){this.seed=this.seed+1831565813>>>0;let t=this.seed;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}spreadAboutAnAxis(t){const e=1/Math.max(1e-6,t*t),i=Math.max(1e-12,this.random()),n=1+Math.log(i+(1-i)*Math.exp(-2*e))/e;return Math.max(-1,Math.min(1,n))}spreadAboutAPlane(t){for(let e=0;e<8;e++){const i=this.gaussian()*t;if(i>=-1&&i<=1)return i}return this.random()*2-1}gaussian(){if(this.hasSpare)return this.hasSpare=!1,this.spare;const t=Math.sqrt(-2*Math.log(Math.max(1e-12,this.random()))),e=2*Math.PI*this.random();return this.spare=t*Math.sin(e),this.hasSpare=!0,t*Math.cos(e)}}class xC{static fromRadiance(t,e){const i=gs.toHalfFloat(1);for(let n=0,s=0;s<t.length;n+=4,s+=3)e[n]=gs.toHalfFloat(t[s]),e[n+1]=gs.toHalfFloat(t[s+1]),e[n+2]=gs.toHalfFloat(t[s+2]),e[n+3]=i}}class Di{static RADIUS=880;static RAYS=9e5;static RAYS_PER_BATCH=2e3;static BUDGET_MS=6;static URGENT_BUDGET_MS=40;static ALTITUDE_STEP_DEG=1;static ALIGNMENT_STEP=.05;static LEAP_ALTITUDE_DEG=5;static LEAP_ALIGNMENT=.25;static GAIN=.55;setCloudOffset(t){this.material.uniforms.uFieldOffset.value.copy(t)}object;material;sky=new ke;texture;texels;mappedAltitudeDeg=Number.NaN;mappedAlignment=Number.NaN;mappedRare=Number.NaN;tracing=!1;everDisplayed=!1;urgent=!1;workHandle;onRepaint;constructor(){const t=ke.AZIMUTH_BINS,e=ke.ALTITUDE_BINS;this.texels=new Uint16Array(t*e*4),this.texture=new Ms(this.texels,t,e,qi,He),this.texture.minFilter=we,this.texture.magFilter=we,this.texture.wrapS=Oi,this.texture.wrapT=Oi,this.texture.needsUpdate=!0,this.material=new Ae({uniforms:{uSource:{value:new R(0,1,0)},uUp:{value:new R(0,1,0)},uStrength:{value:0},uTint:{value:new R(1,.97,.92)},uIceCover:{value:0},uIceHeight:{value:1},uFieldOffset:{value:new R},uMap:{value:this.texture},uGain:{value:Di.GAIN}},vertexShader:`
|
|
8278
8278
|
varying vec3 vDirection;
|
|
8279
8279
|
void main() {
|
|
8280
8280
|
vDirection = normalize((modelMatrix * vec4(position, 1.0)).xyz - cameraPosition);
|
|
@@ -8311,7 +8311,7 @@ uniform float uWindowLuminance;
|
|
|
8311
8311
|
varying float vLitRank;
|
|
8312
8312
|
${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
|
|
8313
8313
|
totalEmissiveRadiance *= step(vLitRank, uLitShare) * uWindowLuminance * ${vt.WINDOW_VARIETY_GLSL};`)}`},r.customProgramCacheKey=()=>"facade-lit-windows";const a=new xt(s,r);return a.castShadow=!0,a.receiveShadow=!0,e.add(a),e}static CLOSED_AT_NIGHT_SHARE=.2;static litWindowShare={value:0};static WINDOW_LUMINANCE_CD_M2=15;static ROOM_LIGHT_K=2900;static COLD_ROOM_LIGHT_K=4e3;static windowLuminance={value:0};static get WINDOW_VARIETY_GLSL(){const t=n=>`vec3(${n.map(s=>s.toFixed(4)).join(", ")})`,e=nh.ofTemperature(vt.ROOM_LIGHT_K),i=nh.ofTemperature(vt.COLD_ROOM_LIGHT_K);return`(mix(0.35, 2.0, fract(vLitRank * 97.13) * fract(vLitRank * 97.13)) * mix(${t(e)}, ${t(i)}, step(0.86, fract(vLitRank * 53.71))))`}static setWindowLuminance(t){vt.windowLuminance.value=vt.WINDOW_LUMINANCE_CD_M2*t}static setLitWindowShare(t){vt.litWindowShare.value=Math.max(0,Math.min(1,t))}static build(t,e){const i=vt.hasFacade(t)?vt.buildFacade(t):t.kind==="building"?l2(t.floors??Hd,t.windows,t.observerSide,t.occupiedFloor,t.observerFacing):t.kind==="tree"?d2():t.kind==="shrub"?u2():t.kind==="bridge"?kC(t):t.kind==="wire"?UC(t):t.kind==="wall"?Xi.build(t):t.kind==="crop"?p2():t.kind==="terrace"?XC():t.kind==="mound"?m2():t.kind==="streetlight"?g2(e,t.lamp?.mount,t.lamp):t.kind==="trafficlight"?ve.trafficLight(re.isPedestrian(t.lights)):t.kind==="crossing"?ve.crossing(vt.sizeOf(t).widthM,vt.sizeOf(t).lengthM):t.kind==="roadsign"?ve.roadSign(t.sign):t.kind==="vehicle"?v2(e,t.windows,t.observerSide,t.observerFacing):t.kind==="aircraft"?S2():t.kind==="entity"?b2():rg();t.color&&this.paint(i,t.color);const n=this.scaleFor(t),s=new Pe;return t.kind==="building"&&t.roof&&this.addRoof(s,t),i.name=vt.BODY_NAME,i.scale.copy(n),s.add(i),t.headingDeg!==void 0&&(s.rotation.y=-t.headingDeg*Z0),this.addLights(s,t.lights),vt.fitLights(s,t,t.sizeM??{}),s}static scaleFor(t){const e=t.sizeM;if(!e||vt.hasFacade(t)||t.kind==="bridge"||t.kind==="wire"||t.kind==="terrace"||t.kind==="wall"||t.kind==="crossing")return new R(1,1,1);const i=this.naturalSize(t.kind,t.floors);return new R(e.widthM===void 0?1:tp(e.widthM,i.widthM),e.heightM===void 0?1:tp(t.kind==="building"?this.wallHeightOf(t,e.heightM):e.heightM,i.heightM),e.lengthM===void 0?1:tp(e.lengthM,i.lengthM))}static naturalSize(t,e){const i=t==="building"?Math.max(1,(e??Hd)+1):0;if(t==="bridge")return di.NATURAL_SIZE;if(t==="wire")return Io.NATURAL_SIZE;if(t==="terrace"||t==="wall")return{widthM:1,lengthM:1,heightM:1};if(t==="crossing")return{widthM:6,lengthM:2.5,heightM:ve.CROSSING_LIFT_M};const n=`${t}:${i}`,s=M2.get(n);if(s)return s;const r=t==="building"?l2(i-1,void 0,void 0,void 0):t==="tree"?d2():t==="shrub"?u2():t==="crop"?p2():t==="mound"?m2():t==="streetlight"?g2(!1):t==="trafficlight"?ve.trafficLight(!1):t==="roadsign"?ve.roadSign(void 0):t==="vehicle"?v2(!1,void 0,void 0):t==="aircraft"?S2():t==="entity"?b2():rg(),a=new Ki().setFromObject(r),c={widthM:a.max.x-a.min.x,heightM:a.max.y-a.min.y,lengthM:a.max.z-a.min.z};return this.dispose(r),M2.set(n,c),c}static usesModel(t){return Gd(t)!==void 0&&!(t.observerSide!==void 0&&ch(t.kind))}static applyModel(t,e,i,n={}){const s=this.bodyOf(t),r=new Pe;r.name=vt.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*Z0,i.updateMatrixWorld(!0);const a=new Ki().setFromObject(i),c={lengthM:a.max.z-a.min.z,heightM:a.max.y-a.min.y,widthM:a.max.x-a.min.x},h=e.kind==="tree"&&e.sizeM?.heightM!==void 0?{heightM:e.sizeM.heightM}:e.sizeM,l=y2(h,c)??y2(n.depictedSizeM,c)??1;i.scale.multiplyScalar(l);const u=a.getCenter(new R).multiplyScalar(l);i.position.x-=u.x,i.position.z-=u.z,i.position.y-=e.kind==="aircraft"?u.y:a.min.y*l,i.traverse(d=>{d instanceof xt&&(d.castShadow=!0,d.receiveShadow=!0)}),r.add(i),e.kind==="tree"&&r.add(vt.trunkShadow(c.heightM*l)),s.parent?(s.parent.add(r),s.removeFromParent()):t.add(r),this.dispose(s),vt.fitLights(t,e,{widthM:c.widthM*l,heightM:c.heightM*l,lengthM:c.lengthM*l})}static fitLights(t,e,i){const n=Vd.byId(Gc.rigOf(e)||void 0)?.referenceSizeM;if(!n||!e.lights)return;const s=(l,u)=>l===void 0||u===0?1:l/u,r=s(i.widthM,n.widthM),a=s(i.heightM,n.heightM),c=s(i.lengthM,n.lengthM),h=new Map(e.lights.map(l=>[l.id,l.offsetM]));t.traverse(l=>{const u=l.userData.lightId,d=u===void 0?void 0:h.get(u);d&&l.position.set(d.x*r,d.y*a,d.z*c)})}static trunkShadow(t){vt.trunkProxy??={geometry:new Cn(1,1.15,1,8),material:new ss({colorWrite:!1,depthWrite:!1})};const e=new xt(vt.trunkProxy.geometry,vt.trunkProxy.material),i=Math.min(.3,Math.max(.12,t*.035)),n=t*.45;return e.scale.set(i,n,i),e.position.y=n/2,e.castShadow=!0,e.receiveShadow=!1,e.userData.sharedModel=!0,e.name="trunk-shadow",e}static trunkProxy;static sizeOf(t){const e=this.naturalSize(t.kind,t.floors);return{widthM:t.sizeM?.widthM??e.widthM,lengthM:t.sizeM?.lengthM??e.lengthM,heightM:t.sizeM?.heightM??e.heightM}}static addLights(t,e){for(const i of e??[]){const n=TC(i.color),s=re.figureOf(i),r=s?ve.pedestrianFigure(s,1.8*(i.radiusM??J0)):new Hi(i.radiusM??J0,8,6),a=Fe(t,r,n,i.offsetM.y,!0);a.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),a.userData={emissive:!0,lightId:i.id,lightColor:n},a.visible=!1;const c=a.material;$x.apply(c),c.transparent=!0,c.depthWrite=!1,c.fog=!1}}static setLights(t,e,i,n,s=0,r=1,a=bC,c=[1,1,1],h){if(!e||e.length===0)return;const l=new Map(e.map(d=>[d.id,d]));let u;h&&e.some(d=>d.beamDeg!==void 0)&&(t.updateWorldMatrix(!0,!1),u=t.worldToLocal(vt.eyeScratch.copy(h)));for(const d of t.children){if(!(d instanceof xt))continue;const f=d.userData.lightId;if(!f)continue;const p=l.get(f);if(!p)continue;const g=s>0?Ty(p,i,i+s):cS(p,i)?1:0,m=u&&p.beamDeg!==void 0?vt.beamShare(p.beamDeg,d.position,u):1;d.visible=g>0&&m>0;const v=p.radiusM??J0,y=Math.max(1,n*a/v),x=v*y,M=r/(Math.PI*x*x),b=d.material,S=d.userData.lightColor;if(S){const E=g*m*wC*(p.intensity??1)*M,w=[S[0]*E*c[0],S[1]*E*c[1],S[2]*E*c[2]],_=Math.min(1,c2/Math.max(w[0],w[1],w[2],1e-30));b.color.setRGB(w[0]*_,w[1]*_,w[2]*_)}d.scale.setScalar(y)}}static eyeScratch=new R;static beamShare(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=i.z-e.z,a=Math.hypot(n,s,r);if(a===0)return 1;const c=-r/a;if(c<=0)return 0;const h=Math.log(.5)/Math.log(Math.cos(t*Math.PI/180));return Math.pow(c,h)}static setLit(t,e,i,n=1,s){const[r,a,c]=e==="streetlight"?[SC*vt.lampShare(s),EC,vt.lampHue(s)]:[AC,_C,Mb],h=i?r*n/(Math.PI*a*a):0,l=Math.min(1,c2/Math.max(c[0]*h,c[1]*h,c[2]*h,1e-30)),u=[c[0]*h*l,c[1]*h*l,c[2]*h*l];t.traverse(d=>{const f=d.userData;!(d instanceof xt)||!f.emissive||f.lightId||(d.material instanceof Cs?d.material.emissive.setRGB(...u):d.material.color.setRGB(...u))})}static REFERENCE_LUMENS=1e4;static lampShare(t){return t?.lumens?t.lumens/vt.REFERENCE_LUMENS:1}static lampHue(t){return t?.colorTemperatureK?nh.ofTemperature(t.colorTemperatureK):IC}static dispose(t){t.traverse(e=>{if(!(e instanceof xt))return;if(e.userData.sharedModel){for(const n of e.userData.tintedMaterials??[])n.dispose();return}e.geometry.dispose();const i=e.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const ip="https://ufoathome.org/models/index.json";class Ml{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??qC()}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(`
|
|
8314
|
-
`);let e=Ml.shared.get(t);return e||(e=this.fetchFirstAvailable(),Ml.shared.set(t,e),e.then(i=>{i.length===0&&Ml.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 qC(){const o=`?v=${encodeURIComponent("0.150.
|
|
8314
|
+
`);let e=Ml.shared.get(t);return e||(e=this.fetchFirstAvailable(),Ml.shared.set(t,e),e.then(i=>{i.length===0&&Ml.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 qC(){const o=`?v=${encodeURIComponent("0.150.2")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==ip?[t,ip]:[ip]).map(e=>e+o)}const ZC=[{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 Ml}];async function np(o){const{GLTFLoader:t}=await Ee(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BGUT3v5v.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 Ab=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class ps{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new xt(new Wn(2,2),new Ae({uniforms:{uColor:{value:new st(0,0,0)},uRadius:{value:1}},vertexShader:ps.VERTEX,fragmentShader:ps.FRAGMENT,transparent:!0,depthWrite:!1,blending:sn,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*ps.MIN_ANGLE_RAD),r=ps.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(ps.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(ps.MAX_SHARE*ps.FILL*Math.PI))}static VERTEX=`
|
|
8315
8315
|
uniform float uRadius;
|
|
8316
8316
|
varying vec2 vOffset;
|
|
8317
8317
|
void main() {
|
|
@@ -8954,7 +8954,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
8954
8954
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
8955
8955
|
gl_FragColor = vec4(light, 1.0);
|
|
8956
8956
|
}
|
|
8957
|
-
`,transparent:!0,blending:sn,depthWrite:!1,side:xi,fog:!1});this.object=new xt(new Hi(s1.RADIUS,128,32,0,Math.PI*2,0,De.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<De.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=gs.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=gs.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class vf{constructor(t){this.generator=t}static SIZE=128;target=new Ul(vf.SIZE,{type:He,generateMipmaps:!1,minFilter:we,magFilter:we});camera=new Hg(.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 _n{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){_n.install(),this.generator=new Rm(t),this.eye=new vf(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],h,l=_n.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const u=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new vf(this.generator),this.probes.set(m.id,v)),u.push({probe:v,reflector:m})}const d=performance.now(),f=()=>u.filter(({probe:m})=>m.capturedVersion!==a),p=f().filter(({probe:m})=>d-m.capturedAtMs>=l);if(p.length>0){const m=p.reduce((v,y)=>y.probe.capturedAtMs<v.probe.capturedAtMs?y:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(t,e,v,[m.reflector.holder,...s]),_n.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(t,e,i,[...s,...c]),h?.(m.probe.sharp),_n.decor=m.probe.filtered;for(const v of r)_n.reflectOn(v,m.probe);for(const v of n)v.shiny||_n.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=a}const g=f();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>l-(d-m.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:_n.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof zl?e.sharp&&s.setSurroundings(e.sharp):s instanceof Da&&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(_n.installed)return;_n.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!ae.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}ae.lights_fragment_maps=ae.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function t6(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 Xu=900,sp=1,A2=4,rp=5,$u=.5,Yu=Si.GROUND_RADIUS_M;function _2(o){return Si.groundRadiusFor(o)}const ap=.5,op=850,cp=.03,e6=.015,$n=850,Xh=300,va=120,i6=700,n6=3.5,Ku=20,T2=.04,s6=.26,R2=4,hp=1.5,I2=-1,r6=.01,yd=-4,a6=2,o6=20,qu=2600,c6=.97,h6=.38,$h=yd,l6=8,u6=2,D2=1500,d6=.7,f6=.3,p6=.32,m6=.65,C2=2.4,g6=.9,v6=400,M6=[0,45,90,135,180,225,270,315],y6=2,x6=16,O2=4e3,P2=880,Zu=40,L2=60,b6=10,w6=1,S6=Si.REBUILD_DISTANCE_M,N2=.265,k2=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*N2,Math.sin(e)*N2]})],lp=700,up=250/og,E6=12,U2=5,dp=6,Ja=[.92,.92,.95],fp=[.15,.15,.19],pp={snow:{fallSpeedMPerS:2,size:.3,color:new st(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new st(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Dc=0,mp=0,A6=150,gp=3e3,Yh=20,_6=15,F2=Dc,T6=40,z2=1,R6=9;function vp(o){return z2+(R6-z2)*o}const B2=new st(.75,.82,.92),I6=10,D6=.5;function H2(o){return cr(o/I6,D6,1)}const ja=200,G2=.18,V2=.32,C6=.35,W2=new st(.85,.9,.98),X2=5,$2=.85,Y2=.01;function O6(o,t,e=1){return Math.round(o*(Y2+(1-Y2)*t)*e)}function P6(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 K2=230,q2=.7,Z2=.05,L6=.6,N6=.7,k6=.15,J2=.35,U6=3,F6=1/12,z6=.5,sr=new st(.82,.86,1),B6=2500,H6=1.6,Mp=15,G6={Venus:new st(1,.96,.85),Mars:new st(1,.55,.4),Jupiter:new st(.95,.87,.72),Saturn:new st(.92,.86,.68)};class wt{renderer;scene=new Zs;phenomena=new zs(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Pe;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()+O2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),O2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ge;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new nt;decorModelProvider=ZC[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new ue(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale);bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??wt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*wt.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 fM(16777215,0);celestialLightTarget=new bi;skyLight=new WA(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 md;weather=_f;observerElevationM=0;siteElevationM=0;air=new As;groundRadius=Yu;terrainRadius=Yu;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new R;cloudFieldOffset=new R;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new R;rainLastVerticalFacing=-1;rainViewportSize=new nt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new fM(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new md;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new md;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=fi.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 Bl;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Gy()){this.renderer=new rI({canvas:t,antialias:!0}),this.resolution=new ze(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=al,this.camera=new ts(60,t.width/Math.max(t.height,1),.1,Xu*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=-va,this.celestialLight.shadow.camera.right=va,this.celestialLight.shadow.camera.top=va,this.celestialLight.shadow.camera.bottom=-va,this.celestialLight.shadow.camera.near=$n-Xh,this.celestialLight.shadow.camera.far=$n+Xh,this.celestialLight.shadow.bias=-.03/(2*Xh),this.celestialLight.shadow.normalBias=T2,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(sr),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 ye(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*up,0,t.z*up);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)*mi,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*mi;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*mi,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(_2(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Yu),this.camera.far=Math.max(Xu*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;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=wt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Si.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ie(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.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{this.terrainProviders===d&&this.setTerrainOrigin(t,e,i)}),wt.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}=ie(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<S6*(r/Yu))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ie(t,e,c.lat,c.lng).x,ie(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(a2(t,e,this.terrainProviders,r,{route:this.observerRoute}),wt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:g})=>{if(l!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const m=this.terrainMesh,v=this.terrainMeshOrigin,y=v?ie(t,e,v.lat,v.lng):void 0;m&&y&&Math.hypot(y.x,y.z)<=a&&(u.position.y=m.position.y+this.groundYOfPatch(m,y.x,y.z)),m&&v&&y&&Math.hypot(y.x,y.z)<=a?this.crossfadeTerrain(u,m,v):this.disposeMesh(this.terrainMesh),u.renderOrder=w6,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,g),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=Si.beamReachFor(this.beams,{lat:t,lng:e});if(!Si.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:g}=ie(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,g)<i*wt.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??Si.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(a2(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*wt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),wt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=wt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-wt.FAR_RING_DROP_M;const g=p.material;g.polygonOffset=!0,g.polygonOffsetFactor=2,g.polygonOffsetUnits=8,g.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=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=ie(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=ie(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)/wt.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=Si.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>wt.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(ie(t,e,s.lat,s.lng).x,ie(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(pl(t,e,i)),wt.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>wt.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),wt.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(ie(t,e,a.lat,a.lng).x,ie(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(pl(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)}),wt.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)),_n.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Ee(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BLt9Dsxc.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>wt.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(ie(t,e,s.lat,s.lng).x,ie(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(pl(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)}),wt.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),_n.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Ee(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-geTpPVGC.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??=Ee(async()=>{const{TraceSystem:t}=await import("./TraceSystem-DpokUmzt.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(rp);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=vt.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?ie(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 ui(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=ln.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.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(t6(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!P6(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=As.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:Na.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>=z6,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(wt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=wt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=wt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),vt.dispose(i);this.decorGroups.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,l6);for(const i of t){const n=vt.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)<u6,i.lamp),i.model&&i.id.startsWith(gn.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.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??=Ee(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-D_EBfThB.js");return{ContrailSystem:t}},__vite__mapDeps([0,1]),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=wt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=Hn.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),h=De.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??=Ee(async()=>{const{BeamSystem:t}=await import("./BeamSystem-Ddt2lTBT.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?Ke(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*mi)/Math.cos(t.lat*mi)}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 np(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(Gd(t))||!vt.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=QC(i.scene);n.traverse(s=>{s instanceof xt&&(s.userData.sharedModel=!0)}),vt.applyModelParameters(n,t.modelParameters,i.bindings),vt.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(t.id,i.credit)}standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?Ay[t.kind]:Gd(t);if(!(!n||!vt.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 np(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"&&_n.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=np(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||_n.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?ie(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&ch(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=Ys(s,i),g=vt.occupantView(s,p.headingDeg),m=-(p.headingDeg??0)*mi,v=g.x*Math.cos(m)+g.z*Math.sin(m),y=-g.x*Math.sin(m)+g.z*Math.cos(m),x=p.eastM+n.x,M=-p.northM+n.z;r.x=-(x+v),r.z=-(M+y),this.camera.position.y=this.groundYUnder(x,M)+g.eyeY,c=g.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*mi,-(g.headingDeg+this.indoorLookYawDeg)*mi,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(g=>g.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 g=this.decorGroups.get(p.id);if(!g)continue;const m=Ys(p,i),v=this.lampNudges.get(p.id),y=m.eastM+(v?.eastM??0)+n.x+r.x,x=-(m.northM+(v?.northM??0))+n.z+r.z,M=this.terrainMesh,b=`${M?.geometry.uuid}:${(y-(M?.position.x??0)).toFixed(3)}:${(x-(M?.position.z??0)).toFixed(3)}:${(M?.position.y??0).toFixed(3)}:${m.headingDeg}:${m.altitudeM}:${l}`;if(g.userData.footprintKey!==b){if(p.kind==="wire"){const O=vt.wireGround(p,y,x,m.headingDeg,(L,N)=>this.groundYUnder(L,N));g.userData.footprintGroundY=O.startY,vt.shearWire(g,vt.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(y,x),L=-(m.headingDeg??0)*mi,N=Math.cos(L),P=Math.sin(L);g.userData.footprintGroundY=O,ve.drape(vt.bodyOf(g),(z,B)=>this.groundYUnder(y+z*N+B*P,x-z*P+B*N)-O)}else g.userData.footprintGroundY=this.groundUnderFootprint(p,y,x,m.headingDeg,m.altitudeM);g.userData.footprintKey=b}const E=m.altitudeM>wt.AIRBORNE_M&&Math.hypot(y,x)<wt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:g.userData.footprintGroundY;if(g.position.set(y,E+m.altitudeM,x),p.kind==="crop"){const O=Math.hypot(y,x);g.visible=O<=A6}const w=this.decorPresence.get(p.id),_=w!==void 0&&(i<w.fromMs||i>w.untilMs);w&&(g.visible=!_);const D=this.decorSunlight.get(p.id);D&&!_&&this.lightFromAbove(g,D),m.headingDeg!==void 0&&(g.rotation.y=-m.headingDeg*mi);const I=hS(p,i);if(I!==void 0&&wt.turnHead(g,m.headingDeg??0,I),p.kind==="crop"&&g.visible){const O=this.terrainMesh,L=[O?.geometry.uuid,y-(O?.position.x??0),x-(O?.position.z??0),g.position.y-(O?.position.y??0),m.headingDeg,m.altitudeM].map(N=>typeof N=="number"?N.toFixed(4):N).join(":");g.userData.cropGroundKey!==L&&(vt.fitCropToGround(g,(N,P)=>this.groundYUnder(N,P)+m.altitudeM),g.userData.cropGroundKey=L)}if(!_){const O=g.position.distanceTo(this.camera.position);a=Math.max(a,O),O<wt.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?Si.beamReachFor(this.beams,this.terrainMeshOrigin):0,f=Math.max(Xu*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=Ys(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=vt.sizeOf(s),u=-(a.headingDeg??0)*mi,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=vt.fitTerrace(r,s,(g,m)=>this.terrainYUnder(c+g*d+m*f,h-g*f+m*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):mp}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))+wt.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),g=u*u/(2*wt.SIGHT_EARTH_RADIUS_M);l=Math.max(l,Math.atan2(p-g-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 mp;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 mp;const d=Math.min(Math.floor(l),s-2),f=Math.min(Math.floor(u),s-2),p=l-d,g=u-f,m=(b,S)=>n.getY(b*s+S),v=m(f,d),y=m(f,d+1),x=m(f+1,d),M=m(f+1,d+1);return p+g<=1?v+(y-v)*p+(x-v)*g:M+(x-M)*(1-p)+(y-M)*(1-g)}groundUnderFootprint(t,e,i,n,s=0){return vt.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}: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($i.uColorVision.value.set(...i.colorMatrix),$i.uContrast.value=i.contrastGain,!t){$i.uMedium.value=0;return}$i.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:3;const n=t.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0,s=n===void 0?void 0:this.meteredBodies(),r=n===void 0?void 0:n+s.mean,a=h=>.065*t.exposureSeconds*h*this.filterTransmittance/(t.fNumber*t.fNumber*e);let c=r!==void 0&&r>0?1/(e*r):void 0;c!==void 0&&t.metering==="highlights"&&s.brightest>0&&(c=Math.min(c,wt.HIGHLIGHT_KEPT_AT/(.18*e*s.brightest))),$i.uMediumExposure.value=c!==void 0?Math.min(c,t.maxIso!==void 0?a(t.maxIso):1/0):a(t.iso)}static HIGHLIGHT_KEPT_AT=.3;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 R;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/(wt.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 nt;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&&vt.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"?_y(n,t):void 0,c=a!==void 0?zo.lamps(a):Cf(n,t,this.lastAstronomy?.sun.altitudeDeg);vt.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??=Ee(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-Cz4cc2lG.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 R(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=vt.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-f6);r.y+=d6;const a=vt.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*p6,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?zo.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new R(Math.sin(i),0,-Math.cos(i)),s=new R(n.x*C2,this.camera.position.y-g6,n.z*C2);this.headlightSystem.aim("observer",e,s,n,m6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=vt.bodyOf(e),r=s.children.find(h=>h.userData.emissive);if(!r)return;const a=D2*vt.lampShare(n),c=new Ox(16764006,a*this.relativeScale,v6);n?.colorTemperatureK&&c.color.setRGB(...vt.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;vt.setLitWindowShare(t?un.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=Rs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Pt.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=Ui.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,R2,new st(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<yd){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=R2/$n*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ke(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ke(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*mi/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 R(s.x,s.y,s.z).normalize(),moon:new R(d.x,d.y,d.z).normalize(),sunRadiusRad:i*mi,moonRadiusRad:f*mi};const p=.01,g=(y,x)=>Ke(t.sun.altitudeDeg+y,t.sun.azimuthDeg+x,1),m={x:g(p,0).x-g(-p,0).x,y:g(p,0).y-g(-p,0).y,z:g(p,0).z-g(-p,0).z},v={x:g(0,p).x-g(0,-p).x,y:g(0,p).y-g(0,-p).y,z:g(0,p).z-g(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:m,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Wc(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??wt.relativeSkyOf(Um(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),Ot.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??D2)*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?Xt.DEFAULT_AEROSOL_OPTICAL_DEPTH:Na.opticalDepth(i))*Xt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=De.aureoleScale(n,De.airMass(t.altitudeDeg))*s,c=De.coronaScale(r),h=De.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 s1,this.celestialGroup.add(this.lunarDiffraction.object));const u=De.profile(De.HAZE_COARSE_MODE),d=De.profile(De.CLOUD_DROPLETS),f=II(t.altitudeDeg),p=new Float32Array(De.STEPS*3);let g=0;for(let x=0;x<De.STEPS;x++){const M=x*3,b=[0,1,2].map(E=>h*f[E]*(a*u[M+E]+c*d[M+E])),S=Rs.shown(b,Rs.luminanceOf(b),(E,w)=>e.relativeOfLuminance(E,w));p.set(S,M),g=Math.max(g,Rs.response(S))}const{x:m,y:v,z:y}=Ke(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:y}:void 0,p)}applyAir(){this.scene.fog instanceof ko||(this.scene.fog=new ko),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,wt.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:Ui.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?Ui.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)}}}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?x6:y6),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 MC(op),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):vd(-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 qn,this.celestialGroup.add(this.reentrySystem.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):vd(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(t){t.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new ai,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,wt.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(cp*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,h]of this.decorGroups){if(!h.visible||!c.startsWith(gn.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}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(cp*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>=$h,s=!n&&t.moon.altitudeDeg>=$h,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*mi)),h=this.siteElevationM+this.observerElevationM;let l=r,u=n||s?E2.directFraction(r.altitudeDeg,h):0;n&&u<=0&&t.moon.altitudeDeg>=$h&&(l=t.moon,u=E2.directFraction(l.altitudeDeg,h));const d=Math.max(0,Math.sin(Math.max(l.altitudeDeg,0)*mi)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),g=Math.max(0,1/(1+.1125*p)-f),m=[0,0,0];if(n||s){const S=De.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(h,r.altitudeDeg);for(let I=0;I<3;I++)m[I]=S*E[I]*g*c,this.cloudBeam[I]=S*E[I];const{x:w,y:_,z:D}=Ke(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(w,_,D),u>0){const I=De.illuminanceOf(l.magnitude)*i,O=l===r?E:this.air.transmittanceFromSpace(h,l.altitudeDeg),L=l===r?f:this.cloudTransmission(l);for(let N=0;N<3;N++)a[N]=I*O[N]*L*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=e.skyIrradiance,w=[0,1,2].map(D=>E[D]*S+m[D]);this.skyLight.color.setRGB(w[0],w[1],w[2]);const _=jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(_*(w[0]+a[0]*d),_*(w[1]+a[1]*d),_*(w[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:y,y:x,z:M}=Ke(l.altitudeDeg,l.azimuthDeg,1);this.lightDirection.set(y,x,M),this.celestialLight.shadow.normalBias=T2*cr(x/s6,.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=Hn.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=De.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=wt.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 Cs||r instanceof Da)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=wt.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 R(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=n6;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Ku+5,i.near=this.shadowLightDistanceM-Ku,i.far=this.shadowLightDistanceM+Ku,i.updateProjectionMatrix(),e.bias=-.004/(2*Ku),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!==wt.CABIN_SKY_SHARE&&(r.envMapIntensity=wt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(i6,Math.max(va,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(Xh,e*(Xh/va));this.shadowLightDistanceM=Math.max($n,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=e>2*va?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=va;shadowLightDistanceM=$n;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*mi,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 R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Pt.semiSaturation(Pt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new cn,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?.update(t)}setInstrument(t){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const e=nn.starPointsOf(t);e!==this.starPoints&&(this.starPoints=e,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=e),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 vd(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),this.developingExposure||t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture()),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const 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()+wt.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.observerSide!==void 0&&ch(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Ys(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=vt.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 _n(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof Qn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=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,a=>this.measureSurroundings(a,n,s),t?0:_n.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,wt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new fl;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>Ke(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,s,r=>{const a=f=>f.map(p=>p/e),c=this.surroundings,h={up:a(r.up),down:a(r.down)},l=(f,p)=>f.some((g,m)=>Math.abs(g-p[m])>.03*Math.max(Math.abs(g),Math.abs(p[m]),1e-12)),u=!c||l(c.up,h.up)||l(c.down,h.down);u&&(this.surroundings=h),this.eyeSettledVersion=-1;const d=this.scatteredSky?.adaptToSurroundings(wt.adaptingLuminance(Math.exp(r.logAverage)/e,h.down))??!1;if(!u&&!d){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>=$h?t.sun:t.moon.altitudeDeg>=$h?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;surroundings;animate(t,e){const i=Math.min(e/1e3,F6);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(),vt.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.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()),$i.uRodShare.value=this.scatteredSky?.rodShare??0,$i.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);$i.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 Qn&&e.userData.pointSource||e instanceof xt&&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(rp),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(_b),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 ss({blending:Bo,blendSrc:Sr,blendDst:Sr,blendSrcAlpha:Sr,blendDstAlpha:Sr,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??=Ee(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-DKmWxtY-.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 R)}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;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);s&&wt.markDecorDepth(s,n.kind!=="crop")}t.layers.set(sp),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(Tb),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new ss({colorWrite:!1});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(wt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*mi}static isSolidSurface(t){if(!(t instanceof xt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==sn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof xt))return;e&&wt.isSolidSurface(i)?i.layers.enable(sp):i.layers.disable(sp)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new nt),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new mI(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()+wt.EXPOSURE_BUDGET_MS,s=wt.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(){$i.uRodShare.value=this.scatteredSky?.rodShare??0,$i.uHasOverlay.value=1,$i.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 Zs,n=new Os(-1,1,1,-1,0,2),s=Zu/(P2*Math.tan(L2*mi/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),h=this.screenPointOf(c);if(!h)continue;const l=new Lh(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 Ki,i=new R,n=this.camera.getWorldDirection(new R),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)<wt.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 g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;c=Math.min(c,m),h=Math.max(h,m),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 nt),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new gl(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,$i.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 nt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Kn(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new nt);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new n1(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new nt);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new vi(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new nt(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 R)}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);if(this.projectionKind==="equidistant"&&this.equidistantPass)return vi.ndcFor(e,this.camera.fov,n);if(e.z>=0)return;const s=Math.tan(this.camera.fov/2*mi);return{ndcX:e.x/-e.z/(n*s),ndcY:e.y/-e.z/s}}screenPointScratch=new R;screenPointQuaternion=new ns;screenPointSize=new nt;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-wt.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(A2),this.camera.layers.set(A2),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 k2)this.isSunOccluded(e[0],e[1])||t++;return t/k2.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){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(this.sunWorldPosition).sub(this.camera.position),s=n.length();if(n.normalize(),t!==0||e!==0){const a=Math.PI/180,c=this.sunOcclusionRightScratch.set(n.z,0,-n.x);c.lengthSq()<1e-9&&c.set(1,0,0),c.normalize();const h=this.sunOcclusionUpScratch.crossVectors(c,n).normalize();n.addScaledVector(c,t*a).addScaledVector(h,e*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const m=(s.position.y-t.y)/e.y;if(m>n&&m<i){const v=t.x+e.x*m-s.position.x,y=t.z+e.z*m-s.position.z;if(Math.hypot(v,y)<=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[m,v,y]of[[t.x,e.x,h],[t.z,e.z,l]]){const x=Math.min(y[0],y[1]),M=Math.max(y[0],y[1]);if(Math.abs(v)<1e-12){if(m<x||m>M)return!1;continue}const b=(x-m)/v,S=(M-m)/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),g=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=g;m++){const v=d+(f-d)*m/g,y=t.x+e.x*v,x=t.y+e.y*v,M=t.z+e.z*v;if(x<=this.groundYUnder(y,M))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=$u;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=>wt.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=r6*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([l,u])=>{const d=u.getWorldPosition(new R).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=wt.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=e6*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?wt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let h,l=1/0;const u=new Ki,d=new R;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new R).length()/2,g=d.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||c!==void 0&&c<m-p)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),y=Math.atan(p/m);if(y>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(v>r)continue;y<l&&(l=y,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(cp*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,$u)}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 Ki;bodyCornerScratch=new R;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*mi/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 Ea;decorHitScratch=new R;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<wt.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=wt.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 yh().copy(n).applyMatrix4(new le().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new R(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,wt.RAILWAY_PICK_ABOVE_M))return;const c=wt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-wt.RAILWAY_GROUND_MARGIN_M,$u))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,wt.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,$u))return;const r=wt.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(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.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())vt.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const 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),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 R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<wt.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 Hi(Xu,32,16),i=e.attributes.position,n=e.getAttribute("color")??new he(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=MI(i.getX(r),i.getY(r),i.getZ(r)),h=_I(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 ss({vertexColors:!0,side:xi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new xt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=_2(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new Pg(this.groundRadius,48),i=new Cs({color:new st(ap,ap,ap),fog:!0});ko.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new xt(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=Ke(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-Ue.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*c6);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Ue.iceAlphaAt(i,qu,r,this.cloudFieldOffset)*h6),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<yd){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}=Ke(e.altitudeDeg,e.azimuthDeg,$n),h=this.cloudTransmission(e),l=this.arrivingIlluminance(e,s,h),u=wt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/$n)**2,p=[0,1,2].map(m=>u[m]*l[m]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const g=p.map(m=>Math.min(wt.BRIGHTEST_RELATIVE,m));d instanceof xt||(this.disposeMesh(d),d=new xt(new Hi(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(g[0],g[1],g[2]),d.scale.setScalar(i)}else{if(!(d instanceof Qn)){this.disposeMesh(d);const g=new se;g.setAttribute("position",new ce(new Float32Array(3),3)),g.setAttribute("color",new ce(new Float32Array(3),3)),d=new Qn(g,Ot.material(Po[Po.length-1].size,!1)),Ot.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/$n*(180/Math.PI),wt.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=vC(),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<yd){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ke(t.altitudeDeg,t.azimuthDeg,$n),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),h=t.radiusDeg??Mr.MEAN_RADIUS_DEG,l=$n*Math.tan(h*mi),u=Math.max(cr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(l/$n)**2,d=new st(...c.map(g=>Math.min(wt.BRIGHTEST_RELATIVE,g/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(cr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Lh?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=Q2(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Lh(new pd({map:Q2(t.phase),color:d,fog:!1,blending:sn,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=a6){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 wt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new st;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,Ot.CONE_SOLID_ANGLE/e)}pointScratch=new nt;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=De.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Rs.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 pd({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Lh(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(ln.radiusDeg(ln.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new ln(`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=_o(t.magnitude,e),s=Y0(n);this.cometKey=i,this.setBodyMesh(i,t.position,hp*(.5+.5*n),new st(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new us($n),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Di,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:qu},0);return}const s=this.lowerCloudCover(),r=de.deckLitUntilDeg(de.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?ye.SUN_MAGNITUDE:e.magnitude),h=de.strength(i,s,a.altitudeDeg,r)*c.scale,{x:l,y:u,z:d}=Ke(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??qu},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??jb,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Ao,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?ye.SUN_MAGNITUDE:e.magnitude,o6),c=ls.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}=Ke(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 Aa,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=Fs.galactic(i,n),r=wt.directionOf(s.centre),a=wt.directionOf(s.rotation),c=wt.directionOf(s.pole),h=new ne().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),l=wt.directionOf(Fs.eclipticPole(i,n)),u=wt.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:wt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new R(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ke(t.altitudeDeg,t.azimuthDeg,1);return new R(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=_o(n.magnitude,e),a=Y0(r);this.setBodyMesh(s,n.position,hp*(.5+.5*r),new st(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=_o(n.magnitude,e),r=Y0(s),a=G6[n.body]??new st(1,1,1),c=new st(a.r*r,a.g*r,a.b*r),h=hp*(.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 Vs(n,s),a=yp(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<I2)continue;const{x:p,y:g,z:m}=Ke(d,f,op);c.push({x:p,y:g,z:m,brightness:_o(u,e),illuminance:this.air.transmittanceFromSpace(h,d).map(v=>v*De.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const l of ZD){if(l.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(l.raHours,l.decDeg);if(u<I2)continue;const{x:f,y:p,z:g}=Ke(u,d,op);this.namedStars.push({star:l,direction:new R(f,p,g).normalize(),altitudeDeg:u})}this.starTiers=Po.map((l,u)=>{const d=c.filter(b=>Bf(b.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),g=new Float32Array(d.length*3),m=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,g.set(b.illuminance,S*3),m[S]=b.phase,v[S]=b.speedFactor});const y=new se;y.setAttribute("position",new ce(f,3)),y.setAttribute("seed",new ce(m.map(b=>b/(2*Math.PI)),1));const x=new ce(new Float32Array(d.length*3),3);y.setAttribute("color",x);let M=this.starTiers[u]?.points;return M?(M.geometry.dispose(),M.geometry=y):(M=new Qn(y,Ot.material(l.size)),Ot.track(M),this.celestialGroup.add(M)),{points:M,colorAttribute:x,brightness:p,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Ot.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 jc(this.celestialGroup,lp,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 st(Ja[0]+(fp[0]-Ja[0])*e,Ja[1]+(fp[1]-Ja[1])*e,Ja[2]+(fp[2]-Ja[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}=Om(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=Pm(lp);this.cloudMesh=new xt(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}=Om(new st(...Ja),t,qu,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new xt(Pm(lp*1.04),e),this.cirrusMesh.renderOrder=U2-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?jc.deckOrder(!0,0,1):U2}cloudLayerOffset(){const e=((this.weather.cloudBaseM??og)-this.observerElevationM)*up;return Math.sign(e||1)*Math.max(Math.abs(e),E6)}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*Mp*this.relativeScale/Math.PI,h=new st(e[0]+sr.r*c,e[1]+sr.g*c,e[2]+sr.b*c);this.layeredClouds?.setLighting(n.clone(),new st(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 O6(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,gp],[this.rainSplashSystem?.points,ja],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:pp[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=H2(vp(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=pp[t],i=e.poolSize,n=yp(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 x=0;x<i;x++){const M=n()*Math.PI*2,b=n()*e.radiusM;s[x*3]=Math.cos(M)*b,s[x*3+1]=Dc+n()*(e.topYM-Dc),s[x*3+2]=Math.sin(M)*b,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,h[x]=.4+n()*1.2}const g=new se;g.setAttribute("position",new ce(s,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new st(...this.baseFogColor)},uTexture:{value:V6(t)},uNearFocusDistance:{value:X2},uHazeDistance:{value:e.radiusM*$2}},v=new Ae({uniforms:m,vertexShader:q6,fragmentShader:Z6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const y=new Qn(g,v);y.renderOrder=dp,this.scene.add(y),this.precipitationPoints=y,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=pp[i];if(this.precipitationUniforms?.uColor.value.copy(wt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*mi,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,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,y=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&g&&m&&v;for(let M=0,b=0;M<c.length;M+=3,b++){if(x&&f[b]>0){if(f[b]-=e,f[b]<=0){const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_,f[b]=0}else{const w=1-f[b]/g[b];c[M+1]=Dc+Math.sin(Math.PI*w)*p[b],c[M]=Ju(c[M]+(r+m[b])*e,n.radiusM),c[M+2]=Ju(c[M+2]+(a+v[b])*e,n.radiusM)}continue}let S=0,E=0;if(y){const w=L6*u[b],_=N6*d[b];S=Math.sin(t*w*Math.PI*2+h[b])*_,E=Math.sin(t*w*Math.PI*2+h[b]+Math.PI/2)*_}if(c[M]+=(r+S)*e,c[M+1]-=n.fallSpeedMPerS*l[b]*e,c[M+2]+=(a+E)*e,c[M]=Ju(c[M],n.radiusM),c[M+2]=Ju(c[M+2],n.radiusM),c[M+1]<Dc){if(x){p[b]=J2*(.2+Math.random()*1.6),g[b]=k6*(.5+Math.random()),f[b]=g[b];const D=Math.random()*Math.PI*2,I=U6*(p[b]/J2);m[b]=Math.cos(D)*I,v[b]=Math.sin(D)*I,c[M+1]=Dc;continue}const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=vp(this.weather.precipitationIntensity);this.rainSystem=pC({count:gp,radiusM:Yh,heightM:_6,bottomYM:F2,overallSpeed:T6,color:B2.clone(),opacity:.85,visibleCount:this.precipitationCount(gp),speedStreak:H2(t),pixelSize:K2,seed:9001,nearFocusDistanceM:X2,hazeDistanceM:Yh*$2,hazeColor:new st(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=dp,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=yp(4242),e=new Float32Array(ja*3),i=new Float32Array(ja),n=new Float32Array(ja),s=new Float32Array(ja);for(let l=0;l<ja;l++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Yh;e[l*3]=Math.cos(u)*d,e[l*3+1]=F2,e[l*3+2]=Math.sin(u)*d,n[l]=j2(G2,V2),i[l]=t()*n[l],s[l]=i[l]/n[l]}const r=new se;r.setAttribute("position",new ce(e,3));const a=new ce(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(ja));const c=new Ae({uniforms:{uMaxSize:{value:C6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:W2.clone()},uTexture:{value:$6()}},vertexShader:Y6,fragmentShader:K6,transparent:!0,depthWrite:!1}),h=new Qn(r,c);h.renderOrder=dp,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*mi;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-vp(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(wt.litBySky(B2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(wt.litBySky(W2,this.baseFogColor));const n=this.weather.windDirectionDeg*mi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Yh,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=q2+(1-q2)*(1-h),u=Z2+(1-Z2)*(1-h);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=K2*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())*Yh;i[c]=Math.cos(l)*u,i[c+2]=Math.sin(l)*u,s[h]=j2(G2,V2),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=Qi.brightnessAt(c,t);h>i&&(e=c,i=h)}const n=e?Math.min(1,Math.max(.1,(B6/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*Mp*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+sr.r*h,this.airlight[1]+sr.g*h,this.airlight[2]+sr.b*h)}const r=this.skyMesh?.material?.color;if(r){const c=s*H6;r.setRGB(1+c*sr.r,1+c*sr.g,1+c*sr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Mp*this.relativeScale,e){const{x:c,y:h,z:l}=Ke(25,e.azimuthDeg,$n);this.lightningLight.position.set(c,h,l)}this.lightningBolt||(this.lightningBolt=new _a($n*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=M6.map(t=>{const e=No.point(t,this.compassPoints),i=new pd({map:J6(e),depthTest:!1,fog:!1}),n=new Lh(i),{x:s,y:r,z:a}=Ke(0,t,P2);return n.position.set(s,r,a),n.scale.set(Zu,Zu,1),n.renderOrder=b6,n.layers.set(rp),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=L2*Math.PI/360,i=Zu*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 mi=Math.PI/180;function cr(o,t,e){return Math.max(t,Math.min(e,o))}function j2(o,t){return o+Math.random()*(t-o)}function Ju(o,t){return(o%(t*2)+t*3)%(t*2)-t}let ju,Qu;function V6(o){switch(o){case"snow":return W6();case"hail":return X6()}}function W6(){if(ju)return ju;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),ju=new Va(t),ju}function X6(){if(Qu)return Qu;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),Qu=new Va(t),Qu}let td;function $6(){if(td)return td;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),td=new Va(t),td}const Y6=`
|
|
8957
|
+
`,transparent:!0,blending:sn,depthWrite:!1,side:xi,fog:!1});this.object=new xt(new Hi(s1.RADIUS,128,32,0,Math.PI*2,0,De.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<De.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=gs.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=gs.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class vf{constructor(t){this.generator=t}static SIZE=128;target=new Ul(vf.SIZE,{type:He,generateMipmaps:!1,minFilter:we,magFilter:we});camera=new Hg(.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 _n{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){_n.install(),this.generator=new Rm(t),this.eye=new vf(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],h,l=_n.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const u=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new vf(this.generator),this.probes.set(m.id,v)),u.push({probe:v,reflector:m})}const d=performance.now(),f=()=>u.filter(({probe:m})=>m.capturedVersion!==a),p=f().filter(({probe:m})=>d-m.capturedAtMs>=l);if(p.length>0){const m=p.reduce((v,y)=>y.probe.capturedAtMs<v.probe.capturedAtMs?y:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(t,e,v,[m.reflector.holder,...s]),_n.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(t,e,i,[...s,...c]),h?.(m.probe.sharp),_n.decor=m.probe.filtered;for(const v of r)_n.reflectOn(v,m.probe);for(const v of n)v.shiny||_n.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=a}const g=f();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>l-(d-m.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:_n.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof zl?e.sharp&&s.setSurroundings(e.sharp):s instanceof Da&&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(_n.installed)return;_n.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!ae.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}ae.lights_fragment_maps=ae.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function t6(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 Xu=900,sp=1,A2=4,rp=5,$u=.5,Yu=Si.GROUND_RADIUS_M;function _2(o){return Si.groundRadiusFor(o)}const ap=.5,op=850,cp=.03,e6=.015,$n=850,Xh=300,va=120,i6=700,n6=3.5,Ku=20,T2=.04,s6=.26,R2=4,hp=1.5,I2=-1,r6=.01,yd=-4,a6=2,o6=20,qu=2600,c6=.97,h6=.38,$h=yd,l6=8,u6=2,D2=1500,d6=.7,f6=.3,p6=.32,m6=.65,C2=2.4,g6=.9,v6=400,M6=[0,45,90,135,180,225,270,315],y6=2,x6=16,O2=4e3,P2=880,Zu=40,L2=60,b6=10,w6=1,S6=Si.REBUILD_DISTANCE_M,N2=.265,k2=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*N2,Math.sin(e)*N2]})],lp=700,up=250/og,E6=12,U2=5,dp=6,Ja=[.92,.92,.95],fp=[.15,.15,.19],pp={snow:{fallSpeedMPerS:2,size:.3,color:new st(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new st(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Dc=0,mp=0,A6=150,gp=3e3,Yh=20,_6=15,F2=Dc,T6=40,z2=1,R6=9;function vp(o){return z2+(R6-z2)*o}const B2=new st(.75,.82,.92),I6=10,D6=.5;function H2(o){return cr(o/I6,D6,1)}const ja=200,G2=.18,V2=.32,C6=.35,W2=new st(.85,.9,.98),X2=5,$2=.85,Y2=.01;function O6(o,t,e=1){return Math.round(o*(Y2+(1-Y2)*t)*e)}function P6(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 K2=230,q2=.7,Z2=.05,L6=.6,N6=.7,k6=.15,J2=.35,U6=3,F6=1/12,z6=.5,sr=new st(.82,.86,1),B6=2500,H6=1.6,Mp=15,G6={Venus:new st(1,.96,.85),Mars:new st(1,.55,.4),Jupiter:new st(.95,.87,.72),Saturn:new st(.92,.86,.68)};class wt{renderer;scene=new Zs;phenomena=new zs(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Pe;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()+O2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),O2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ge;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new nt;decorModelProvider=ZC[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new ue(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale);bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??wt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*wt.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 fM(16777215,0);celestialLightTarget=new bi;skyLight=new WA(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 md;weather=_f;observerElevationM=0;siteElevationM=0;air=new As;groundRadius=Yu;terrainRadius=Yu;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new R;cloudFieldOffset=new R;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new R;rainLastVerticalFacing=-1;rainViewportSize=new nt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new fM(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new md;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new md;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=fi.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 Bl;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Gy()){this.renderer=new rI({canvas:t,antialias:!0}),this.resolution=new ze(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=al,this.camera=new ts(60,t.width/Math.max(t.height,1),.1,Xu*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=-va,this.celestialLight.shadow.camera.right=va,this.celestialLight.shadow.camera.top=va,this.celestialLight.shadow.camera.bottom=-va,this.celestialLight.shadow.camera.near=$n-Xh,this.celestialLight.shadow.camera.far=$n+Xh,this.celestialLight.shadow.bias=-.03/(2*Xh),this.celestialLight.shadow.normalBias=T2,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(sr),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 ye(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*up,0,t.z*up);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)*mi,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*mi;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*mi,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(_2(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Yu),this.camera.far=Math.max(Xu*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;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=wt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Si.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ie(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.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{this.terrainProviders===d&&this.setTerrainOrigin(t,e,i)}),wt.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}=ie(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<S6*(r/Yu))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ie(t,e,c.lat,c.lng).x,ie(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(a2(t,e,this.terrainProviders,r,{route:this.observerRoute}),wt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:g})=>{if(l!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const m=this.terrainMesh,v=this.terrainMeshOrigin,y=v?ie(t,e,v.lat,v.lng):void 0;m&&y&&Math.hypot(y.x,y.z)<=a&&(u.position.y=m.position.y+this.groundYOfPatch(m,y.x,y.z)),m&&v&&y&&Math.hypot(y.x,y.z)<=a?this.crossfadeTerrain(u,m,v):this.disposeMesh(this.terrainMesh),u.renderOrder=w6,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,g),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=Si.beamReachFor(this.beams,{lat:t,lng:e});if(!Si.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:g}=ie(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,g)<i*wt.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??Si.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(a2(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*wt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),wt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=wt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-wt.FAR_RING_DROP_M;const g=p.material;g.polygonOffset=!0,g.polygonOffsetFactor=2,g.polygonOffsetUnits=8,g.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=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=ie(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=ie(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)/wt.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=Si.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>wt.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(ie(t,e,s.lat,s.lng).x,ie(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(pl(t,e,i)),wt.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>wt.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),wt.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(ie(t,e,a.lat,a.lng).x,ie(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(pl(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)}),wt.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)),_n.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Ee(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BLt9Dsxc.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>wt.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(ie(t,e,s.lat,s.lng).x,ie(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(pl(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)}),wt.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),_n.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Ee(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-geTpPVGC.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??=Ee(async()=>{const{TraceSystem:t}=await import("./TraceSystem-DpokUmzt.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(rp);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=vt.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?ie(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 ui(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=ln.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(t6(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!P6(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=As.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:Na.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>=z6,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(wt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=wt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=wt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),vt.dispose(i);this.decorGroups.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,l6);for(const i of t){const n=vt.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)<u6,i.lamp),i.model&&i.id.startsWith(gn.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.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??=Ee(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-D_EBfThB.js");return{ContrailSystem:t}},__vite__mapDeps([0,1]),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=wt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=Hn.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),h=De.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??=Ee(async()=>{const{BeamSystem:t}=await import("./BeamSystem-Ddt2lTBT.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?Ke(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*mi)/Math.cos(t.lat*mi)}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 np(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(Gd(t))||!vt.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=QC(i.scene);n.traverse(s=>{s instanceof xt&&(s.userData.sharedModel=!0)}),vt.applyModelParameters(n,t.modelParameters,i.bindings),vt.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(t.id,i.credit)}standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?Ay[t.kind]:Gd(t);if(!(!n||!vt.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 np(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"&&_n.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=np(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||_n.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?ie(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&ch(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=Ys(s,i),g=vt.occupantView(s,p.headingDeg),m=-(p.headingDeg??0)*mi,v=g.x*Math.cos(m)+g.z*Math.sin(m),y=-g.x*Math.sin(m)+g.z*Math.cos(m),x=p.eastM+n.x,M=-p.northM+n.z;r.x=-(x+v),r.z=-(M+y),this.camera.position.y=this.groundYUnder(x,M)+g.eyeY,c=g.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*mi,-(g.headingDeg+this.indoorLookYawDeg)*mi,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(g=>g.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 g=this.decorGroups.get(p.id);if(!g)continue;const m=Ys(p,i),v=this.lampNudges.get(p.id),y=m.eastM+(v?.eastM??0)+n.x+r.x,x=-(m.northM+(v?.northM??0))+n.z+r.z,M=this.terrainMesh,b=`${M?.geometry.uuid}:${(y-(M?.position.x??0)).toFixed(3)}:${(x-(M?.position.z??0)).toFixed(3)}:${(M?.position.y??0).toFixed(3)}:${m.headingDeg}:${m.altitudeM}:${l}`;if(g.userData.footprintKey!==b){if(p.kind==="wire"){const O=vt.wireGround(p,y,x,m.headingDeg,(L,N)=>this.groundYUnder(L,N));g.userData.footprintGroundY=O.startY,vt.shearWire(g,vt.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(y,x),L=-(m.headingDeg??0)*mi,N=Math.cos(L),P=Math.sin(L);g.userData.footprintGroundY=O,ve.drape(vt.bodyOf(g),(z,B)=>this.groundYUnder(y+z*N+B*P,x-z*P+B*N)-O)}else g.userData.footprintGroundY=this.groundUnderFootprint(p,y,x,m.headingDeg,m.altitudeM);g.userData.footprintKey=b}const E=m.altitudeM>wt.AIRBORNE_M&&Math.hypot(y,x)<wt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:g.userData.footprintGroundY;if(g.position.set(y,E+m.altitudeM,x),p.kind==="crop"){const O=Math.hypot(y,x);g.visible=O<=A6}const w=this.decorPresence.get(p.id),_=w!==void 0&&(i<w.fromMs||i>w.untilMs);w&&(g.visible=!_);const D=this.decorSunlight.get(p.id);D&&!_&&this.lightFromAbove(g,D),m.headingDeg!==void 0&&(g.rotation.y=-m.headingDeg*mi);const I=hS(p,i);if(I!==void 0&&wt.turnHead(g,m.headingDeg??0,I),p.kind==="crop"&&g.visible){const O=this.terrainMesh,L=[O?.geometry.uuid,y-(O?.position.x??0),x-(O?.position.z??0),g.position.y-(O?.position.y??0),m.headingDeg,m.altitudeM].map(N=>typeof N=="number"?N.toFixed(4):N).join(":");g.userData.cropGroundKey!==L&&(vt.fitCropToGround(g,(N,P)=>this.groundYUnder(N,P)+m.altitudeM),g.userData.cropGroundKey=L)}if(!_){const O=g.position.distanceTo(this.camera.position);a=Math.max(a,O),O<wt.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?Si.beamReachFor(this.beams,this.terrainMeshOrigin):0,f=Math.max(Xu*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=Ys(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=vt.sizeOf(s),u=-(a.headingDeg??0)*mi,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=vt.fitTerrace(r,s,(g,m)=>this.terrainYUnder(c+g*d+m*f,h-g*f+m*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):mp}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))+wt.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),g=u*u/(2*wt.SIGHT_EARTH_RADIUS_M);l=Math.max(l,Math.atan2(p-g-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 mp;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 mp;const d=Math.min(Math.floor(l),s-2),f=Math.min(Math.floor(u),s-2),p=l-d,g=u-f,m=(b,S)=>n.getY(b*s+S),v=m(f,d),y=m(f,d+1),x=m(f+1,d),M=m(f+1,d+1);return p+g<=1?v+(y-v)*p+(x-v)*g:M+(x-M)*(1-p)+(y-M)*(1-g)}groundUnderFootprint(t,e,i,n,s=0){return vt.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}: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($i.uColorVision.value.set(...i.colorMatrix),$i.uContrast.value=i.contrastGain,!t){$i.uMedium.value=0;return}$i.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:3;const n=t.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0,s=n===void 0?void 0:this.meteredBodies(),r=n===void 0?void 0:n+s.mean,a=h=>.065*t.exposureSeconds*h*this.filterTransmittance/(t.fNumber*t.fNumber*e);let c=r!==void 0&&r>0?1/(e*r):void 0;c!==void 0&&t.metering==="highlights"&&s.brightest>0&&(c=Math.min(c,wt.HIGHLIGHT_KEPT_AT/(.18*e*s.brightest))),$i.uMediumExposure.value=c!==void 0?Math.min(c,t.maxIso!==void 0?a(t.maxIso):1/0):a(t.iso)}static HIGHLIGHT_KEPT_AT=.3;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 R;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/(wt.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 nt;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&&vt.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"?_y(n,t):void 0,c=a!==void 0?zo.lamps(a):Cf(n,t,this.lastAstronomy?.sun.altitudeDeg);vt.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??=Ee(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-Cz4cc2lG.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 R(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=vt.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-f6);r.y+=d6;const a=vt.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*p6,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?zo.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new R(Math.sin(i),0,-Math.cos(i)),s=new R(n.x*C2,this.camera.position.y-g6,n.z*C2);this.headlightSystem.aim("observer",e,s,n,m6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=vt.bodyOf(e),r=s.children.find(h=>h.userData.emissive);if(!r)return;const a=D2*vt.lampShare(n),c=new Ox(16764006,a*this.relativeScale,v6);n?.colorTemperatureK&&c.color.setRGB(...vt.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;vt.setLitWindowShare(t?un.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=Rs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Pt.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=Ui.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,R2,new st(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<yd){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=R2/$n*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ke(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ke(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*mi/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 R(s.x,s.y,s.z).normalize(),moon:new R(d.x,d.y,d.z).normalize(),sunRadiusRad:i*mi,moonRadiusRad:f*mi};const p=.01,g=(y,x)=>Ke(t.sun.altitudeDeg+y,t.sun.azimuthDeg+x,1),m={x:g(p,0).x-g(-p,0).x,y:g(p,0).y-g(-p,0).y,z:g(p,0).z-g(-p,0).z},v={x:g(0,p).x-g(0,-p).x,y:g(0,p).y-g(0,-p).y,z:g(0,p).z-g(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:m,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Wc(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??wt.relativeSkyOf(Um(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),Ot.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??D2)*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?Xt.DEFAULT_AEROSOL_OPTICAL_DEPTH:Na.opticalDepth(i))*Xt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=De.aureoleScale(n,De.airMass(t.altitudeDeg))*s,c=De.coronaScale(r),h=De.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 s1,this.celestialGroup.add(this.lunarDiffraction.object));const u=De.profile(De.HAZE_COARSE_MODE),d=De.profile(De.CLOUD_DROPLETS),f=II(t.altitudeDeg),p=new Float32Array(De.STEPS*3);let g=0;for(let x=0;x<De.STEPS;x++){const M=x*3,b=[0,1,2].map(E=>h*f[E]*(a*u[M+E]+c*d[M+E])),S=Rs.shown(b,Rs.luminanceOf(b),(E,w)=>e.relativeOfLuminance(E,w));p.set(S,M),g=Math.max(g,Rs.response(S))}const{x:m,y:v,z:y}=Ke(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:y}:void 0,p)}applyAir(){this.scene.fog instanceof ko||(this.scene.fog=new ko),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,wt.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:Ui.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?Ui.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)}}}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?x6:y6),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 MC(op),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):vd(-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 qn,this.celestialGroup.add(this.reentrySystem.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):vd(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(t){t.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new ai,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,wt.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(cp*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,h]of this.decorGroups){if(!h.visible||!c.startsWith(gn.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}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(cp*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>=$h,s=!n&&t.moon.altitudeDeg>=$h,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*mi)),h=this.siteElevationM+this.observerElevationM;let l=r,u=n||s?E2.directFraction(r.altitudeDeg,h):0;n&&u<=0&&t.moon.altitudeDeg>=$h&&(l=t.moon,u=E2.directFraction(l.altitudeDeg,h));const d=Math.max(0,Math.sin(Math.max(l.altitudeDeg,0)*mi)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),g=Math.max(0,1/(1+.1125*p)-f),m=[0,0,0];if(n||s){const S=De.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(h,r.altitudeDeg);for(let I=0;I<3;I++)m[I]=S*E[I]*g*c,this.cloudBeam[I]=S*E[I];const{x:w,y:_,z:D}=Ke(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(w,_,D),u>0){const I=De.illuminanceOf(l.magnitude)*i,O=l===r?E:this.air.transmittanceFromSpace(h,l.altitudeDeg),L=l===r?f:this.cloudTransmission(l);for(let N=0;N<3;N++)a[N]=I*O[N]*L*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=e.skyIrradiance,w=[0,1,2].map(D=>E[D]*S+m[D]);this.skyLight.color.setRGB(w[0],w[1],w[2]);const _=jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(_*(w[0]+a[0]*d),_*(w[1]+a[1]*d),_*(w[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:y,y:x,z:M}=Ke(l.altitudeDeg,l.azimuthDeg,1);this.lightDirection.set(y,x,M),this.celestialLight.shadow.normalBias=T2*cr(x/s6,.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=Hn.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=De.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=wt.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 Cs||r instanceof Da)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=wt.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 R(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=n6;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Ku+5,i.near=this.shadowLightDistanceM-Ku,i.far=this.shadowLightDistanceM+Ku,i.updateProjectionMatrix(),e.bias=-.004/(2*Ku),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!==wt.CABIN_SKY_SHARE&&(r.envMapIntensity=wt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(i6,Math.max(va,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(Xh,e*(Xh/va));this.shadowLightDistanceM=Math.max($n,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=e>2*va?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=va;shadowLightDistanceM=$n;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*mi,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 R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Pt.semiSaturation(Pt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new cn,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?.update(t)}setInstrument(t){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const e=nn.starPointsOf(t);e!==this.starPoints&&(this.starPoints=e,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=e),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 vd(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()+wt.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.observerSide!==void 0&&ch(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Ys(s,t),c=a.eastM+e.x+i.x,h=-a.northM+e.z+i.z,l=vt.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 _n(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof Qn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=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,a=>this.measureSurroundings(a,n,s),t?0:_n.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,wt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new fl;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>Ke(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,s,r=>{const a=f=>f.map(p=>p/e),c=this.surroundings,h={up:a(r.up),down:a(r.down)},l=(f,p)=>f.some((g,m)=>Math.abs(g-p[m])>.03*Math.max(Math.abs(g),Math.abs(p[m]),1e-12)),u=!c||l(c.up,h.up)||l(c.down,h.down);u&&(this.surroundings=h),this.eyeSettledVersion=-1;const d=this.scatteredSky?.adaptToSurroundings(wt.adaptingLuminance(Math.exp(r.logAverage)/e,h.down))??!1;if(!u&&!d){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>=$h?t.sun:t.moon.altitudeDeg>=$h?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;surroundings;animate(t,e){const i=Math.min(e/1e3,F6);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(),vt.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.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()),$i.uRodShare.value=this.scatteredSky?.rodShare??0,$i.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);$i.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 Qn&&e.userData.pointSource||e instanceof xt&&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(rp),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(_b),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 ss({blending:Bo,blendSrc:Sr,blendDst:Sr,blendSrcAlpha:Sr,blendDstAlpha:Sr,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??=Ee(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-DKmWxtY-.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 R)}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;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);s&&wt.markDecorDepth(s,n.kind!=="crop")}t.layers.set(sp),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(Tb),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new ss({colorWrite:!1});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(wt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*mi}static isSolidSurface(t){if(!(t instanceof xt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==sn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof xt))return;e&&wt.isSolidSurface(i)?i.layers.enable(sp):i.layers.disable(sp)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new nt),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new mI(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()+wt.EXPOSURE_BUDGET_MS,s=wt.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(){$i.uRodShare.value=this.scatteredSky?.rodShare??0,$i.uHasOverlay.value=1,$i.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 Zs,n=new Os(-1,1,1,-1,0,2),s=Zu/(P2*Math.tan(L2*mi/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),h=this.screenPointOf(c);if(!h)continue;const l=new Lh(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 Ki,i=new R,n=this.camera.getWorldDirection(new R),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)<wt.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 g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;c=Math.min(c,m),h=Math.max(h,m),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 nt),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new gl(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,$i.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 nt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Kn(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new nt);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new n1(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new nt);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new vi(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new nt(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 R)}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);if(this.projectionKind==="equidistant"&&this.equidistantPass)return vi.ndcFor(e,this.camera.fov,n);if(e.z>=0)return;const s=Math.tan(this.camera.fov/2*mi);return{ndcX:e.x/-e.z/(n*s),ndcY:e.y/-e.z/s}}screenPointScratch=new R;screenPointQuaternion=new ns;screenPointSize=new nt;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-wt.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(A2),this.camera.layers.set(A2),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 k2)this.isSunOccluded(e[0],e[1])||t++;return t/k2.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){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(this.sunWorldPosition).sub(this.camera.position),s=n.length();if(n.normalize(),t!==0||e!==0){const a=Math.PI/180,c=this.sunOcclusionRightScratch.set(n.z,0,-n.x);c.lengthSq()<1e-9&&c.set(1,0,0),c.normalize();const h=this.sunOcclusionUpScratch.crossVectors(c,n).normalize();n.addScaledVector(c,t*a).addScaledVector(h,e*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const m=(s.position.y-t.y)/e.y;if(m>n&&m<i){const v=t.x+e.x*m-s.position.x,y=t.z+e.z*m-s.position.z;if(Math.hypot(v,y)<=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[m,v,y]of[[t.x,e.x,h],[t.z,e.z,l]]){const x=Math.min(y[0],y[1]),M=Math.max(y[0],y[1]);if(Math.abs(v)<1e-12){if(m<x||m>M)return!1;continue}const b=(x-m)/v,S=(M-m)/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),g=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=g;m++){const v=d+(f-d)*m/g,y=t.x+e.x*v,x=t.y+e.y*v,M=t.z+e.z*v;if(x<=this.groundYUnder(y,M))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=$u;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=>wt.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=r6*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([l,u])=>{const d=u.getWorldPosition(new R).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=wt.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=e6*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?wt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let h,l=1/0;const u=new Ki,d=new R;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new R).length()/2,g=d.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||c!==void 0&&c<m-p)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),y=Math.atan(p/m);if(y>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(v>r)continue;y<l&&(l=y,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(cp*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,$u)}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 Ki;bodyCornerScratch=new R;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*mi/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 Ea;decorHitScratch=new R;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<wt.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=wt.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 yh().copy(n).applyMatrix4(new le().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new R(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,wt.RAILWAY_PICK_ABOVE_M))return;const c=wt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-wt.RAILWAY_GROUND_MARGIN_M,$u))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,wt.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,$u))return;const r=wt.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(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.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())vt.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const 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 R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<wt.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 Hi(Xu,32,16),i=e.attributes.position,n=e.getAttribute("color")??new he(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=MI(i.getX(r),i.getY(r),i.getZ(r)),h=_I(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 ss({vertexColors:!0,side:xi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new xt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=_2(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new Pg(this.groundRadius,48),i=new Cs({color:new st(ap,ap,ap),fog:!0});ko.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new xt(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=Ke(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-Ue.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*c6);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Ue.iceAlphaAt(i,qu,r,this.cloudFieldOffset)*h6),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<yd){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}=Ke(e.altitudeDeg,e.azimuthDeg,$n),h=this.cloudTransmission(e),l=this.arrivingIlluminance(e,s,h),u=wt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/$n)**2,p=[0,1,2].map(m=>u[m]*l[m]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const g=p.map(m=>Math.min(wt.BRIGHTEST_RELATIVE,m));d instanceof xt||(this.disposeMesh(d),d=new xt(new Hi(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(g[0],g[1],g[2]),d.scale.setScalar(i)}else{if(!(d instanceof Qn)){this.disposeMesh(d);const g=new se;g.setAttribute("position",new ce(new Float32Array(3),3)),g.setAttribute("color",new ce(new Float32Array(3),3)),d=new Qn(g,Ot.material(Po[Po.length-1].size,!1)),Ot.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/$n*(180/Math.PI),wt.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=vC(),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<yd){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ke(t.altitudeDeg,t.azimuthDeg,$n),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),h=t.radiusDeg??Mr.MEAN_RADIUS_DEG,l=$n*Math.tan(h*mi),u=Math.max(cr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(l/$n)**2,d=new st(...c.map(g=>Math.min(wt.BRIGHTEST_RELATIVE,g/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(cr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Lh?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=Q2(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Lh(new pd({map:Q2(t.phase),color:d,fog:!1,blending:sn,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=a6){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 wt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new st;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,Ot.CONE_SOLID_ANGLE/e)}pointScratch=new nt;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=De.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Rs.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 pd({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Lh(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(ln.radiusDeg(ln.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new ln(`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=_o(t.magnitude,e),s=Y0(n);this.cometKey=i,this.setBodyMesh(i,t.position,hp*(.5+.5*n),new st(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new us($n),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Di,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:qu},0);return}const s=this.lowerCloudCover(),r=de.deckLitUntilDeg(de.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?ye.SUN_MAGNITUDE:e.magnitude),h=de.strength(i,s,a.altitudeDeg,r)*c.scale,{x:l,y:u,z:d}=Ke(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??qu},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??jb,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Ao,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?ye.SUN_MAGNITUDE:e.magnitude,o6),c=ls.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}=Ke(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 Aa,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=Fs.galactic(i,n),r=wt.directionOf(s.centre),a=wt.directionOf(s.rotation),c=wt.directionOf(s.pole),h=new ne().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),l=wt.directionOf(Fs.eclipticPole(i,n)),u=wt.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:wt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new R(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ke(t.altitudeDeg,t.azimuthDeg,1);return new R(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=_o(n.magnitude,e),a=Y0(r);this.setBodyMesh(s,n.position,hp*(.5+.5*r),new st(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=_o(n.magnitude,e),r=Y0(s),a=G6[n.body]??new st(1,1,1),c=new st(a.r*r,a.g*r,a.b*r),h=hp*(.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 Vs(n,s),a=yp(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<I2)continue;const{x:p,y:g,z:m}=Ke(d,f,op);c.push({x:p,y:g,z:m,brightness:_o(u,e),illuminance:this.air.transmittanceFromSpace(h,d).map(v=>v*De.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const l of ZD){if(l.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(l.raHours,l.decDeg);if(u<I2)continue;const{x:f,y:p,z:g}=Ke(u,d,op);this.namedStars.push({star:l,direction:new R(f,p,g).normalize(),altitudeDeg:u})}this.starTiers=Po.map((l,u)=>{const d=c.filter(b=>Bf(b.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),g=new Float32Array(d.length*3),m=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,g.set(b.illuminance,S*3),m[S]=b.phase,v[S]=b.speedFactor});const y=new se;y.setAttribute("position",new ce(f,3)),y.setAttribute("seed",new ce(m.map(b=>b/(2*Math.PI)),1));const x=new ce(new Float32Array(d.length*3),3);y.setAttribute("color",x);let M=this.starTiers[u]?.points;return M?(M.geometry.dispose(),M.geometry=y):(M=new Qn(y,Ot.material(l.size)),Ot.track(M),this.celestialGroup.add(M)),{points:M,colorAttribute:x,brightness:p,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Ot.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 jc(this.celestialGroup,lp,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 st(Ja[0]+(fp[0]-Ja[0])*e,Ja[1]+(fp[1]-Ja[1])*e,Ja[2]+(fp[2]-Ja[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}=Om(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=Pm(lp);this.cloudMesh=new xt(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}=Om(new st(...Ja),t,qu,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new xt(Pm(lp*1.04),e),this.cirrusMesh.renderOrder=U2-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?jc.deckOrder(!0,0,1):U2}cloudLayerOffset(){const e=((this.weather.cloudBaseM??og)-this.observerElevationM)*up;return Math.sign(e||1)*Math.max(Math.abs(e),E6)}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*Mp*this.relativeScale/Math.PI,h=new st(e[0]+sr.r*c,e[1]+sr.g*c,e[2]+sr.b*c);this.layeredClouds?.setLighting(n.clone(),new st(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 O6(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,gp],[this.rainSplashSystem?.points,ja],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:pp[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=H2(vp(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=pp[t],i=e.poolSize,n=yp(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 x=0;x<i;x++){const M=n()*Math.PI*2,b=n()*e.radiusM;s[x*3]=Math.cos(M)*b,s[x*3+1]=Dc+n()*(e.topYM-Dc),s[x*3+2]=Math.sin(M)*b,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,h[x]=.4+n()*1.2}const g=new se;g.setAttribute("position",new ce(s,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new st(...this.baseFogColor)},uTexture:{value:V6(t)},uNearFocusDistance:{value:X2},uHazeDistance:{value:e.radiusM*$2}},v=new Ae({uniforms:m,vertexShader:q6,fragmentShader:Z6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const y=new Qn(g,v);y.renderOrder=dp,this.scene.add(y),this.precipitationPoints=y,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=pp[i];if(this.precipitationUniforms?.uColor.value.copy(wt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*mi,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,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,y=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&g&&m&&v;for(let M=0,b=0;M<c.length;M+=3,b++){if(x&&f[b]>0){if(f[b]-=e,f[b]<=0){const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_,f[b]=0}else{const w=1-f[b]/g[b];c[M+1]=Dc+Math.sin(Math.PI*w)*p[b],c[M]=Ju(c[M]+(r+m[b])*e,n.radiusM),c[M+2]=Ju(c[M+2]+(a+v[b])*e,n.radiusM)}continue}let S=0,E=0;if(y){const w=L6*u[b],_=N6*d[b];S=Math.sin(t*w*Math.PI*2+h[b])*_,E=Math.sin(t*w*Math.PI*2+h[b]+Math.PI/2)*_}if(c[M]+=(r+S)*e,c[M+1]-=n.fallSpeedMPerS*l[b]*e,c[M+2]+=(a+E)*e,c[M]=Ju(c[M],n.radiusM),c[M+2]=Ju(c[M+2],n.radiusM),c[M+1]<Dc){if(x){p[b]=J2*(.2+Math.random()*1.6),g[b]=k6*(.5+Math.random()),f[b]=g[b];const D=Math.random()*Math.PI*2,I=U6*(p[b]/J2);m[b]=Math.cos(D)*I,v[b]=Math.sin(D)*I,c[M+1]=Dc;continue}const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=vp(this.weather.precipitationIntensity);this.rainSystem=pC({count:gp,radiusM:Yh,heightM:_6,bottomYM:F2,overallSpeed:T6,color:B2.clone(),opacity:.85,visibleCount:this.precipitationCount(gp),speedStreak:H2(t),pixelSize:K2,seed:9001,nearFocusDistanceM:X2,hazeDistanceM:Yh*$2,hazeColor:new st(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=dp,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=yp(4242),e=new Float32Array(ja*3),i=new Float32Array(ja),n=new Float32Array(ja),s=new Float32Array(ja);for(let l=0;l<ja;l++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Yh;e[l*3]=Math.cos(u)*d,e[l*3+1]=F2,e[l*3+2]=Math.sin(u)*d,n[l]=j2(G2,V2),i[l]=t()*n[l],s[l]=i[l]/n[l]}const r=new se;r.setAttribute("position",new ce(e,3));const a=new ce(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(ja));const c=new Ae({uniforms:{uMaxSize:{value:C6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:W2.clone()},uTexture:{value:$6()}},vertexShader:Y6,fragmentShader:K6,transparent:!0,depthWrite:!1}),h=new Qn(r,c);h.renderOrder=dp,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*mi;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-vp(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(wt.litBySky(B2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(wt.litBySky(W2,this.baseFogColor));const n=this.weather.windDirectionDeg*mi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Yh,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=q2+(1-q2)*(1-h),u=Z2+(1-Z2)*(1-h);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=K2*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())*Yh;i[c]=Math.cos(l)*u,i[c+2]=Math.sin(l)*u,s[h]=j2(G2,V2),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=Qi.brightnessAt(c,t);h>i&&(e=c,i=h)}const n=e?Math.min(1,Math.max(.1,(B6/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*Mp*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+sr.r*h,this.airlight[1]+sr.g*h,this.airlight[2]+sr.b*h)}const r=this.skyMesh?.material?.color;if(r){const c=s*H6;r.setRGB(1+c*sr.r,1+c*sr.g,1+c*sr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Mp*this.relativeScale,e){const{x:c,y:h,z:l}=Ke(25,e.azimuthDeg,$n);this.lightningLight.position.set(c,h,l)}this.lightningBolt||(this.lightningBolt=new _a($n*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=M6.map(t=>{const e=No.point(t,this.compassPoints),i=new pd({map:J6(e),depthTest:!1,fog:!1}),n=new Lh(i),{x:s,y:r,z:a}=Ke(0,t,P2);return n.position.set(s,r,a),n.scale.set(Zu,Zu,1),n.renderOrder=b6,n.layers.set(rp),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=L2*Math.PI/360,i=Zu*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 mi=Math.PI/180;function cr(o,t,e){return Math.max(t,Math.min(e,o))}function j2(o,t){return o+Math.random()*(t-o)}function Ju(o,t){return(o%(t*2)+t*3)%(t*2)-t}let ju,Qu;function V6(o){switch(o){case"snow":return W6();case"hail":return X6()}}function W6(){if(ju)return ju;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),ju=new Va(t),ju}function X6(){if(Qu)return Qu;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),Qu=new Va(t),Qu}let td;function $6(){if(td)return td;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),td=new Va(t),td}const Y6=`
|
|
8958
8958
|
uniform float uMaxSize;
|
|
8959
8959
|
uniform float uScale;
|
|
8960
8960
|
attribute float aLife;
|
|
@@ -9249,6 +9249,6 @@ ${ei.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery
|
|
|
9249
9249
|
<button id="copy" class="share-copy" type="button">Copy</button>
|
|
9250
9250
|
</div>
|
|
9251
9251
|
</dialog>
|
|
9252
|
-
`;class sh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(sh.TAG)||customElements.define(sh.TAG,sh)}subject;messages=ag;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=kO;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"?ag:await $S(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?xr.frozenLink(t.link(),"0.150.
|
|
9253
|
-
${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.150.1")),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??=Ee(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 mn{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(mn.PLAIN.test(e))return mn.num(e);const i=mn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||mn.num(a)>=60?void 0:mn.num(s)*3600+Number(r)*60+mn.num(a)}const n=mn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?mn.num(n[1])*3600+mn.num(n[2])*60+mn.num(n[3]):/^P/i.test(e)?Yc.seconds(e.toUpperCase()):void 0}static isClock(t){return mn.clock(t)!==void 0}static clock(t){const e=mn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,h={hour:Number(r),minute:Number(a),second:mn.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)}}Pb();sh.register();const xd=Hl.home(),id="compare-account",Tp="start-time",cy="start-clock",Zh="observer",nd="case",sd="account",rd="variant-",Rp=`${xd}/edit/`;class rh extends HTMLElement{static get observedAttributes(){return["src","show-labels",Tp,cy,Zh,Tr,Rr,id]}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 _l(nl,new wf,new _s(["en"]),new od({}),{messages:nl,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=nl;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${Gb}</style>${Hb}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(Ef),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=Kt.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(Ob,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=Ua.preferencesFor(this);this.preferences=e;const i=pg(e,mg),[n,s,r]=i==="en"?[nl,{},void 0]:await Promise.all([WS(i),YS(i),Dy(i)]);if(t!==this.localeToken)return;const a=i!==this.language;this.language=i,this.messages=n,this.tags=new od(s),this.said=new _s(e),this.summaryBuilder=new _l(this.messages,new wf(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 _s(["en"]);tags=new od({});connectedCallback(){Ua.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===Tr||t===Rr)&&this.forwardPlayerAttributes(),t===Zh&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===id&&this.setComparing(this.hasAttribute(id))}forwardPlayerAttributes(){for(const t of[Tr,Rr]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=ka.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(tn.isCase(i)){tn.check(i);const n=tn.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){this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:t}],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?tn.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 ka.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=tn.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,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.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(Zh)?.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===nd))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===nd}editorUrl(){if(!this.currentSrc)return Rp;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${Rp}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${Rp}?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=tn.interpretationEvents(t.json,tn.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?[[Zh,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?[`${Zh}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${xd}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${xd}/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([Tp,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Tr,""]),t.milestones.input.checked||e.push([Rr,""]),t.compare.input.checked&&e.push([id,""]),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,nd,this.messages.shareScopeCase);for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??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=nd,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(sd,this.messages.account,()=>Promise.resolve(r));const a=this.caseSource;a&&tn.interpretationEvents(a.json,tn.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(g=>this.agentName(g)).filter(Boolean).join(", ");n(`case-${d}`,p?this.messages.interpretationBy.replace("{title}",f).replace("{by}",p):f,()=>tn.interpretationOf(u,a.url,g=>ka.recording(g)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${rd}${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:sd;this.interpretationSelect.value=l,l===sd?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(sd,this.messages.account);for(const{index:i,kept:n}of t)e(`${rd}${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(rd)?Number(t.slice(rd.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=mn.clock(this.getAttribute(cy));return(e?mn.elapsedSince(this.plain(t).time,e):void 0)??mn.delta(this.getAttribute(Tp))}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(UO,{detail:{src:t}}))}async runAssessments(){const t=++this.assessmentToken,e=await new yS(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=Bn.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?.[0],i=to(t.time??{},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(rh.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?.[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),uy.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.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,rh.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages.location,r,this.basisOf(t,rh.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=xd,this.infoAppLink.textContent="UFO@home v0.150.1",dn.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=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.0"];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(`
|
|
9252
|
+
`;class sh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(sh.TAG)||customElements.define(sh.TAG,sh)}subject;messages=ag;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=kO;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"?ag:await $S(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?xr.frozenLink(t.link(),"0.150.2"):t.link(),this.fitLink();const n=`<script type="module" src="${e?xr.frozen(t.module,"0.150.2"):xr.current(t.module,import.meta.url,Hl.home())}"><\/script>
|
|
9253
|
+
${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.150.2")),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??=Ee(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 mn{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(mn.PLAIN.test(e))return mn.num(e);const i=mn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||mn.num(a)>=60?void 0:mn.num(s)*3600+Number(r)*60+mn.num(a)}const n=mn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?mn.num(n[1])*3600+mn.num(n[2])*60+mn.num(n[3]):/^P/i.test(e)?Yc.seconds(e.toUpperCase()):void 0}static isClock(t){return mn.clock(t)!==void 0}static clock(t){const e=mn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,h={hour:Number(r),minute:Number(a),second:mn.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)}}Pb();sh.register();const xd=Hl.home(),id="compare-account",Tp="start-time",cy="start-clock",Zh="observer",nd="case",sd="account",rd="variant-",Rp=`${xd}/edit/`;class rh extends HTMLElement{static get observedAttributes(){return["src","show-labels",Tp,cy,Zh,Tr,Rr,id]}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 _l(nl,new wf,new _s(["en"]),new od({}),{messages:nl,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=nl;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${Gb}</style>${Hb}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(Ef),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=Kt.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(Ob,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=Ua.preferencesFor(this);this.preferences=e;const i=pg(e,mg),[n,s,r]=i==="en"?[nl,{},void 0]:await Promise.all([WS(i),YS(i),Dy(i)]);if(t!==this.localeToken)return;const a=i!==this.language;this.language=i,this.messages=n,this.tags=new od(s),this.said=new _s(e),this.summaryBuilder=new _l(this.messages,new wf(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 _s(["en"]);tags=new od({});connectedCallback(){Ua.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===Tr||t===Rr)&&this.forwardPlayerAttributes(),t===Zh&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===id&&this.setComparing(this.hasAttribute(id))}forwardPlayerAttributes(){for(const t of[Tr,Rr]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=ka.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(tn.isCase(i)){tn.check(i);const n=tn.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){this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:t}],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?tn.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 ka.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=tn.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,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.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(Zh)?.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===nd))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===nd}editorUrl(){if(!this.currentSrc)return Rp;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${Rp}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${Rp}?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=tn.interpretationEvents(t.json,tn.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?[[Zh,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?[`${Zh}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${xd}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${xd}/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([Tp,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Tr,""]),t.milestones.input.checked||e.push([Rr,""]),t.compare.input.checked&&e.push([id,""]),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,nd,this.messages.shareScopeCase);for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??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=nd,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(sd,this.messages.account,()=>Promise.resolve(r));const a=this.caseSource;a&&tn.interpretationEvents(a.json,tn.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(g=>this.agentName(g)).filter(Boolean).join(", ");n(`case-${d}`,p?this.messages.interpretationBy.replace("{title}",f).replace("{by}",p):f,()=>tn.interpretationOf(u,a.url,g=>ka.recording(g)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${rd}${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:sd;this.interpretationSelect.value=l,l===sd?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(sd,this.messages.account);for(const{index:i,kept:n}of t)e(`${rd}${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(rd)?Number(t.slice(rd.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=mn.clock(this.getAttribute(cy));return(e?mn.elapsedSince(this.plain(t).time,e):void 0)??mn.delta(this.getAttribute(Tp))}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(UO,{detail:{src:t}}))}async runAssessments(){const t=++this.assessmentToken,e=await new yS(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=Bn.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?.[0],i=to(t.time??{},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(rh.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?.[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),uy.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.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,rh.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages.location,r,this.basisOf(t,rh.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=xd,this.infoAppLink.textContent="UFO@home v0.150.2",dn.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=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.0"];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(`
|
|
9254
9254
|
`)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const hy="rr0-sighting",UO="observerchange",ly="rr0-eyeobserver";class FO extends rh{}function zO(){Pb(),sh.register(),customElements.get(hy)||customElements.define(hy,rh),customElements.get(ly)||customElements.define(ly,FO)}zO();export{Mn as $,Co as A,se as B,st as C,Cc as D,Qn as E,he as F,Pe as G,pd as H,QO as I,Va as J,Lh as K,Pp as L,IA as M,ss as N,Gn as O,wm as P,Xt as Q,_e as R,wl as S,gn as T,_A as U,ks as V,KO as W,en as X,sn as Y,JO as Z,zo as _,Fn as a,vn as a0,we as a1,xi as a2,Hi as a3,Wn as a4,bi as a5,gO as a6,h1 as a7,BO as a8,GO as a9,mx as aA,YO as aB,ts as aC,Os as aD,px as aE,oM as aF,z3 as aG,QC as aH,qd as aI,xm as aJ,Dx as aK,Fg as aL,zg as aM,Ce as aN,Ba as aO,Vl as aP,HO as aa,Wl as ab,jO as ac,qO as ad,jd as ae,Ox as af,fM as ag,XO as ah,ns as ai,Hv as aj,ZO as ak,tP as al,dx as am,Ks as an,eu as ao,r0 as ap,zE as aq,ii as ar,Vo as as,Vp as at,Oi as au,Nr as av,X3 as aw,Ze as ax,WO as ay,$O as az,xt as b,Hu as c,nt as d,ul as e,Da as f,ie as g,ce as h,Cs as i,eP as j,nf as k,es as l,Ki as m,na as n,R as o,FS as p,Ae as q,Ys as r,to as s,dr as t,yt as u,Te as v,iP as w,le as x,VO as y,iE as z};
|