@rr0/ufoathome 0.170.0 → 0.170.1
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.
|
@@ -2435,9 +2435,9 @@ canvas[data-cursor="rotate"] {
|
|
|
2435
2435
|
`;class Ah{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 Ah(e)}static TRAVEL_M=50;get travels(){return this.spanM>Ah.TRAVEL_M}get moved(){return this.spanM>Ah.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(ae(e,t.east,e,t.west).x),Math.abs(ae(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:Ps(0,-s,i,n).lat,south:Ps(0,s,i,n).lat,east:Ps(s,0,i,n).lng,west:Ps(-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 nr{constructor(t,e){this.rotationPassed=t,this.scale=e}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(t){if(t.instrument.mounted)return;const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>nr.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new nr(Math.max(1-(t.instrument.stabilization??0),nr.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,l,h]=nr.HZ;return{eastM:i*nr.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*nr.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*nr.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*nr.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*nr.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*nr.DRIFT_ROLL_DEG*n(s,2.9)}}}class ri{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=Ah.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 l=ae(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=ri.stepHzFor(f);i.push({startMs:r.t,endMs:a.t,speedMPerS:f,eastUnit:d>0?h/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 ri(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=ri.of(t)?.offsetAt(e)??ri.STILL;return i?n:ri.add(n,nr.of(t)?.offsetAt(e))}static stepHzFor(t){return t<ri.SLOWEST_WALK_M_PER_S||t>ri.FASTEST_WALK_M_PER_S?0:ri.REFERENCE_STEP_HZ*Math.pow(t/ri.REFERENCE_SPEED_M_PER_S,ri.CADENCE_EXPONENT)}offsetAt(t){return ri.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/ri.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>ri.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/ri.JOLT_DECAY_S)*Math.sin(2*Math.PI*ri.JOLT_HZ*u),f=h*c*i*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},s=e.rampsOut?n(t-e.endMs,ri.STOP_LURCH_M,ri.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,ri.START_LURCH_M,ri.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 ri.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=ri.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/ri.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:ri.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:ri.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:ri.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 lT{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 zS=["nw","n","ne","e","se","s","sw","w"],hT=24,hf=8,uT=3,dT=8;function uf(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 au(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const fT={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 Ws{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-hT}},a=au(t.bounds),c={};for(const l of Object.keys(r))c[l]=uf(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...zS,"rotate"]){const s=Ws.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=((Ws.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=au(t),r=uf(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=fT[i];let d=a,f=c,p=a+l,m=c+h;return u.left&&(d=Math.min(r.x,p-hf)),u.right&&(p=Math.max(r.x,d+hf)),u.top&&(f=Math.min(r.y,m-hf)),u.bottom&&(m=Math.max(r.y,f+hf)),{x:d,y:f,width:p-d,height:m-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=t.bounds,r=Ws.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(l=>({x:l.x*a,y:l.y*c}))}}static rotateShape(t,e){const i=au(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=au(t.bounds);return t.points.map(i=>uf({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=dT){const n=Ws.vertexPointsFor(t);let s,r=i;return n.forEach((a,c)=>{const l=Math.hypot(e.x-a.x,e.y-a.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(t,e){const i=au(t.bounds),n=uf(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?Ws.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)),l={x:t.bounds.x+s,y:t.bounds.y+r,width:a-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...t,bounds:l,points:h}}static insertVertexNear(t,e){const i=Ws.toLocalPoint(t,e),{points:n}=t;let s=n.length-1,r=1/0;for(let c=0;c<n.length;c++){const l=n[c],h=n[(c+1)%n.length],u=Ws.distanceToSegment(i,l,h);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,l=e.y+a*s;return Math.hypot(t.x-c,t.y-l)}static deleteVertex(t,e){return t.points.length<=uT?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const _1=6,df=_1/2,z2=20,B2=24,H2=9,G2=6,V2=7,W2=6,Fr=4;class $h{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,l=Math.hypot(n,s)/2,h=c?l:n/2,u=c?l:s/2,d=Math.max(n,s)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+H2*f),W2*f)-d:0,m=f>0?d*(1+V2*f)-d:0,g=3*B2*(t.blur??0)+1.5*z2*t.haloScale,v=Math.max(p,m,0)+g+2;return{x:r-h-v,y:a-u-v,width:2*(h+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(${(B2*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,l=Math.max(s,r)/2,h=Math.max(l*(1+H2*e),W2*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(a,c,0,a,c,h);for(let d=0;d<=G2;d++){const f=d/G2,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,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+V2*e);this.ctx.lineWidth=Math.max(1,l*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const p=f/this.starPoints*Math.PI*2+this.roll,m=a+Math.cos(p)*d,g=c+Math.sin(p)*d,v=this.ctx.createLinearGradient(a,c,m,g);v.addColorStop(0,this.withAlpha(t.color,e*.55)),v.addColorStop(.35,this.withAlpha(t.color,e*.22)),v.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=v,this.ctx.beginPath(),this.ctx.moveTo(a,c),this.ctx.lineTo(m,g),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const i=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!i)return t.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*e);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),n=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!n)return t;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(t){this.ctx.fillStyle=this.dazzledFill(t,t.brightness??0),this.tracePath(t),this.ctx.fill()}paintGhost(t,e){this.ctx.save(),this.tracePath(t),this.ctx.setLineDash([e*3,e*2]),this.ctx.lineWidth=e,this.ctx.strokeStyle=t.color,this.ctx.stroke(),this.ctx.restore()}tracePath(t){if(this.ctx.beginPath(),t.kind==="oval"){const{x:e,y:i,width:n,height:s}=t.bounds,r=n/2,a=s/2;this.ctx.ellipse(e+r,i+a,r,a,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:n,height:s}=t.bounds;this.ctx.save(),this.ctx.translate(e+n/2,i+s/2),this.ctx.rotate(t.angle),this.ctx.translate(-n/2,-s/2),t.points.forEach((r,a)=>{a===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=z2*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(Ws.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of Ws.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Fr,Fr,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(Ws.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=$h.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,Fr+2,Fr+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,Fr,Fr,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Fr+2,Fr+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Fr+5,s.picture.y-Fr-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,l,h,u=[])=>{n.setLineDash(u),n.lineWidth=h+2,n.strokeStyle="rgba(0, 0, 0, 0.6)",c(),n.lineWidth=h,n.strokeStyle=l,c(),n.setLineDash([])},r=(c,l)=>()=>{n.beginPath(),n.arc(c.x,c.y,l,0,2*Math.PI),n.stroke()},a=(c,l,h)=>()=>{const[u,d]=h?[l,l]:[l,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(Ws.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 zS){const n=t[i];this.ctx.fillRect(n.x-df,n.y-df,_1,_1)}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,df+1,df+1,0,0,2*Math.PI),this.ctx.fill())}}const X2=.05,$2=.08,Y2=2,K2=3,pT=14,mT=.02;class gT{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}}Gc.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,X2);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,X2)}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*Y2),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*Y2),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*K2),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(mT*t.sampleRate)),s=Math.round(K2*pT);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],c*(1-l/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,$2/3);const n=i+$2;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 Kr{static KINDS=["beams","launches","reentries"];static statedKinds(t){return Object.keys(t??{}).filter(e=>Array.isArray(t[e])&&t[e].length>0)}static isEmpty(t){return Kr.statedKinds(t).length===0}static written(t){const e=Kr.statedKinds(t);if(e.length===0)return;const i={};for(const n of e)i[n]=t[n];return i}static read(t,e){const i=e,n={};for(const r of Kr.statedKinds(t))n[r]=t[r];for(const r of Kr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&Kr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...l}=i;s=Kr.isReading(l)?l:void 0}return{skyEvents:Kr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function Wu(o){return[...o].sort((t,e)=>t.t-e.t)}function Pm(o,t){let e;for(const i of Wu(o)){if(i.t>t)break;e=i}return e}const Nm=Math.PI/180,ff=180/Math.PI;class ha{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*Nm/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new ha(t.projection,e,i)}degToPx(t){const e=t*Nm;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*ff:2*Math.atan(t/(2*this.focalPx))*ff}angleDegToRadiusPx(t){const e=t*Nm;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*ff:Math.atan(t/this.focalPx)*ff}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(hi.angularWidthDeg(t))}}class fn{static fovOf(t,e){return Pe(t,e)?.fovDeg??zi.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)<fn.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<fn.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=ha.of(t.instrument,hi.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,Pe(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=Pe(t,s.t),c=ha.of(t.instrument,hi.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:l,shape:h}of s.shapes){const u=n.get(l),d=i.get(l);if(n.set(l,h),!u||!d){i.set(l,h);continue}const f=Object.fromEntries(Object.entries(h).filter(([g,v])=>g!=="bounds"&&g!=="points"&&JSON.stringify(v)!==JSON.stringify(u[g]))),p={...d,...f},m=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);fn.near(m,h)?(e.add(`${r}:${l}`),i.set(l,p)):i.set(l,h)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=fn.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:zi.frameWidthPx(t.instrument,hi.CANVAS_HEIGHT_PX)/2,y:hi.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=fn.OFF_CANVAS_DEG?Math.sign(e)*fn.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=zi.frameWidthPx(e,hi.CANVAS_HEIGHT_PX)/2,s=zi.frameWidthPx(t.instrument,hi.CANVAS_HEIGHT_PX)/2,r=hi.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),l=i?.get(a.t)??c,h=ha.of(e,hi.CANVAS_HEIGHT_PX,l),u=ha.of(t.instrument,hi.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,m=f.y+f.height/2-r,g=Math.hypot(p,m),v=g===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(g))/g,M={...f,x:s+p*v-f.width/2,y:r+m*v-f.height/2};return{...d,shape:{...d.shape,bounds:M}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=Pe(t,n.t),r=this.fovOf(t,n.t),a=ha.of(t.instrument,hi.CANVAS_HEIGHT_PX,r);let c=!1;const l=n.shapes.map(h=>{const u=e(h.shape,a,s);return u===h.shape?h:(c=!0,{...h,shape:u})});c&&i.addKeyframe(n.t,l)}}}class fs{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(fs.isRelative(t)){const i=fs.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return fs.isAbsolute(t)&&e.origin?fs.toLocal(t,e.origin):void 0}static restated(t,e,i){if(fs.isRelative(t)){const s=fs.referenceOf(t,i);return s?fs.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=fs.toGeo(e,i.origin);return{lat:fs.degrees(n.lat),lng:fs.degrees(n.lng)}}static relative(t,e,i){const n={eastM:fs.metres(t),northM:fs.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=ae(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return Ps(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 jn{static restatedDecor(t){const e=jn.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=jn.restated(i.saidPosition,i,jn.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=jn.restated(r.saidPosition,r,jn.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=jn.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=fs.toLocal({lat:s.lat,lng:s.lng},i),a=jn.restated(s.saidPosition,r,jn.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=jn.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?jn.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},jn.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}=Cr(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return fs.restated(t,{eastM:e.eastM,northM:e.northM},i)}}class ai{constructor(t,e,i){this.params=t,this.from=e,this.origin=t.path[0],this.cos0=Math.cos(t.path[0].lat*Math.PI/180),this.points=t.path.map(r=>this.local(r)),this.cumulative=[0];for(let r=1;r<this.points.length;r++){const a=this.points[r-1],c=this.points[r];this.cumulative.push(this.cumulative[r-1]+Math.hypot(c.e-a.e,c.n-a.n))}this.distances=[];let n=0;for(let r=e;r<=i+ai.BEYOND_MS;r+=ai.STEP_MS)this.distances.push(n),n+=this.speedAt(r)*ai.STEP_MS/1e3;this.shift=this.project(this.local(t.through))-this.distanceAt(t.through.t);const s=[];for(let r=e;r<=i;r+=ai.SAMPLE_MS)s.push({t:r,place:this.placeAt(r)});this.sampleOrigin=s[0].place,this.sampleCos=Math.cos(this.sampleOrigin.lat*Math.PI/180),this.samples=s.map(({t:r,place:a})=>({t:r,e:(a.lng-this.sampleOrigin.lng)*Math.PI/180*ai.R*this.sampleCos,n:(a.lat-this.sampleOrigin.lat)*Math.PI/180*ai.R}))}static R=63710088e-1;static STEP_MS=100;static SAMPLE_MS=2e3;static BEYOND_MS=8e4;origin;cos0;points;cumulative;distances;shift;samples;sampleOrigin;sampleCos;get start(){return this.sampleOrigin}stateAt(t){const e=this.samples,i=e.length-2;let n=0;for(;n<i&&e[n+1].t<t;)n++;const s=e[n],r=e[n+1],a=(t-s.t)/(r.t-s.t),c=p=>[n>0?p[n-1]:2*p[n]-p[n+1],p[n],p[n+1],n+2<p.length?p[n+2]:2*p[n+1]-p[n]],l=e.map(p=>p.e),h=e.map(p=>p.n),u=ai.catmull(c(l),a),d=ai.catmull(c(h),a),f=(Math.atan2(ai.slope(c(l),a),ai.slope(c(h),a))*180/Math.PI%360+360)%360;return{eastM:u,northM:d,roadDeg:f,lat:this.sampleOrigin.lat+d/ai.R*180/Math.PI,lng:this.sampleOrigin.lng+u/(ai.R*this.sampleCos)*180/Math.PI}}bearingAt(t,e){const i=this.local(this.placeAt(t)),n=this.local(e);return(Math.atan2(n.e-i.e,n.n-i.n)*180/Math.PI%360+360)%360}get sampleTimes(){return this.samples.map(t=>t.t)}placeAt(t){const e=this.along(this.distanceAt(t)+this.shift);return{lat:this.origin.lat+e.n/ai.R*180/Math.PI,lng:this.origin.lng+e.e/(ai.R*this.cos0)*180/Math.PI}}distanceAt(t){const e=Math.max(0,Math.min(this.distances.length-1,Math.round((t-this.from)/ai.STEP_MS)));return this.distances[e]}speedAt(t){const e=this.params.speedDivisors?ai.linear(this.params.speedDivisors.map(({t:i,divisor:n,step:s})=>({t:i,value:n,step:s})),t):1;return ai.linear(this.params.speeds.map(({t:i,kmh:n,step:s})=>({t:i,value:n,step:s})),t)/3.6/e}local(t){return{e:(t.lng-this.origin.lng)*Math.PI/180*ai.R*this.cos0,n:(t.lat-this.origin.lat)*Math.PI/180*ai.R}}along(t){const e=this.points;let i=0;for(;i<e.length-2&&this.cumulative[i+1]<t;)i++;const n=e[i],s=e[i+1],r=(t-this.cumulative[i])/(this.cumulative[i+1]-this.cumulative[i]);return{e:n.e+(s.e-n.e)*r,n:n.n+(s.n-n.n)*r}}project(t){let e=1/0,i=0;for(let n=0;n<this.points.length-1;n++){const s=this.points[n],r=this.points[n+1],a=r.e-s.e,c=r.n-s.n,l=Math.max(0,Math.min(1,((t.e-s.e)*a+(t.n-s.n)*c)/(a*a+c*c))),h=Math.hypot(s.e+a*l-t.e,s.n+c*l-t.n);h<e&&(e=h,i=this.cumulative[n]+l*Math.hypot(a,c))}return i}static linear(t,e){if(e<=t[0].t)return t[0].value;for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];if(s.step&&e<s.t)return n.value;if(e<=s.t)return n.value+(s.value-n.value)*(e-n.t)/(s.t-n.t)}return t[t.length-1].value}static catmull([t,e,i,n],s){return .5*(2*e+(i-t)*s+(2*t-5*e+4*i-n)*s*s+(3*e-t-3*i+n)*s**3)}static slope([t,e,i,n],s){return .5*(i-t+2*(2*t-5*e+4*i-n)*s+3*(3*e-t-3*i+n)*s*s)}}class je{constructor(t,e,i,n,s,r){this.drive=t,this.eye=e,this.lookAhead=i,this.lean=n,this.watch=s,this.times=t.sampleTimes;const a=i.pitchShare??1;this.aimed=[];for(const c of this.times){const l=t.bearingAt(c,i.target),h=this.aimed[this.aimed.length-1];this.aimed.push(h===void 0?l:h+je.signed(l-h))}this.pitched=this.times.map(c=>r(c)*a)}static STEP_MS=250;static DENSE_MS=50;static SETTLED_MS=700;static TURN_S=.4;static TURN_S_PER_DEG=.5/150;static ROAD_PITCH_DEG=-1;static SHOULDER={x:-.08,y:0,z:-.07};static TWIST_FROM_DEG=60;aimed;pitched;times;poses(t,e){const i=[];for(let u=t;u<e;u+=je.STEP_MS)i.push(u);i.push(e);const n=new Map(i.map(u=>{const d=this.sample(u);return[u,je.signed(d.headingDeg-d.roadDeg)]})),s=u=>n.get(i.reduce((d,f)=>Math.abs(f-u)<Math.abs(d-u)?f:d)),r=this.schedule(s,e),a=this.watch?.t,c=r.map(([u,d],f)=>{if(f===0)return 0;if(u===a&&this.lean)return this.lean.params.turnS;const p=this.sample(u);return je.turnS(this.target(r[f-1][1],p),this.target(d,p))}),l=new Set(i),h=r.map(([u],d)=>[u,c[d]]);this.lean&&h.push([this.lean.t,this.lean.params.turnS],[this.lean.t+this.lean.params.holdS*1e3,this.lean.params.turnS]);for(const[u,d]of h){const f=Math.round(u+d*1e3+je.SETTLED_MS)+je.DENSE_MS;for(let p=Math.round(u);p<f;p+=je.DENSE_MS)p>=t&&p<=e&&l.add(p)}return[...l].sort((u,d)=>u-d).map(u=>{const d=this.sample(u),[f,p]=this.gaze(r,c,d),m=this.drive.stateAt(u);return{t:u,headingDeg:f,pitchDeg:p,eye:this.eyeAt(u,je.signed(f-d.roadDeg)),roadDeg:m.roadDeg,lat:m.lat,lng:m.lng}})}schedule(t,e){const i=[],n=this.lookAhead,s=this.watch?.t??e;let r=0;for(;r<s;){if(Math.abs(t(r))<=n.glanceBeyondDeg){(i.length===0||i[i.length-1][1]!=="watch")&&i.push([r,"watch"]),r+=je.STEP_MS;continue}if(i.push([r,"glance"]),r+=n.glanceS*1e3,r>=s)break;i.push([r,"road"]),r+=n.roadS*1e3}if(!this.watch)return i;const a=this.watch.params;r=s,i.push([r,"mirror"]),r+=a.firstS*1e3;let c=0;for(;r<e;){const l=r<a.glancesUntil&&c%2===0?"glance":"road";i.push([r,l]),r+=(l==="glance"?a.glanceS:a.roadS)*1e3,i.push([r,"mirror"]),r+=a.mirrorS*1e3,c++}return i}sample(t){const e=this.times,i=e.length-2;let n=0;for(;n<i&&e[n+1]<t;)n++;const s=(t-e[n])/(e[n+1]-e[n]),r=a=>[n>0?a[n-1]:2*a[n]-a[n+1],a[n],a[n+1],n+2<a.length?a[n+2]:2*a[n+1]-a[n]];return{t,roadDeg:this.drive.stateAt(t).roadDeg,headingDeg:(ai.catmull(r(this.aimed),s)%360+360)%360,pitchDeg:ai.catmull(r(this.pitched),s),eye:this.eyeAt(t,0)}}target(t,e){const{roadDeg:i,headingDeg:n,pitchDeg:s,eye:r}=e;if(t==="glance")return[n,s];if(t==="watch"){const u=je.signed(n-i),d=this.lookAhead.keepDeg,f=u-d*Math.tanh(u/d),p=u?f/u:0;return[je.normalized(i+f),je.ROAD_PITCH_DEG+(s-je.ROAD_PITCH_DEG)*p]}if(t==="road"||!this.watch)return[i,je.ROAD_PITCH_DEG];const a=this.watch.params.mirror,c={x:a.x-r.x,y:a.y-r.y,z:a.z-r.z},l=Math.atan2(-c.x,-c.z)*180/Math.PI,h=Math.atan2(c.y,Math.hypot(c.x,c.z))*180/Math.PI;return[je.normalized(i-l),h]}gaze(t,e,i,n){const s=i.t;let r=n??0;if(n===void 0&&s>=t[0][0])for(let g=0;g<t.length;g++)t[g][0]<=s&&(r=g);const[a,c]=this.target(t[r][1],i);if(r===0)return[a,c];const l=e[r]*1e3,h=s-t[r][0];if(h>l+je.SETTLED_MS)return[a,c];const[u,d]=this.gaze(t,e,i,r-1);if(h<l){const g=h/l,v=-2*g**3+3*g*g+(g**3-g*g)*Mn.ARRIVAL;return[je.normalized(u+je.signed(a-u)*v),d+(c-d)*v]}const f=je.signed(a-u),p=h-l,m=Mn.ARRIVAL/l*p*Math.exp(-p/Math.min(Mn.SETTLE_MS,.4*l));return[je.normalized(a+f*m),c+(c-d)*m]}leanAt(t){if(!this.lean)return 0;const{holdS:e,turnS:i}=this.lean.params,n=(t-this.lean.t)/1e3;return n<0||n>e+i?0:je.smooth(Math.min(1,n/i,(e+i-n)/i))}eyeAt(t,e){const i=this.leanAt(t),n=this.lean?.params.offsetM??{x:0,y:0,z:0},s=je.smooth((Math.abs(e)-je.TWIST_FROM_DEG)/(180-je.TWIST_FROM_DEG)),r=je.SHOULDER;return{x:this.eye.x+n.x*i+r.x*s,y:this.eye.y+n.y*i+r.y*s,z:this.eye.z+n.z*i+r.z*s}}static turnS(t,e){return je.TURN_S+je.TURN_S_PER_DEG*Math.hypot(je.signed(e[0]-t[0]),e[1]-t[1])}static smooth(t){const e=Math.min(1,Math.max(0,t));return e*e*e*(10-15*e+6*e*e)}static signed(t){return((t+540)%360+360)%360-180}static normalized(t){return(t%360+360)%360}}const Lm=Math.PI/180;class Ht{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Ht.collect(this.motionKeys,s.t,s.motions),Ht.collect(this.turnKeys,s.t,s.turns),Ht.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;turnKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Ht.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Ht.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Ht.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=Pe(t,0),s=Pe(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ae(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Ht.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Ht.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Ht.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*Lm,n=e*Lm;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const m=i+n+1>>1;e[m].t>t?n=m-1:i=m}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Ht.lerp(r.carried.eastM,a.carried.eastM,c):Ht.lerp(r.eastM,a.eastM,c),u=l?l.northM+Ht.lerp(r.carried.northM,a.carried.northM,c):Ht.lerp(r.northM,a.northM,c),d={widthM:Ht.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Ht.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Ht.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Ht.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Ht.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Ht.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Ht.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=Ht.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+m+d.heightM/2}else p=Ht.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,modelParameters:this.body.modelParameters,flicker:this.body.flicker,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Ht.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Ht.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:Ht.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Ht.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Ht.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Ht.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),...this.turnKeys.size>0?{turns:Ht.channelsAt(this.turnKeys,t,0)}:{},lights:this.lightsAt(t),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Ht.lerp(n.lengthM,s.lengthM,i),widthM:Ht.lerp(n.widthM,s.widthM,i),luminanceCdM2:Ht.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){if(!("upM"in t.vertical))return this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2;const e=t.vertical.fromGround;if(!e)return t.vertical.upM;const i=t.vertical.upM+this.ground.heightAt(e.eastM,e.northM);return Math.max(i,this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.sizeM.heightM/2)}groundUnderFootprint(t,e,i,n){const s=n*Lm,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Ht.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Ht.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Ht.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Ht.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Ht.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Ht.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Ht.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Ht.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Ht.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Ht.rgbOf(t),s=Ht.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Ht.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class Is{static ANONYMOUS_OBSERVER="observer";static observerId(t){return t.observer?.id??Is.ANONYMOUS_OBSERVER}static shapeIds(t){const e=new Set(t.timeline.sourceIds);for(const i of t.events??[])if(i.eventType==="appearance")for(const n of i.params?.parts??[])e.add(n.sourceId);return[...e]}static ids(t){const e=new Map,i=(n,s)=>{n!==void 0&&e.set(n,[...e.get(n)??[],s])};i(Is.observerId(t),"observer");for(const n of Is.shapeIds(t))i(n,"shape");for(const n of t.timeline.allGroups)i(n.id,"group");for(const n of t.interpretation?.bodies??[])i(n.id,"body");for(const n of t.decor)i(n.id,"decor");return e}static kindOf(t,e){if(e===void 0)return;const i=Is.ids(t).get(e);return i?.length===1?i[0]:void 0}static partOf(t){const e=t?.indexOf("/")??-1;if(!(t===void 0||e<=0||e===t.length-1))return{element:t.slice(0,e),part:t.slice(e+1)}}static hasPart(t,e,i){if(e==="body")return!0;if(e!=="decor")return!1;const n=t.decor.find(s=>s.id===i.element);return!!(n?.lights?.some(s=>s.id===i.part)||n?.groups?.some(s=>s.id===i.part))}static isObserver(t,e){return e.who===Is.observerId(t)}static isPhenomenon(t,e){return e.who===void 0?!1:t.timeline.groupOf(e.who)!==void 0||Is.shapeIds(t).includes(e.who)}static within(t,e){const i=new Set([e]),n=s=>{for(const r of t.timeline.groupOf(s)?.members??[])i.has(r)||(i.add(r),n(r))};return n(e),i}static renamed(t,e,i){if(e!==i)for(const n of t.events??[])n.who===e&&(n.who=i)}static issues(t){const e=[],i=Is.ids(t);for(const[n,s]of i)s.length>1&&e.push({kind:"duplicate-id",id:n,path:s.join(", ")});return(t.events??[]).forEach((n,s)=>{const r=Is.partOf(n.who);r&&i.get(r.element)?.length===1&&Is.hasPart(t,i.get(r.element)[0],r)||(n.who===void 0||!i.has(n.who))&&e.push({kind:"unknown-who",id:n.who??"",path:`events.${s}.who`})}),e}}class xe{constructor(t,e,i){this.travel=t;const n=t.params,s=t.until??i;let r=xe.unit(n.from),a=xe.towards(r,xe.unit(n.towards));const c=e.map(h=>{const u=h.params,d=u.side==="left"?1:-1;return{from:h.t,to:h.until??h.t,radians:u.byDeg*Math.PI/180*(u.seenFrom==="craft"?-d:d)}}),l=xe.STEP_MS;for(let h=t.t;h<=s;h+=l){this.directions.push(xe.direction(r));for(const f of c){const p=f.to-f.from;if(p<=0)continue;const m=f.radians*(xe.smooth((h+l-f.from)/p)-xe.smooth((h-f.from)/p));m&&(a=xe.add(xe.scale(a,Math.cos(m)),xe.scale(xe.cross(a,r),Math.sin(m))))}const u=xe.speedAt(n.speeds,h)*l/1e3*Math.PI/180,d=xe.add(xe.scale(r,Math.cos(u)),xe.scale(a,Math.sin(u)));a=xe.add(xe.scale(a,Math.cos(u)),xe.scale(r,-Math.sin(u))),r=d}}static STEP_MS=5;directions=[];at(t){const e=Math.round((t-this.travel.t)/xe.STEP_MS);return this.directions[Math.max(0,Math.min(this.directions.length-1,e))]}sizeAt(t){const e=this.travel.params;return e.sizeBy!=="altitude"?e.sizeDeg:e.sizeDeg*Math.max(.1,Math.sin(Math.max(this.at(t).altitudeDeg,1)*Math.PI/180))}static speedAt(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].degPerS;for(let i=1;i<t.length;i++){const n=t[i-1],s=t[i];if(s.step&&e<s.t)return n.degPerS;if(e<s.t)return n.degPerS+(s.degPerS-n.degPerS)*xe.smooth((e-n.t)/(s.t-n.t))}return t[t.length-1].degPerS}static smooth(t){const e=Math.max(0,Math.min(1,t));return e*e*(3-2*e)}static unit(t){const e=t.azimuthDeg*Math.PI/180,i=t.altitudeDeg*Math.PI/180;return[Math.cos(i)*Math.sin(e),Math.cos(i)*Math.cos(e),Math.sin(i)]}static direction(t){return{azimuthDeg:(Math.atan2(t[0],t[1])*180/Math.PI%360+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,t[2])))*180/Math.PI}}static towards(t,e){const i=xe.add(e,xe.scale(t,-xe.dot(t,e))),n=Math.hypot(...i)||1;return xe.scale(i,1/n)}static toScreen(t,e,i){const[n,s,r]=xe.basis(e,i),a=xe.unit(t),c=xe.dot(a,n);return[xe.dot(a,s)/c,xe.dot(a,r)/c]}static fromScreen(t,e,i,n){const[s,r,a]=xe.basis(i,n),c=[s[0]+t*r[0]+e*a[0],s[1]+t*r[1]+e*a[1],s[2]+t*r[2]+e*a[2]],l=Math.hypot(...c);return xe.direction([c[0]/l,c[1]/l,c[2]/l])}static basis(t,e){const i=t*Math.PI/180,n=e*Math.PI/180;return[[Math.cos(n)*Math.sin(i),Math.cos(n)*Math.cos(i),Math.sin(n)],[Math.cos(i),-Math.sin(i),0],[-Math.sin(n)*Math.sin(i),-Math.sin(n)*Math.cos(i),Math.cos(n)]]}static dot(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}static cross(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}static add(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}static scale(t,e){return[t[0]*e,t[1]*e,t[2]*e]}}class Io{constructor(t,e){this.sighting=t,this.events=e}static FOV_DEG=60;keyframes(){const t=this.events.filter(c=>c.eventType==="look").sort((c,l)=>c.t-l.t),e=this.events.filter(c=>c.eventType==="walk").sort((c,l)=>c.t-l.t),i=this.events.filter(c=>c.eventType==="follow").sort((c,l)=>c.t-l.t);if(t.length===0&&e.length===0)return[];const n=new Set([0]);for(const c of[...t,...e,...i])n.add(c.t),c.until!==void 0&&n.add(c.until);const s=c=>{let l;for(const h of e){const u=h.params;if(c<=h.t)return l??u.from;if(h.until===void 0||c>=h.until)l=u.to;else return}return l??this.sighting.event.place?.[0]},r=c=>([...t].reverse().find(h=>h.t<=c)??t[0])?.params??{headingDeg:0,pitchDeg:0},a=[...n].sort((c,l)=>c-l).flatMap(c=>{const l=s(c);if(!l)return[];const h=r(c);return[{t:c,pose:Io.pose(l,h.headingDeg,h.pitchDeg,h.fovDeg)}]});for(const c of a)this.sighting.observerTrack.addKeyframe(c.t,c.pose);for(const c of i)this.follow(c,r(c.t));return[...this.sighting.observerTrack.allKeyframes]}follow(t,e){const i=t.params;if(this.followSky(t,e))return;const n=this.sighting.interpretation?.bodies.find(h=>h.id===i.target);if(!n)return;const s={heightAt:()=>0},r=h=>Ht.eyeOf(this.sighting,h,s),a=new Ht(n,s,r),c=t.until??1/0;let l=e;for(const h of n.track){if(h.t<=t.t||h.t>=c)continue;const u=a.at(h.t),d=r(h.t),f=this.sighting.observerTrack.getInterpolatedPoseAt(h.t);if(!u||!d||!f)continue;const p=u.eastM-d.eastM,m=u.northM-d.northM,g=u.upM-d.upM;l={headingDeg:(Math.atan2(p,m)*180/Math.PI%360+360)%360,pitchDeg:Math.atan2(g,Math.hypot(p,m))*180/Math.PI},this.sighting.observerTrack.addKeyframe(h.t,{...f,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}if(Number.isFinite(c)){const h=this.sighting.observerTrack.getInterpolatedPoseAt(c);h&&this.sighting.observerTrack.addKeyframe(c,{...h,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}}static FOLLOW_SKY_MS=25;static CATCH_UP_MS=900;static OVERHEAD_DEG=78;static HIGHEST_PITCH_DEG=88;followSky(t,e){const i=t.params,n=Is.within(this.sighting,i.target),s=this.sighting.events??[],r=s.find(v=>v.eventType==="travel"&&v.who!==void 0&&n.has(v.who));if(!r)return!1;const a=this.sighting.event.durationSeconds!==void 0?this.sighting.event.durationSeconds*1e3:r.until??t.t,c=new xe(r,s.filter(v=>v.eventType==="turn"&&v.who!==void 0&&n.has(v.who)),a),l=t.until??a,h=(i.lagS??0)*1e3,u=(i.reactionS??0)*1e3,d=[],f=this.sighting.sampleMs??Io.FOLLOW_SKY_MS;for(let v=t.t;v<=l;v+=f)d.push(v);const p=d.map(v=>c.at(Math.max(r.t,v-h))),m=p.map(v=>v.azimuthDeg),g=p.flatMap((v,M)=>v.altitudeDeg>Io.OVERHEAD_DEG?[M]:[]);if(g.length>0){const v=Math.max(0,g[0]-1),M=Math.min(d.length-1,g[g.length-1]+1),x=m[v],y=(m[M]-x+540)%360-180;for(let w=v;w<=M;w++)m[w]=((x+y*xe.smooth((w-v)/(M-v)))%360+360)%360}return d.forEach((v,M)=>{const x=xe.smooth((v-t.t-u)/Io.CATCH_UP_MS),y=(m[M]-e.headingDeg+540)%360-180,w=Math.min(p[M].altitudeDeg,Io.HIGHEST_PITCH_DEG),S=this.sighting.observerTrack.getInterpolatedPoseAt(v)??this.sighting.observerTrack.getLatestPoseAt(v);if(!S)return;const E=b=>Math.round(b*100)/100;this.sighting.observerTrack.addKeyframe(v,{...S,headingDeg:E(((e.headingDeg+y*x)%360+360)%360),pitchDeg:E(e.pitchDeg+(w-e.pitchDeg)*x)})}),!0}static pose(t,e,i,n=Io.FOV_DEG){return{lat:t.lat,lng:t.lng,elevationM:0,headingDeg:e,pitchDeg:i,fovDeg:n}}}class $o{constructor(t,e,i,n){this.body=t,this.events=e,this.endMs=i,this.sampleMs=n}static SAMPLE_MS=250;track(){const t=new Map,e=l=>{const h=t.get(l.t);t.set(l.t,h?{...h,...l,motions:{...h.motions,...l.motions},...h.turns||l.turns?{turns:{...h.turns,...l.turns}}:{},...h.lights||l.lights?{lights:{...h.lights,...l.lights}}:{}}:l)};for(const l of this.body.track)e({...l});const i=[...this.events].sort((l,h)=>l.t-h.t),n=new Map,s=new Map,r=new Map;let a=0;for(const l of this.body.track){for(const[h,u]of Object.entries(l.motions??{}))n.set(h,u);for(const[h,u]of Object.entries(l.turns??{}))s.set(h,u);for(const[h,u]of Object.entries(l.lights??{}))r.set(h,u);l.attitude?.headingDeg!==void 0&&(a=l.attitude.headingDeg)}let c=this.startPlace();for(const l of i){const h=$o.partOf(l.who,this.body.id);if(h!==void 0&&(l.eventType==="light"||l.eventType==="blink")){for(const u of this.leavesOf(h))this.switchLight(u,l,r,e,d=>t.get(d)?.lights?.[u]);continue}if(h!==void 0){if(l.eventType!=="spin"&&l.eventType!=="turn")continue;const u=s.get(h)??0,d=l.until??l.t,f=l.eventType==="spin"?u+360*l.params.turnsPerS*(d-l.t)/1e3:l.params.headingDeg;e({t:l.t,turns:{[h]:u}}),e({t:d,turns:{[h]:f}}),s.set(h,f);continue}if((l.eventType==="motion"||l.eventType==="spin")&&l.params?.motion){const u=l.params,d=u.motion,f=n.get(d)??0,p=l.until??l.t,m=l.eventType==="motion"?u.to:f+u.turnsPerS*(p-l.t)/1e3;e({t:l.t,motions:{[d]:f}}),e({t:p,motions:{[d]:m}}),n.set(d,m)}else if(l.eventType==="rise"&&c){const u=l.params,d=l.until??l.t,f=u.angleDeg*Math.PI/180,p=(u.headingDeg??0)*Math.PI/180,m=c,g=v=>{const M=u.stops===!1?v*v:v*v*v*(10-15*v+6*v*v),x=u.distanceM*M;return{eastM:m.eastM+x*Math.sin(f)*Math.sin(p),northM:m.northM+x*Math.sin(f)*Math.cos(p),aboveGroundM:m.aboveGroundM+x*Math.cos(f)}};for(let v=l.t;v<d;v+=this.sampleMs??$o.SAMPLE_MS)e($o.key(v,g((v-l.t)/(d-l.t))));c=g(1),e($o.key(d,c))}else if(l.eventType==="turn"){const u=l.params;e({t:l.t,attitude:{headingDeg:a}}),e({t:l.until??l.t,attitude:{headingDeg:u.headingDeg}}),a=u.headingDeg}else l.eventType==="vanish"&&e({t:l.t,present:!1})}return[...t.values()].sort((l,h)=>l.t-h.t)}static ride(t,e,i){const n=e.params,s=e.until??1/0,r=new Map(t.track.map(a=>[a.t,{...a}]));for(const a of i.track){if(a.t<e.t||a.t>s||(a.present===!1&&r.set(a.t,{...r.get(a.t),t:a.t,present:!1}),a.eastM===void 0||a.northM===void 0))continue;const c=(a.onGround?0:a.altitudeAboveGroundM??0)+n.aboveM;r.set(a.t,{...r.get(a.t),t:a.t,eastM:a.eastM,northM:a.northM,altitudeAboveGroundM:c})}return[...r.values()].sort((a,c)=>a.t-c.t)}switchLight(t,e,i,n,s){const r=i.get(t)??0,a=e.eventType==="light"?e.until:e.until??this.endMs,c=(l,h)=>n({t:l,lights:{[t]:h}});if(e.t>0&&s(e.t-1)===void 0&&c(e.t-1,r),e.eventType==="light"){const l=e.params.cdM2;if(c(e.t,l),a===void 0){i.set(t,l);return}c(a-1,l)}else{const l=e.params;if(a===void 0)return;const h=l.cdM2??r;let u=e.t,d=!0;for(;u<a;){const f=Math.min(Math.round(u+1e3*(d?l.onS:l.offS)),a);if(f<=u)break;c(u,d?h:0),c(f-1,d?h:0),u=f,d=!d}}c(a,r),i.set(t,r)}leavesOf(t,e=new Set){const i=this.body.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}startPlace(){const t=this.body.track.find(e=>e.eastM!==void 0&&e.northM!==void 0);return t&&{eastM:t.eastM,northM:t.northM,aboveGroundM:t.onGround?0:t.altitudeAboveGroundM??0}}static key(t,e){return e.aboveGroundM<=0?{t,eastM:e.eastM,northM:e.northM,onGround:!0}:{t,eastM:e.eastM,northM:e.northM,altitudeAboveGroundM:e.aboveGroundM}}}class Nd{constructor(t,e,i){this.object=t,this.events=e,this.endMs=i}lights(){const t=new Map,e=[...this.events].sort((i,n)=>i.t-n.t);for(const i of e){const n=Nd.partOf(i.who,this.object.id);if(!(n===void 0||i.eventType!=="light"&&i.eventType!=="blink"))for(const s of this.leavesOf(n)){const r=this.object.lights?.find(a=>a.id===s);r&&t.set(s,this.switched(r,t.get(s)??[],i))}}return(this.object.lights??[]).map(i=>t.has(i.id)?{...i,keyframes:t.get(i.id)}:i)}switched(t,e,i){const n=Nd.stateAt(t,e,i.t),s=i.eventType==="light"?i.until:i.until??this.endMs,r=[];if(i.eventType==="light")r.push({t:i.t,intensity:i.params.intensity,pattern:n.pattern});else{const c=i.params,l=c.onS+c.offS;if(s===void 0||l<=0)return e;const h=l*1e3,u=(-i.t/h%1+1)%1,d={kind:"flash",perMinute:60/l,dutyCycle:c.onS/l,...u?{phase:u}:{}},f=c.intensity??(n.intensity>0?n.intensity:t.intensity??1);r.push({t:i.t,intensity:f,pattern:d})}s!==void 0&&r.push({t:s,intensity:n.intensity,pattern:n.pattern});const a=new Set(r.map(c=>c.t));return[...e.filter(c=>!a.has(c.t)),...r].sort((c,l)=>c.t-l.t)}static stateAt(t,e,i){const n=e.filter(s=>s.t<=i).at(-1);return{intensity:n?.intensity??t.intensity??1,pattern:n?.pattern??t.pattern}}leavesOf(t,e=new Set){const i=this.object.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}}class _h{static observer(t){const e=t.allKeyframes,i=e.map(s=>_h.said(s.pose)),n=e.filter((s,r)=>r>0&&r<e.length-1&&i[r]===i[r-1]&&i[r]===i[r+1]);for(const s of n)t.removeKeyframeAt(s.t)}static said(t){return JSON.stringify(t,(e,i)=>typeof i=="number"?Math.round(i*1e10)/1e10:i)}static timeline(t){const e=new Map;for(const i of t.allKeyframes)for(const n of i.shapes){const s=e.get(n.sourceId)??[];s.push({t:i.t,said:_h.said(n.shape)}),e.set(n.sourceId,s)}for(const[i,n]of e){const s=n.filter((r,a)=>a>0&&a<n.length-1&&r.said===n[a-1].said&&r.said===n[a+1].said);for(const r of s)t.removeShapeAt(r.t,i)}}}class cp{constructor(t,e){this.end=e;const i=[...t].sort((n,s)=>n.t-s.t);this.rolls=i.filter(n=>n.eventType==="roll"),this.vibrations=i.filter(n=>n.eventType==="vibrate"),this.spirals=i.filter(n=>n.eventType==="spiral")}static SPIRAL_OPENS=4;static THINNEST=.08;rolls;vibrations;spirals;rollAt(t){let e=0,i=0;for(const n of this.rolls){if(t<n.t)break;const s=n.params,r=this.progress(n,t);i=e+(s.toDeg-e)*(s.andBack?Math.sin(Math.PI*xe.smooth(r)):xe.smooth(r)),s.andBack||(e=s.toDeg)}for(const n of this.spirals){if(t<n.t)break;const s=n.params;i=e+(s.clockwise?1:-1)*s.rollDeg*this.progress(n,t)}return i}acrossShareAt(t){return Math.max(cp.THINNEST,Math.abs(Math.cos(this.rollAt(t)*Math.PI/180)))}sidewaysAt(t,e){let i=0;for(const n of this.vibrations){const s=n.until??this.end;if(t<n.t||t>=s)continue;const r=n.params,a=xe.smooth((t-n.t)/(r.riseS*1e3))*Math.max(0,1-(t-n.t)/(s-n.t));i+=r.amplitudeShare*e*a*Math.sin(2*Math.PI*r.hz*(t-n.t)/1e3)}return i}spiralAt(t){const e=[...this.spirals].reverse().find(a=>a.t<=t);if(!e)return;const i=e.params,n=this.progress(e,t),s=Math.tan(i.radiusDeg*Math.PI/180)*xe.smooth(n*cp.SPIRAL_OPENS)*(1-i.shrink*xe.smooth(n)),r=-(i.clockwise?1:-1)*2*Math.PI*i.turns*n;return[s*(Math.cos(r)-1),s*Math.sin(r)]}progress(t,e){const i=t.until??this.end;return i<=t.t?1:Math.max(0,Math.min(1,(e-t.t)/(i-t.t)))}}class Ts{constructor(t,e,i,n){this.sighting=t,this.stand=e;const s=i.filter(a=>a.eventType==="appearance").sort((a,c)=>a.t-c.t);this.vanishAt=i.find(a=>a.eventType==="vanish")?.t;const r=this.vanishAt??n;this.path=e.eventType==="travel"?new xe(e,i.filter(a=>a.eventType==="turn"),n):void 0,this.motion=this.path?new cp(i,e.until??n):void 0,this.looks=s.map((a,c)=>({t:a.t,until:a.until??s[c+1]?.t??r,parts:a.params.parts})),this.blinks=i.filter(a=>a.eventType==="blink").map(a=>({t:a.t,until:a.until??r,parts:a.who===void 0?[]:t.timeline.leavesOf(a.who),params:a.params}))}static SAMPLE_MS=2e3;static TRAVEL_SAMPLE_MS=25;static MOTION_MS=40;static SPIRAL_AHEAD_MS=20;static R=63710088e-1;looks;blinks;vanishAt;path;motion;timeline(){const t=new Map,e=(r,a)=>{const c=this.state(a,r);c&&(t.has(r)||t.set(r,new Map),t.get(r).set(a,c))},i=[...new Set(this.looks.flatMap(r=>r.parts.map(a=>a.sourceId)))];this.looks.forEach((r,a)=>{const c=this.looks[a+1];for(const l of i){if(!r.parts.some(d=>d.sourceId===l)){e(r.t,l),c?.parts.some(d=>d.sourceId===l)&&e(c.t-1,l);continue}const u=this.sighting.sampleMs??(this.path?Ts.TRAVEL_SAMPLE_MS:Ts.SAMPLE_MS);for(let d=r.t;d<r.until;d+=u)e(d,l);e(r.until-1,l)}});for(const r of this.blinks)for(const[a,c]of this.phases(r))for(const l of r.parts)e(a,l),e(c-1,l);if(this.vanishAt!==void 0)for(const r of i)e(this.vanishAt,r);const n=[...t.keys()].sort((r,a)=>r-a).map(r=>({t:r,shapes:[...t.get(r).values()]})),s=new Map;for(const r of n)for(const a of r.shapes){const c=a.shape.angle,l=s.get(a.sourceId);if(c===void 0)continue;const h=l===void 0?c:c+2*Math.PI*Math.round((l-c)/(2*Math.PI));a.shape.angle=Math.round(h*1e4)/1e4,s.set(a.sourceId,h)}return{keyframes:n,order:i,groups:[]}}phases(t){const e=[];let i=!0;for(let n=t.t;n<t.until;){const s=Math.min(n+(i?t.params.onS:t.params.offS)*1e3,t.until);e.push([n,s]),n=s,i=!i}return e}off(t,e){for(const i of this.blinks){if(e<i.t||e>=i.until||!i.parts.includes(t))continue;if(this.phases(i).findIndex(([s,r])=>e>=s&&e<r)%2===1)return i.params.off}}state(t,e){const i=[...this.looks].reverse().find(l=>l.t<=e)??this.looks[0],n=i?.parts.find(l=>l.sourceId===t),r=(n?i:this.looks.find(l=>l.t>e&&l.parts.some(h=>h.sourceId===t))??[...this.looks].reverse().find(l=>l.parts.some(h=>h.sourceId===t)))?.parts.find(l=>l.sourceId===t);if(!r)return;const a=!n||this.vanishAt!==void 0&&e>=this.vanishAt,c=a?void 0:this.off(t,e);return this.path?{sourceId:t,shape:this.onPath(r,e,c,a)}:{sourceId:t,shape:Ts.shape(r,this.geometry(e),c,a)}}onPath(t,e,i,n){const s=this.path,r=this.sighting.observerTrack.getInterpolatedPoseAt(e)??this.sighting.observerTrack.getLatestPoseAt(e),a=r?.headingDeg??0,c=r?.pitchDeg??0,l=this.motion,h=b=>xe.toScreen(s.at(b),a,c),u=(b,A)=>{const _=Math.hypot(A[0]-b[0],A[1]-b[1])||1;return[(A[0]-b[0])/_,(A[1]-b[1])/_]};let d=h(e),[f,p]=u(h(e-Ts.MOTION_MS),h(e+Ts.MOTION_MS));const m=s.sizeAt(e),g=Math.tan(l.sidewaysAt(e,m)*Math.PI/180);d=[d[0]-g*p,d[1]+g*f];const v=l.spiralAt(e);if(v){const b=l.spiralAt(e+Ts.SPIRAL_AHEAD_MS),A=h(e),_=h(e+Ts.SPIRAL_AHEAD_MS);d=[d[0]+v[0],d[1]+v[1]],[f,p]=u([A[0]+v[0],A[1]+v[1]],[_[0]+b[0],_[1]+b[1]])}const M=l.acrossShareAt(e),x={...t,heightShare:(t.heightShare??t.widthShare)*M,...t.upShare===void 0?{}:{upShare:t.upShare*M}},y=Math.tan(m*(x.alongShare??0)*Math.PI/180),w=Math.tan(m*(x.upShare??0)*Math.PI/180),S=xe.fromScreen(d[0]+y*f-w*p,d[1]+y*p+w*f,a,c),E=Ts.shape(x,{...S,sizeDeg:m},i,n,!0);return E.angle=Math.atan2(-p,f),E}geometry(t){const e=this.stand.params,i=this.sighting.observerTrack.getInterpolatedPoseAt(t)??this.sighting.observerTrack.getLatestPoseAt(t),n=i?.lat!==void 0&&i.lng!==void 0?{lat:i.lat,lng:i.lng}:this.sighting.event.place?.[0]??e.place;return Ts.seenFrom(e,n,t)}static seenFrom(t,e,i){const n=(t.place.lng-e.lng)*Math.PI/180*Ts.R*Math.cos(e.lat*Math.PI/180),s=(t.place.lat-e.lat)*Math.PI/180*Ts.R,r=Math.hypot(n,s),a=ai.linear(t.metres.map(({t:l,widthM:h,step:u})=>({t:l,value:h,step:u})),i),c=ai.linear(t.metres.map(({t:l,heightM:h,step:u})=>({t:l,value:h,step:u})),i);return{azimuthDeg:(Math.atan2(n,s)*180/Math.PI%360+360)%360,altitudeDeg:Math.atan2(c,r)*180/Math.PI,sizeDeg:2*Math.atan(a/(2*r))*180/Math.PI}}static shape(t,e,i,n,s=!1){const r=e.sizeDeg,a=Math.max(t.minWidthDeg??0,r*t.widthShare),c=t.kind==="oval"&&t.heightShare===void 0?a:Math.max(t.minHeightDeg??0,r*(t.heightShare??t.widthShare)),l=s?e.altitudeDeg:e.altitudeDeg+r*(t.upShare??0),h=s?e.azimuthDeg:e.azimuthDeg+r*(t.alongShare??0)/Math.cos(l*Math.PI/180),u=(p,m)=>Math.round(p*10**m)/10**m,d=t.kind==="polygon"?{kind:"polygon",bounds:{x:300,y:170,width:100,height:100*c/a},points:(t.points??[]).map(p=>({x:u(p.x*100,2),y:u(p.y*100*c/a,2)}))}:{kind:"oval",bounds:{x:320,y:180,width:2,height:2}};Object.assign(d,{color:i?.color??t.color,angle:0,transparency:n?1:i?.transparency??t.transparency??0,haloScale:t.halo??0,selected:!1,...t.blur===void 0?{}:{blur:t.blur},...t.title===void 0?{}:{title:t.title},angular:{widthDeg:u(a,4),heightDeg:u(c,4)},aim:{azimuthDeg:u((h%360+360)%360,3),altitudeDeg:u(l,3)}});const f=i&&"brightness"in i?i.brightness:t.brightness;return f!=null&&(d.brightness=n?0:f),d}}class Oe{static STANDING_EYE_M=1.6;static METERS_PER_DEGREE=111320;static expand(t){Oe.expandBodies(t),Oe.expandObserver(t),Oe.expandFlights(t),Oe.expandDecorLights(t),Oe.expandPhenomenon(t)}static expandDecorLights(t){for(const e of t.decor){if(!e.lights?.length||e.lights.some(s=>s.keyframes?.length))continue;const i=(t.events??[]).filter(s=>Nd.partOf(s.who,e.id)!==void 0);if(i.length===0)continue;const n=JSON.stringify(e.lights);e.lights=new Nd(e,i,Oe.endOf(t)).lights(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorLights={...t.eventsExpansion.decorLights,[e.id]:{stated:n,expanded:JSON.stringify(e.lights)}}}}static writtenLights(t,e,i){const n=t.eventsExpansion?.decorLights?.[e];return n&&JSON.stringify(i)===n.expanded?JSON.parse(n.stated):i}static expandPhenomenon(t){if(t.timeline.allKeyframes.length>0)return;const e=Oe.stands(t);for(const i of e){const n=Is.within(t,i.who),s=(t.events??[]).filter(a=>a.who!==void 0&&n.has(a.who)),r=new Ts(t,i,s,i.until??Oe.endOf(t)).timeline();for(const a of Jd.fromJSON(r).allKeyframes)t.timeline.addKeyframe(a.t,a.shapes)}e.length!==0&&(_h.timeline(t.timeline),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.timelinePending=!0)}static stands(t){return(t.events??[]).filter(e=>(e.eventType==="stand"||e.eventType==="travel")&&Is.isPhenomenon(t,e))}static shapesOf(t){const{groups:e,...i}=t.timeline.toJSON();return JSON.stringify(i)}static timelineWithoutShapes(t){const e=t.timeline.toJSON().groups??[];return e.length>0?{keyframes:[],groups:e}:{keyframes:[]}}static settle(t){t.eventsExpansion?.timelinePending&&(fn.toAngular(t),fn.toAim(t),t.eventsExpansion.timeline=Oe.shapesOf(t),t.eventsExpansion.timelinePending=!1)}static timelineIsExpanded(t){return t.eventsExpansion?.timeline!==void 0&&t.eventsExpansion.timeline===Oe.shapesOf(t)}static expandFlights(t){const e=t.observerTrack.allKeyframes[0]?.pose??t.event.place?.[0];if(e?.lat===void 0||e.lng===void 0)return;const i=Math.cos(e.lat*Math.PI/180);for(const n of t.events??[]){if(n.eventType!=="fly"||n.who===void 0)continue;const s=t.decor.find(m=>m.id===n.who);if(!s||s.track?.length)continue;const r=n.params,a=n.until??Oe.endOf(t),c=r.headingDeg*Math.PI/180,l=(r.from.lng-e.lng)*Math.PI/180*Oe.R*i,h=(r.from.lat-e.lat)*Math.PI/180*Oe.R,u=r.speeds.map(({t:m,kmh:g,step:v})=>({t:m,value:g/3.6,step:v})),d=r.heights.map(({t:m,altitudeM:g,step:v})=>({t:m,value:g,step:v})),f=m=>{const g=Math.sign(m-r.at.t)*Oe.FLY_STEP_MS;let v=0;for(let M=r.at.t;g!==0&&(g>0?M<m:M>m);M+=g){const x=g>0?Math.min(m,M+g):Math.max(m,M+g);v+=(ai.linear(u,M)+ai.linear(u,x))/2*(x-M)/1e3}return v},p=[];for(let m=n.t;m<=a;m+=ai.SAMPLE_MS){const g=r.at.metresBefore-f(m);p.push({t:m,eastM:l-Math.sin(c)*g,northM:h-Math.cos(c)*g,altitudeM:ai.linear(d,m),headingDeg:r.headingDeg})}s.track=p,s.eastM=p[0].eastM,s.northM=p[0].northM,s.headingDeg=r.headingDeg,t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorTracks[s.id]=JSON.stringify(p)}}static R=63710088e-1;static FLY_STEP_MS=100;static expandObserver(t){const e=(t.events??[]).filter(m=>Is.isObserver(t,m)),i=e.find(m=>m.eventType==="drive"),n=e.find(m=>m.eventType==="lookAhead");if(t.observerTrack.allKeyframes.length>0)return;if(!i){new Io(t,e).keyframes().length>0&&(_h.observer(t.observerTrack),t.eventsExpansion={...t.eventsExpansion,observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:t.eventsExpansion?.decorTracks??{}});return}if(!n)return;const s=i.until??Oe.endOf(t),r=i.params,a=new ai(r,i.t,s),c=e.find(m=>m.eventType==="lean"),l=e.find(m=>m.eventType==="watch"),u=new je(a,r.eye,n.params,c&&{t:c.t,params:c.params},l&&{t:l.t,params:l.params},m=>{const g=Oe.stands(t).find(M=>M.eventType==="stand");if(!g)return Oe.phenomenonPitchAt(t,m);const v=a.stateAt(m);return Ts.seenFrom(g.params,{lat:v.lat,lng:v.lng},m).altitudeDeg}).poses(i.t,s),d=u.map(m=>({t:m.t,pose:{lat:m.lat,lng:m.lng,elevationM:m.eye.y-Oe.STANDING_EYE_M,headingDeg:m.headingDeg,pitchDeg:m.pitchDeg,fovDeg:r.fovDeg??60}}));for(const m of d)t.observerTrack.addKeyframe(m.t,m.pose);_h.observer(t.observerTrack);const f={observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:{}},p=r.vehicle===void 0?void 0:t.decor.find(m=>m.id===r.vehicle);if(p&&!p.track?.length){const m=u[0],g=M=>Math.cos(M*Math.PI/180),v=u.map(M=>{const x=M.roadDeg*Math.PI/180,y=-M.eye.z,w=M.eye.x,S=(M.lng-m.lng)*Oe.METERS_PER_DEGREE*g(M.lat),E=(M.lat-m.lat)*Oe.METERS_PER_DEGREE;return{t:M.t,eastM:S-y*Math.sin(x)-w*Math.cos(x),northM:E-y*Math.cos(x)+w*Math.sin(x),altitudeM:0,headingDeg:M.roadDeg}});p.track=v,p.eastM=v[0].eastM,p.northM=v[0].northM,p.headingDeg=v[0].headingDeg,f.decorTracks[p.id]=JSON.stringify(v)}t.eventsExpansion={...t.eventsExpansion,...f}}static expandBodies(t){const e=t.interpretation?.bodies??[],i=n=>(t.events??[]).some(s=>s.who===n.id&&s.eventType==="ride");for(const n of[...e.filter(s=>!i(s)),...e.filter(i)]){const s=(t.events??[]).filter(h=>h.who===n.id||$o.partOf(h.who,n.id)!==void 0);if(s.length===0)continue;const r=Math.min(...s.map(h=>h.t));if(n.track.some(h=>h.t>r))continue;const a=JSON.stringify(n.track),c=s.find(h=>h.eventType==="ride"),l=c&&e.find(h=>h.id===c.params.in);n.track=c?l?$o.ride(n,c,l):n.track:new $o(n,s,Oe.endOf(t),t.sampleMs).track(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.bodies={...t.eventsExpansion.bodies,[n.id]:{stated:a,expanded:JSON.stringify(n.track)}}}}static writtenInterpretation(t,e){const i=t.eventsExpansion?.bodies;return!e||!i?e:{...e,bodies:e.bodies.map(n=>{const s=i[n.id];return s&&JSON.stringify(n.track)===s.expanded?{...n,track:JSON.parse(s.stated)}:n})}}static refresh(t){const e=t.observerTrack.allKeyframes.length===0||Oe.observerTrackIsExpanded(t),i=t.timeline.allKeyframes.length===0||Oe.timelineIsExpanded(t);Oe.again(t,e,i)}static reset(t){Oe.again(t,!0,Oe.stands(t).length>0)}static again(t,e,i){for(const s of t.interpretation?.bodies??[]){const r=t.eventsExpansion?.bodies?.[s.id];r&&JSON.stringify(s.track)===r.expanded&&(s.track=JSON.parse(r.stated))}for(const s of t.decor)s.lights&&(s.lights=Oe.writtenLights(t,s.id,s.lights));if(e){for(const s of Object.keys(t.eventsExpansion?.decorTracks??{})){const r=t.decor.find(a=>a.id===s);r&&delete r.track}t.observerTrack.clear()}const n=t.timeline.toJSON().groups??[];if(i){for(const s of[...t.timeline.sourceIds])t.timeline.removeSource(s);t.timeline.setGroups(n,!1)}t.eventsExpansion=void 0,Oe.expand(t),i&&t.timeline.pruneGroups(),i&&(fn.toBounds(t),fn.toPosition(t)),Oe.settle(t)}static bodiesAreExpanded(t){const e=t.eventsExpansion?.bodies??{};return(t.interpretation?.bodies??[]).every(i=>!e[i.id]||JSON.stringify(i.track)===e[i.id].expanded)}static observerTrackIsExpanded(t){return t.eventsExpansion?.observerTrack!==void 0&&t.eventsExpansion.observerTrack===JSON.stringify(t.observerTrack.toJSON())}static decorTrackIsExpanded(t,e,i){const n=t.eventsExpansion?.decorTracks[e];return n!==void 0&&n===JSON.stringify(i)}static phenomenonPitchAt(t,e){let i;for(const n of t.timeline.sourceIds){const s=t.timeline.getInterpolatedShapeAt(e,n),r=s?.aim?.altitudeDeg;if(!s||s.transparency>=1||r===void 0)continue;const a=(s.angular?.widthDeg??0)*(s.angular?.heightDeg??0);(!i||a>i.area)&&(i={area:a,altitude:r})}return i?.altitude??0}static endOf(t){return t.event.durationSeconds!==void 0?t.event.durationSeconds*1e3:Math.max(...(t.events??[]).map(e=>e.until??e.t))}}function vT(o){return ms.restore(MT(o),o.provenance)}function MT(o,t=!1){return fn.toAngular(o),fn.toAim(o),{version:4,id:o.id,time:lp.write(o.event.time),endTime:lp.write(o.event.endTime),durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:BS.write(o.event.place),observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:!t&&Oe.timelineIsExpanded(o)?Oe.timelineWithoutShapes(o):o.timeline.toJSON(),observerTrack:!t&&Oe.observerTrackIsExpanded(o)?void 0:jn.restatedObserverTrack(o),events:o.events?.length?o.events:void 0,weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:jn.restatedDecor(o).map(e=>{if(!t&&e.lights&&(e={...e,lights:Oe.writtenLights(o,e.id,e.lights)}),t||!Oe.decorTrackIsExpanded(o,e.id,e.track))return e;const{track:i,...n}=e;return n}),milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,film:o.film,metering:o.metering,sampleMs:o.sampleMs,lens:o.lens,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:t?jn.restatedInterpretation(o):Oe.writtenInterpretation(o,jn.restatedInterpretation(o)),variants:o.variants.length>0?o.variants:void 0,skyEvents:Kr.written(o.skyEvents),snapshots:o.snapshots,modules:o.modules?.length?o.modules:void 0}}function yT(o){Pc.check(o,"sighting");const t=Fi.toCurrent(o),{recording:e,provenance:i}=ms.strip(t),n=xT(e);return n.provenance=i,n}function xT(o){const t=[],e=new Qp({eventType:"sighting",time:lp.read(o.time),endTime:lp.read(o.endTime),durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:BS.read(o.place),description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Jd.fromJSON(o.timeline,t,!1),o.observerTrack?hd.fromJSON(o.observerTrack):new hd,o.weatherTrack?ud.fromJSON(o.weatherTrack):new ud,o.soundTrack?dd.fromJSON(o.soundTrack):new dd,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,(o.decor??[]).map(n=>{if(!n.facade?.plain)return n;const{plain:s,...r}=n.facade;return{...n,facade:{...r,openings:"plain"}}}),o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),Wu(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.film=o.film,e.metering=o.metering,e.sampleMs=o.sampleMs,e.lens=o.lens,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle,e.events=o.events?.map(n=>n.who===void 0?{...n,who:Fi.observerIdOf(o)}:n);const i=Kr.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.snapshots=o.snapshots,e.modules=Array.isArray(o.modules)?o.modules.filter(n=>typeof n=="string"):void 0,e.loadIssues=t,Oe.expand(e),e.timeline.pruneGroups(),fn.toBounds(e),fn.toPosition(e),Oe.settle(e),e}class lp{static read(t){return t===void 0||t.trim()===""?void 0:bh(t)}static write(t){if(t===void 0)return;const e=Oc(t);return e===""?void 0:e}}class BS{static read(t){if(t?.locations?.length)return t.locations.map(({lat:e,lng:i})=>({lat:e,lng:i,...t.name===void 0?{}:{name:t.name}}))}static write(t){if(!t?.length)return;const e=t.find(i=>i.name)?.name;return{...e===void 0?{}:{name:e},locations:t.map(({lat:i,lng:n})=>({lat:i,lng:n}))}}}class Ld{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=Ld.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=>` ${Ld.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
2436
2436
|
${i.join(`
|
|
2437
2437
|
`)}`)}}class xr{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!xr.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:xr.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(xr.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):xr.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:xr.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=xr.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:xr.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:xr.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return xr.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 Ar{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?Ar.travelDegOver(t,e,i,i+n*1e3)/s/Ar.PIXELS_PER_INSTANT:0,a=Ar.flashesOver(t,n)*Ar.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(Ar.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=Ar.directionAt(r,e,i),c=Ar.directionAt(r,e,n),l=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=Cr(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 hp=["en","fr","es","it"],wT={en:()=>Et(()=>import("./UfoMessages_en-Bau9u8Mz.js"),[],import.meta.url).then(o=>o.ufoMessages_en),fr:()=>Et(()=>import("./UfoMessages_fr-D9BCRY2m.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>Et(()=>import("./UfoMessages_es-DreLXcIR.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>Et(()=>import("./UfoMessages_it-C8r0jnJP.js"),[],import.meta.url).then(o=>o.ufoMessages_it)},bT=js.catalog(wT),ST={en:()=>Et(()=>import("./SightingMessages_en-C6mh8cZI.js"),[],import.meta.url).then(o=>o.sightingMessages_en),fr:()=>Et(()=>import("./SightingMessages_fr-D6DpE28c.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>Et(()=>import("./SightingMessages_es-t6G0aKl4.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>Et(()=>import("./SightingMessages_it-Dtm-W4pl.js"),[],import.meta.url).then(o=>o.sightingMessages_it)},ET=js.catalog(ST),AT={en:()=>Et(()=>import("./ShareMessages_en-B43x8LgJ.js"),[],import.meta.url).then(o=>o.shareMessages_en),fr:()=>Et(()=>import("./ShareMessages_fr-CzZyVbbX.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>Et(()=>import("./ShareMessages_es-DZCJojSc.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>Et(()=>import("./ShareMessages_it-C_Z6eDQK.js"),[],import.meta.url).then(o=>o.shareMessages_it)},_T=js.catalog(AT);function TT(o){switch(o){case"fr":return Et(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return Et(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return Et(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}const RT=js.catalog({en:()=>Et(()=>import("./SceneNames_en-BCismFgW.js"),[],import.meta.url).then(o=>o.sceneNames_en),fr:()=>Et(()=>import("./SceneNames_fr-hA9CGBs-.js"),[],import.meta.url).then(o=>o.sceneNames_fr),es:()=>Et(()=>import("./SceneNames_es-u83jdbyr.js"),[],import.meta.url).then(o=>o.sceneNames_es),it:()=>Et(()=>import("./SceneNames_it-Bp7twqSK.js"),[],import.meta.url).then(o=>o.sceneNames_it)});function HS(o){return RT.load(o)}const GS=Math.PI/180,IT=180/Math.PI,DT=256,VS=19,CT=1.25;function WS(o,t){return 156543.03392*Math.cos(o*GS)/2**t}function XS(o,t){return WS(o,t)*DT}function OT(o,t){let e=0;for(;e<VS&&XS(o,e+1)>=t;)e++;return e}function $S(o,t){return XS(o,t)}function PT(o,t){const e=t*CT;let i=0;for(;i<VS&&WS(o,i)>e;)i++;return i}function k0(o){const t=o*GS;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function YS(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:k0(t)*i}}function KS(o,t,e){const i=k0(o.north),n=k0(o.south);return{x:(t-o.west)/(o.east-o.west),y:(k0(e)-i)/(n-i)}}function NT(o,t,e){const{x:i,y:n}=YS(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function LT(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=q2(o.y,t);return{south:q2(o.y+1,t),north:n,west:e,east:i}}function q2(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*IT}function qS(o,t,e,i){const n=NT(o,t,e),s=Math.floor(i/2),r=[];for(let l=-s;l<=s;l++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+l,z:e});const a=r.map(LT),c={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:c}}const kT="#2ec4ff";class Ac{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=KS(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??kT;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?l:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,l=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:Ac.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,Ac.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=ae(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=Ac.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Ac.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(ae(r,t.east,r,t.west).x)/this.width,l=Ac.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(l===void 0)return;const h=l/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class fi{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 fi.including(t.boundsAround(fi.MIN_SPAN_M,fi.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(fi.MAX_ZOOM,Math.max(fi.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=fi.mercatorY01(e.north),s=fi.mercatorY01(e.south),r=fi.mercatorY01(i.north),a=fi.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=fi.mercatorY01(n.north),r=fi.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(fi.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=fi.mercatorY01(t.north),n=fi.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:fi.latitudeAt(i+(this.centerY-e)*(n-i)),south:fi.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=ae(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=ae(c.lat,c.lng,n,s),u=Math.max(Math.abs(l),Math.abs(h));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:Ps(0,-a,n,s).lat,south:Ps(0,a,n,s).lat,east:Ps(a,0,n,s).lng,west:Ps(-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=fi.mercatorY01(t.north),s=fi.mercatorY01(t.south);return{lat:fi.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 tr=256,Z2=3,UT=32768;class ZS{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(ae(i,t.east,i,t.west).x),r=Math.abs(ae(t.north,n,t.south,n).z),a=OT(i,Math.max(s,r)),{tiles:c}=qS(n,i,a,Z2),l=Z2*tr,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let m=0;m<e.width;m++){const g=t.west+(t.east-t.west)*(m/(e.width-1));d[f*e.width+m]=this.sampleAt(p,g,a,u,h,l)}}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=tr,c.height=tr;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,tr,tr),u=(t.x-e.x)*tr,d=(t.y-e.y)*tr;for(let f=0;f<tr;f++)for(let p=0;p<tr;p++){const m=(f*tr+p)*4,g=h[m]*256+h[m+1]+h[m+2]/256-UT,v=u+p,M=d+f;i[M*n+v]=g}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=YS(e,t,i),l=(a-n.x)*tr,h=(c-n.y)*tr,u=Math.max(0,Math.min(r-1,Math.floor(l))),d=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),m=l-u,g=h-d,v=s[d*r+u],M=s[d*r+f],x=s[p*r+u],y=s[p*r+f],w=v+(M-v)*m,S=x+(y-x)*m;return w+(S-w)*g}}class em{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const M=i+2+v*12;s.set(e.getUint16(M,!0),{type:e.getUint16(M+2,!0),count:e.getUint32(M+4,!0),value:e.getUint32(M+8,!0)})}const r=(v,M)=>{const x=s.get(v);if(x===void 0){if(M===void 0)throw new Error(`TIFF without tag ${v}`);return M}return x.type===3?x.value&65535:x.value},a=v=>{const M=s.get(v);if(M===void 0)throw new Error(`TIFF without tag ${v}`);const x=M.type===3?2:4,y=[];if(M.count*x<=4){const w=new DataView(new ArrayBuffer(4));w.setUint32(0,M.value,!0);for(let S=0;S<M.count;S++)y.push(x===2?w.getUint16(S*2,!0):w.getUint32(0,!0))}else for(let w=0;w<M.count;w++)y.push(x===2?e.getUint16(M.value+w*2,!0):e.getUint32(M.value+w*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),l=r(257),h=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),m=new Uint8Array(c*l*h*(u/8));let g=0;for(let v=0;v<f.length&&g<m.length;v++){const M=Math.min(p[v],m.length-g);m.set(new Uint8Array(t,f[v],M),g),g+=M}if(g<m.length)throw new Error("Truncated TIFF");return new em(c,l,h,d?new Float32Array(m.buffer):m)}}class po extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class FT{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class ke{static covers(t,e){return t>=41.2&&t<=51.3&&e>=-5.4&&e<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??ke.WMS,this.wfs=t.wfsEndpoint??ke.WFS}static radius(t){return Math.min(t,ke.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,ke.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=ke.lidarRadius(e),n=Math.ceil(2*i/ke.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,ke.HEIGHT_LAYER),this.raster(t,i,n,ke.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new po("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===ke.NO_DATA))throw new po("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),l=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:c,building:l,structures:new FT(a,c,l,n,h)}}async laserDate(t){return ke.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return ke.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=ke.radius(e),n=Math.min(ke.MAX_PHOTO_PIXELS,Math.ceil(2*i/ke.METRES_PER_PIXEL)),s=await this.raster(t,i,n,ke.PHOTO_LAYER);if(s.samples<3)throw new po("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=ke.radius(e),s=n/ke.METRES_PER_DEGREE,r=n/(ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,ke.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],g=[...f,...m];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:g,zones:p,mapDate:ke.latest(g.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=ke.MAX_WHOLE_M/ke.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,m]=ke.extent(u);if(d>=n&&f>=s&&p<=r&&m<=a)continue;const g=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(m,a+c)];l=l?[Math.min(l[0],g[0]),Math.min(l[1],g[1]),Math.max(l[2],g[2]),Math.max(l[3],g[3])]:g}if(!l)return[];const h=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,ke.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of c)n.push(l.map(h=>({lat:h[1],lng:h[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/ke.METRES_PER_DEGREE,r=e/(ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new po("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new po("unreachable",`The survey answered ${c.status}`);try{return em.parse(await c.arrayBuffer())}catch(l){throw new po("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new po("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new po("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class Do{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>ae(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>ae(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],l=s[a+1],h=Math.hypot(l.x-c.x,l.z-c.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/Do.SAMPLE_M)),d=Math.atan2(l.x-c.x,-(l.z-c.z));for(let f=0;f<=u;f++){const p=f/u,m=Do.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);m.distanceM>Do.NEAR_M||Do.angleBetween(d,m.heading)<=Do.ALIGNED_DEG&&(r+=h/u)}}return r>=Do.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.z-r.z,h=c*c+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*l)/h)),d=Math.hypot(e-(r.x+c*u),i-(r.z+l*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-l)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class Ce{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Ce.WMS,this.timeoutMs=t.timeoutMs??Ce.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Ce.MAX_WINDOW_M,this.geoplatform=new ke({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!ke.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(ae(n.lat,t.east,n.lat,t.west).x),r=Math.abs(ae(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:t.south-c.y/Ce.METRES_PER_DEGREE,north:t.north+c.y/Ce.METRES_PER_DEGREE,west:t.west-c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=m=>Math.min(Ce.MAX_PIXELS,Math.max(Ce.MIN_PIXELS,Math.ceil(m/Ce.METRES_PER_PIXEL))),u={width:h(s+2*c.x),height:h(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>Ce.COARSE_METRES_PER_PIXEL;for(const m of p?[...Ce.LAYERS].reverse():Ce.LAYERS)try{const g=await this.heights(l,u,m);m===Ce.LAYERS[0]&&await this.layBridgeDecks(g,l,u,i?.route);const v=this.sample(g,e,t,l,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${m} does not cover this place`)}catch(g){f=g}throw f}finer(t,e,i){if(t.width<Ce.MESH_FROM_VERTICES||t.height<Ce.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Ce.FINE_SPACING_M),c=Math.max(r-1,Math.min(Ce.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return em.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>Ce.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>Do.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,Ce.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(g,[v,M,x])=>s.values[g*s.samples]===v&&s.values[g*s.samples+1]===M&&s.values[g*s.samples+2]===x,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let g=0;g<l.length;g++)r(g,Ce.DECK)&&(l[g]=1,h=!0);if(!h)return;const u=Ce.DECK_END_PIXELS,d=[];for(let g=0;g<l.length;g++){if(l[g]!==1)continue;const v=g%a,M=(g-v)/a;for(let x=-u;x<=u;x++)for(let y=-u;y<=u;y++){const w=v+y,S=M+x;if(w<0||S<0||w>=a||S>=c)continue;const E=S*a+w;l[E]===0&&r(E,Ce.NO_CLASS)&&d.push(E)}}for(const g of d)l[g]=1;const f=this.paint(n,e,a,c),p=this.touching(l,f,a,c);if(p.every(g=>g===0))return;const m=await this.heights(e,i,Ce.SURFACE_LAYER);if(m.width!==a||m.height!==c)return;for(let g=0;g<p.length;g++){if(p[g]===0)continue;const v=m.values[g];Number.isFinite(v)&&v>Ce.NO_DATA_BELOW&&v>t.values[g]&&(t.values[g]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Ce.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Ce.METRES_PER_DEGREE,h=c/s,u=l/r,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*c,y:(i.north-v.lat)/(i.north-i.south)*l}),f=(v,M)=>{const x=Math.floor(v/h),y=Math.floor(M/u);if(x<0||y<0||x>=s||y>=r)return;const w=e[y*s+x];return Number.isFinite(w)&&w>Ce.NO_DATA_BELOW?w:void 0},p=Ce.DECK_HALF_WIDTH_M,m=Ce.DECK_APPROACH_M,g=(v,M)=>{const x=Math.hypot(v.x-M.x,v.y-M.y)||1,y={x:(v.x-M.x)/x,y:(v.y-M.y)/x},w=[0,m/2,m].map(S=>f(v.x+y.x*S,v.y+y.y*S)).filter(S=>S!==void 0);return w.length>0?Math.max(...w):void 0};for(const v of Ce.chains(n.map(M=>M.map(d)))){const M=[0];for(let I=1;I<v.length;I++)M.push(M[I-1]+Math.hypot(v[I].x-v[I-1].x,v[I].y-v[I-1].y));const x=M[M.length-1];if(x<1||x>Ce.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),w=g(v[v.length-1],v[v.length-2]);if(y===void 0||w===void 0)continue;const S=p+m,E=Math.max(0,Math.floor((Math.min(...v.map(I=>I.x))-S)/h)),b=Math.min(s-1,Math.ceil((Math.max(...v.map(I=>I.x))+S)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(I=>I.y))-S)/u)),_=Math.min(r-1,Math.ceil((Math.max(...v.map(I=>I.y))+S)/u));for(let I=A;I<=_;I++)for(let D=E;D<=b;D++){const O=Ce.nearestAlong(v,M,{x:(D+.5)*h,y:(I+.5)*u});if(O.distance>p||O.s<-m||O.s>x+m)continue;const L=y+(w-y)*Math.min(1,Math.max(0,O.s/x)),P=I*s+D;e[P]>=L||(t.values[P]=L)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],l=s[0],h=s[s.length-1];if(n(h,c[0]))s=[...s,...c.slice(1)];else if(n(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(l,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(l,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.y-r.y,h=c*c+l*l;if(h<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*l)/h;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+l*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(h),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let l=0;l<c.length-1;l++){const h=r(c[l].lng),u=a(c[l].lat),d=r(c[l+1].lng),f=a(c[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let m=0;m<=p;m++){const g=Math.floor(h+(d-h)*m/p),v=Math.floor(u+(f-u)*m/p);for(let M=-1;M<=1;M++)for(let x=-1;x<=1;x++){const y=g+x,w=v+M;y>=0&&w>=0&&y<i&&w<n&&(s[w*i+y]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const u=l.pop();c.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let m=-1;m<=1;m++){const g=d+m,v=f+p;if(g<0||v<0||g>=i||v>=n)continue;const M=v*i+g;t[M]===1&&r[M]===0&&(r[M]=1,l.push(M))}}if(h)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,l=new Float32Array(a*c),h=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const m=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),g=(n.north-m)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const x=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,x,g,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,g),w=p*a+v;y===void 0?f++:(l[w]=y,h[w]=1)}}if(!(f===a*c||f/(a*c)>Ce.MAX_HOLE_SHARE))return this.fill(l,h,a,c),l}tent(t,e,i,n,s){let r=0,a=0,c=0;const l=Math.max(0,Math.ceil(i-s)),h=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let m=u;m<=d;m++){const g=p*(1-Math.abs(m-e)/n);if(g<=0)continue;c+=g;const v=t.at(m,f);!Number.isFinite(v)||v<Ce.NO_DATA_BELOW||(r+=g*v,a+=g)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),l=Math.max(0,Math.min(1,i-s)),h=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const g of[h,u,d,f])if(!Number.isFinite(g)||g<Ce.NO_DATA_BELOW)return;const p=h+(u-h)*c,m=d+(f-d)*c;return p+(m-p)*l}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const l=a*i+c;if(e[l])continue;let h=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,m=c+f;p<0||m<0||p>=n||m>=i||!e[p*i+m]||(h+=t[p*i+m],u++)}u>0&&r.push([l,h/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class zT{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 U0=256,BT=5;async function JS(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(ae(n,o.east,n,o.west).x),a=Math.abs(ae(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=HT(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=qS(s,n,l,h),f=h*U0,p=document.createElement("canvas");p.width=f,p.height=f;const m=p.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=u[0];await Promise.all(u.map(async y=>{const w=e(y),S=await i(w);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${w}`);const E=await createImageBitmap(await S.blob());m.drawImage(E,(y.x-g.x)*U0,(y.y-g.y)*U0)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const M=document.createElement("canvas");M.width=v,M.height=v;const x=M.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,v,v),{source:M,width:v,height:v,bounds:d}}function HT(o,t,e){let i=PT(o,t/Math.max(1,e)),n=J2(o,i,t);for(;n>BT&&i>0;)i--,n=J2(o,i,t);return{zoom:i,gridSize:n,mPerPixel:$S(o,i)/U0}}function J2(o,t,e){const i=Math.ceil(e/2/$S(o,t));return Math.max(3,2*i+1)}class jS{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 JS(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Ds{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=Ds.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,l=(s+a)/2,h=Ds.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[Ds.FRANCE_ENDPOINT,...e.filter(d=>d!==Ds.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=Ds.queue.then(t,t);return Ds.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Ds.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Ds.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,Ds.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class Co{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 Ds(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Co.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:Co.surfaceOf(s),widthM:Co.widthOf(s),...Co.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:Co.WIDTH_M[t.highway]??Co.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 km="https://ufoathome.org/roads/index.json";class eh{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??eh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2438
|
-
`);let e=eh.shared.get(t);return e||(e=this.fetchFirstAvailable(),eh.shared.set(t,e),e.then(i=>{i.length===0&&eh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.
|
|
2439
|
-
`);let e=ih.shared.get(t);return e||(e=this.fetchFirstAvailable(),ih.shared.set(t,e),e.then(i=>{i.length===0&&ih.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==Um?[e,Um]:[Um]).map(i=>i+t)}}class Ss{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=Ss.key(t);let i=Ss.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Ss.asked.set(e,i),i.catch(()=>Ss.asked.delete(e))),structuredClone(await i)}static forget(){Ss.asked.clear()}static key(t){return`v${Ss.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Ss.openCache(),n=Ss.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<Ss.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Ss.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-Ss.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ss.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class ko{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>ko.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=ko.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=ko.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=ko.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>ko.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Gn{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 Ds(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"~"^(${Gn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Gn.ROUTES})$"];out body;`;return Gn.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=Gn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>ae(v.lat,v.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of Gn.samples(a)){u++;const M=Gn.waysAt(d,v);if(M.length===0)continue;const[x]=M;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(M.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,x)=>x[1]-M[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(l)),g=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Gn.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=Gn.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=Gn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=Gn.SAMPLE_M/2;a<n;a+=Gn.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(Gn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=Gn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class nh{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Ds(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${nh.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Gn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Gn.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=Gn.voltageOf(r),l=nh.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=nh.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:nh.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class WT{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(!ko.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 ln{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=ln.key(t);let i=ln.asked.get(e)??ln.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},ln.asked.set(e,i),n.catch(()=>ln.asked.delete(e))}return structuredClone(await i.answer)}static forget(){ln.asked.clear(),ln.failedAt=-1/0}static key(t){return`v${ln.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of ln.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 ln.openCache(),n=ln.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<ln.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-ln.failedAt<ln.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(ln.failedAt=this.now(),s)return s;throw a}return i&&ln.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-ln.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(ln.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Fm="https://ufoathome.org/railways/index.json";class sh{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??sh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2440
|
-
`);let e=sh.shared.get(t);return e||(e=this.fetchFirstAvailable(),sh.shared.set(t,e),e.then(i=>{i.length===0&&sh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Fm?[e,Fm]:[Fm]).map(i=>i+t)}}function QS(){return{elevation:tE(),imagery:eE(),roads:XT(),water:$T(),railways:YT()}}function tE(){return new zT(new Ce,new ZS)}function eE(){return new jS}function XT(){return new eh({fallback:new GT(new Lo,new Co)})}function $T(){return new ih({fallback:new Ss(new VT(new kd,new _c))})}function YT(){return new sh({fallback:new ln(new WT(new ko,new nh))})}const KT=new Set,ma="show-observer-map",ga="hide-milestones",Lc="minified";class He extends HTMLElement{static get observedAttributes(){return["src",ma,ga,Lc]}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 fi;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=Qp.create();issues=[];issueCheck=0;sightingAudio=new gT;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>He.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");He.setIcon(this.moreButton,t?jt.UNFOLDED:jt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<He.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=fi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=fi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},He.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=fi.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>${cT}</style>${oT}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new $h(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Ac(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===ma&&this.applyObserverMapDefault(),t===ga&&this.setMilestonesShown(!this.hasAttribute(ga)),t===Lc){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Lc)}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(nE)))};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 jo.recording(t)}get sightingData(){return vT(this.currentSighting)}set sightingData(t){const e=Fi.toCurrent(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=yT(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;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 Et(async()=>{const{default:r}=await import("./sightingSchema-B1hstz7u.js");return{default:r}},[],import.meta.url);n=new xr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],Ld.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(qT,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Ld.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!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 l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),He.setIcon(this.referencesButton,i?jt.PICTURES_ON:jt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),He.setIcon(this.tracesButton,this.tracesShownState?jt.TRACES_ON:jt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Wu(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 l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=He.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=He.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?Pm(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new $h(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=He.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Pm(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=Ar.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<He.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(He.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/He.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/He.EXPOSURE_STEP_PX),s=Math.min(He.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=zi.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:KT;this.canvasRenderer.setStarPoints(zi.starPointsOf(this.sighting.instrument,Pe(this.sighting,t)?.fNumber));const n=(Pe(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?Ws.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(CS(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 lT(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*He.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?jt.PLAY:jt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){He.icons.get(t)!==e&&(He.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},He.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),He.setIcon(this.playPauseButton,t?jt.PAUSE:jt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(ma),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;He.setIcon(this.observerMapButton,t?jt.MAP_ON:jt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Ah.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=fi.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?fi.expand(t,He.OBSERVER_MAP_IMAGERY_AHEAD):t,n=fi.IMAGERY_PX*(e?1+2*He.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:eE();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?fi.expand(t,He.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=He.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Pe(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},He.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Pm(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Wu(this.currentSighting.milestones):[]){const a=Pe(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?ha.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(zi.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,Wu(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",He.setIcon(this.milestonesButton,this.milestonesShown?jt.MILESTONES_ON:jt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=Pe(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Cr(i,t),{lat:s,lng:r}=Ps(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=Pe(this.currentSighting,this.currentTime),s=ha.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ri.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=He.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),He.setIcon(this.miniMuteButton,this.mutedState?jt.MUTED:jt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){He.setIcon(this.muteButton,jt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}He.setIcon(this.muteButton,this.mutedState?jt.MUTED:jt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;He.setIcon(this.fullscreenButton,t?jt.EXIT_FULLSCREEN:jt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Ks(ja.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=rp(ja.preferencesFor(this),hp);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await bT.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=DS(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?S1(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return mo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?Q2(j2(this.realStartMs+i)):mo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?mo(t):mo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return mo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return mo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?mo(this.currentSighting.timeline.duration):this.canShowClockTime?Q2(j2(this.realStartMs+this.realDurationMs)):mo(this.realDurationMs)}}function j2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function Q2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function mo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const T1="rr0-ufo";function iE(){customElements.get(T1)||customElements.define(T1,He)}const qT="recordingissues",nE="minifiedreset";/**
|
|
2438
|
+
`);let e=eh.shared.get(t);return e||(e=this.fetchFirstAvailable(),eh.shared.set(t,e),e.then(i=>{i.length===0&&eh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==km?[e,km]:[km]).map(i=>i+t)}}class Lo{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(t={}){this.platform=new ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>Lo.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=Lo.BY_NATURE[n]??Lo.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=Lo.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=Lo.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class GT{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(Lo.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class kd{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>kd.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const l=a.map(h=>kd.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:l}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class _c{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new Ds(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return _c.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),c=_c.rings(a("inner"));for(const[l,h]of _c.rings(a("outer")).entries()){const u=c.filter(d=>_c.contains(h,d[0]));n.push({id:`osm-r${r.id}-${l}`,rings:[h,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of _c.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],l=s[s.length-1];if(e(l,c[0]))s=[...s,...c.slice(1)];else if(e(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class VT{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(kd.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const Um="https://ufoathome.org/water/index.json";class ih{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??ih.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2439
|
+
`);let e=ih.shared.get(t);return e||(e=this.fetchFirstAvailable(),ih.shared.set(t,e),e.then(i=>{i.length===0&&ih.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==Um?[e,Um]:[Um]).map(i=>i+t)}}class Ss{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=Ss.key(t);let i=Ss.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Ss.asked.set(e,i),i.catch(()=>Ss.asked.delete(e))),structuredClone(await i)}static forget(){Ss.asked.clear()}static key(t){return`v${Ss.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Ss.openCache(),n=Ss.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<Ss.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Ss.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-Ss.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ss.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class ko{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new ke(t)}static covers(t){return ke.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>ko.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=ko.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=ko.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=ko.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>ko.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Gn{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 Ds(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"~"^(${Gn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Gn.ROUTES})$"];out body;`;return Gn.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=Gn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>ae(v.lat,v.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of Gn.samples(a)){u++;const M=Gn.waysAt(d,v);if(M.length===0)continue;const[x]=M;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(M.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,x)=>x[1]-M[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(l)),g=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Gn.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=Gn.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=Gn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=Gn.SAMPLE_M/2;a<n;a+=Gn.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(Gn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=Gn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class nh{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Ds(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${nh.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Gn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Gn.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=Gn.voltageOf(r),l=nh.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=nh.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:nh.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class WT{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(!ko.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 ln{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=ln.key(t);let i=ln.asked.get(e)??ln.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},ln.asked.set(e,i),n.catch(()=>ln.asked.delete(e))}return structuredClone(await i.answer)}static forget(){ln.asked.clear(),ln.failedAt=-1/0}static key(t){return`v${ln.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of ln.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 ln.openCache(),n=ln.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<ln.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-ln.failedAt<ln.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(ln.failedAt=this.now(),s)return s;throw a}return i&&ln.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-ln.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(ln.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Fm="https://ufoathome.org/railways/index.json";class sh{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??sh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2440
|
+
`);let e=sh.shared.get(t);return e||(e=this.fetchFirstAvailable(),sh.shared.set(t,e),e.then(i=>{i.length===0&&sh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Fm?[e,Fm]:[Fm]).map(i=>i+t)}}function QS(){return{elevation:tE(),imagery:eE(),roads:XT(),water:$T(),railways:YT()}}function tE(){return new zT(new Ce,new ZS)}function eE(){return new jS}function XT(){return new eh({fallback:new GT(new Lo,new Co)})}function $T(){return new ih({fallback:new Ss(new VT(new kd,new _c))})}function YT(){return new sh({fallback:new ln(new WT(new ko,new nh))})}const KT=new Set,ma="show-observer-map",ga="hide-milestones",Lc="minified";class Ge extends HTMLElement{static get observedAttributes(){return["src",ma,ga,Lc]}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 fi;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=Qp.create();issues=[];issueCheck=0;sightingAudio=new gT;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Ge.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Ge.setIcon(this.moreButton,t?jt.UNFOLDED:jt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ge.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=fi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=fi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ge.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=fi.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>${cT}</style>${oT}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new $h(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Ac(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===ma&&this.applyObserverMapDefault(),t===ga&&this.setMilestonesShown(!this.hasAttribute(ga)),t===Lc){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Lc)}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(nE)))};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 jo.recording(t)}get sightingData(){return vT(this.currentSighting)}set sightingData(t){const e=Fi.toCurrent(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=yT(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;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 Et(async()=>{const{default:r}=await import("./sightingSchema-B1hstz7u.js");return{default:r}},[],import.meta.url);n=new xr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],Ld.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(qT,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Ld.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!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 l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ge.setIcon(this.referencesButton,i?jt.PICTURES_ON:jt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Ge.setIcon(this.tracesButton,this.tracesShownState?jt.TRACES_ON:jt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Wu(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 l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ge.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ge.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?Pm(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new $h(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=Ge.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Pm(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=Ar.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ge.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ge.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ge.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ge.EXPOSURE_STEP_PX),s=Math.min(Ge.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=zi.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:KT;this.canvasRenderer.setStarPoints(zi.starPointsOf(this.sighting.instrument,Pe(this.sighting,t)?.fNumber));const n=(Pe(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?Ws.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(CS(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 lT(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Ge.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?jt.PLAY:jt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ge.icons.get(t)!==e&&(Ge.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Ge.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),Ge.setIcon(this.playPauseButton,t?jt.PAUSE:jt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(ma),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;Ge.setIcon(this.observerMapButton,t?jt.MAP_ON:jt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Ah.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=fi.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?fi.expand(t,Ge.OBSERVER_MAP_IMAGERY_AHEAD):t,n=fi.IMAGERY_PX*(e?1+2*Ge.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:eE();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?fi.expand(t,Ge.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Ge.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Pe(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},Ge.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Pm(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Wu(this.currentSighting.milestones):[]){const a=Pe(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?ha.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(zi.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,Wu(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",Ge.setIcon(this.milestonesButton,this.milestonesShown?jt.MILESTONES_ON:jt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=Pe(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Cr(i,t),{lat:s,lng:r}=Ps(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=Pe(this.currentSighting,this.currentTime),s=ha.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ri.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=Ge.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ge.setIcon(this.miniMuteButton,this.mutedState?jt.MUTED:jt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Ge.setIcon(this.muteButton,jt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Ge.setIcon(this.muteButton,this.mutedState?jt.MUTED:jt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ge.setIcon(this.fullscreenButton,t?jt.EXIT_FULLSCREEN:jt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Ks(ja.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=rp(ja.preferencesFor(this),hp);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await bT.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=DS(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?S1(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return mo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?Q2(j2(this.realStartMs+i)):mo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?mo(t):mo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return mo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return mo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?mo(this.currentSighting.timeline.duration):this.canShowClockTime?Q2(j2(this.realStartMs+this.realDurationMs)):mo(this.realDurationMs)}}function j2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function Q2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function mo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const T1="rr0-ufo";function iE(){customElements.get(T1)||customElements.define(T1,Ge)}const qT="recordingissues",nE="minifiedreset";/**
|
|
2441
2441
|
* @license
|
|
2442
2442
|
* Copyright 2010-2026 Three.js Authors
|
|
2443
2443
|
* SPDX-License-Identifier: MIT
|
|
@@ -6552,7 +6552,7 @@ void main() {
|
|
|
6552
6552
|
|
|
6553
6553
|
}
|
|
6554
6554
|
|
|
6555
|
-
}`;class DO{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new IE(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new Re({vertexShader:RO,fragmentShader:IO,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Mt(new os(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class CO extends oc{constructor(t,e){super();const i=this;let n=null,s=1,r=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,p=null;const m=typeof XRWebGLBinding<"u",g=new DO,v={},M=e.getContextAttributes();let x=null,y=null;const w=[],S=[],E=new tt;let b=null;const A=new Wn;A.viewport=new _e;const _=new Wn;_.viewport=new _e;const I=[A,_],D=new _4;let O=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ct=w[Z];return ct===void 0&&(ct=new Km,w[Z]=ct),ct.getTargetRaySpace()},this.getControllerGrip=function(Z){let ct=w[Z];return ct===void 0&&(ct=new Km,w[Z]=ct),ct.getGripSpace()},this.getHand=function(Z){let ct=w[Z];return ct===void 0&&(ct=new Km,w[Z]=ct),ct.getHandSpace()};function P(Z){const ct=S.indexOf(Z.inputSource);if(ct===-1)return;const ot=w[ct];ot!==void 0&&(ot.update(Z.inputSource,Z.frame,l||r),ot.dispatchEvent({type:Z.type,data:Z.inputSource}))}function k(){n.removeEventListener("select",P),n.removeEventListener("selectstart",P),n.removeEventListener("selectend",P),n.removeEventListener("squeeze",P),n.removeEventListener("squeezestart",P),n.removeEventListener("squeezeend",P),n.removeEventListener("end",k),n.removeEventListener("inputsourceschange",H);for(let Z=0;Z<w.length;Z++){const ct=S[Z];ct!==null&&(S[Z]=null,w[Z].disconnect(ct))}O=null,L=null,g.reset();for(const Z in v)delete v[Z];t.setRenderTarget(x),f=null,d=null,u=null,n=null,y=null,Pt.stop(),i.isPresenting=!1,t.setPixelRatio(b),t.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){s=Z,i.isPresenting===!0&&zt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,i.isPresenting===!0&&zt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(Z){l=Z},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(n,e)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(Z){if(n=Z,n!==null){if(x=t.getRenderTarget(),n.addEventListener("select",P),n.addEventListener("selectstart",P),n.addEventListener("selectend",P),n.addEventListener("squeeze",P),n.addEventListener("squeezestart",P),n.addEventListener("squeezeend",P),n.addEventListener("end",k),n.addEventListener("inputsourceschange",H),M.xrCompatible!==!0&&await e.makeXRCompatible(),b=t.getPixelRatio(),t.getSize(E),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let ot=null,V=null,Nt=null;M.depth&&(Nt=M.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,ot=M.stencil?kc:so,V=M.stencil?zd:dr);const Xt={colorFormat:e.RGBA8,depthFormat:Nt,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Xt),n.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new qe(d.textureWidth,d.textureHeight,{format:qi,type:is,depthTexture:new nc(d.textureWidth,d.textureHeight,V,void 0,void 0,void 0,void 0,void 0,void 0,ot),stencilBuffer:M.stencil,colorSpace:t.outputColorSpace,samples:M.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const ot={antialias:M.antialias,alpha:!0,depth:M.depth,stencil:M.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(n,e,ot),n.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new qe(f.framebufferWidth,f.framebufferHeight,{format:qi,type:is,colorSpace:t.outputColorSpace,stencilBuffer:M.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,r=await n.requestReferenceSpace(a),Pt.setContext(n),Pt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function H(Z){for(let ct=0;ct<Z.removed.length;ct++){const ot=Z.removed[ct],V=S.indexOf(ot);V>=0&&(S[V]=null,w[V].disconnect(ot))}for(let ct=0;ct<Z.added.length;ct++){const ot=Z.added[ct];let V=S.indexOf(ot);if(V===-1){for(let Xt=0;Xt<w.length;Xt++)if(Xt>=S.length){S.push(ot),V=Xt;break}else if(S[Xt]===null){S[Xt]=ot,V=Xt;break}if(V===-1)break}const Nt=w[V];Nt&&Nt.connect(ot)}}const W=new R,Q=new R;function q(Z,ct,ot){W.setFromMatrixPosition(ct.matrixWorld),Q.setFromMatrixPosition(ot.matrixWorld);const V=W.distanceTo(Q),Nt=ct.projectionMatrix.elements,Xt=ot.projectionMatrix.elements,Lt=Nt[14]/(Nt[10]-1),Rt=Nt[14]/(Nt[10]+1),Qt=(Nt[9]+1)/Nt[5],ie=(Nt[9]-1)/Nt[5],ne=(Nt[8]-1)/Nt[0],ei=(Xt[8]+1)/Xt[0],ii=Lt*ne,Hi=Lt*ei,Li=V/(-ne+ei),Gi=Li*-ne;if(ct.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(Gi),Z.translateZ(Li),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Nt[10]===-1)Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse);else{const on=Lt+Li,z=Rt+Li,ws=ii-Gi,ni=Hi+(V-Gi),N=Qt*Rt/z*on,T=ie*Rt/z*on;Z.projectionMatrix.makePerspective(ws,ni,N,T,on,z),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function nt(Z,ct){ct===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ct.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(n===null)return;let ct=Z.near,ot=Z.far;g.texture!==null&&(g.depthNear>0&&(ct=g.depthNear),g.depthFar>0&&(ot=g.depthFar)),D.near=_.near=A.near=ct,D.far=_.far=A.far=ot,(O!==D.near||L!==D.far)&&(n.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,L=D.far),D.layers.mask=Z.layers.mask|6,A.layers.mask=D.layers.mask&-5,_.layers.mask=D.layers.mask&-3;const V=Z.parent,Nt=D.cameras;nt(D,V);for(let Xt=0;Xt<Nt.length;Xt++)nt(Nt[Xt],V);Nt.length===2?q(D,A,_):D.projectionMatrix.copy(A.projectionMatrix),at(Z,D,V)};function at(Z,ct,ot){ot===null?Z.matrix.copy(ct.matrixWorld):(Z.matrix.copy(ot.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ct.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=Zh*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(Z){c=Z,d!==null&&(d.fixedFoveation=Z),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Z)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(D)},this.getCameraTexture=function(Z){return v[Z]};let Bt=null;function Zt(Z,ct){if(h=ct.getViewerPose(l||r),p=ct,h!==null){const ot=h.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let V=!1;ot.length!==D.cameras.length&&(D.cameras.length=0,V=!0);for(let Rt=0;Rt<ot.length;Rt++){const Qt=ot[Rt];let ie=null;if(f!==null)ie=f.getViewport(Qt);else{const ei=u.getViewSubImage(d,Qt);ie=ei.viewport,Rt===0&&(t.setRenderTargetTextures(y,ei.colorTexture,ei.depthStencilTexture),t.setRenderTarget(y))}let ne=I[Rt];ne===void 0&&(ne=new Wn,ne.layers.enable(Rt),ne.viewport=new _e,I[Rt]=ne),ne.matrix.fromArray(Qt.transform.matrix),ne.matrix.decompose(ne.position,ne.quaternion,ne.scale),ne.projectionMatrix.fromArray(Qt.projectionMatrix),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert(),ne.viewport.set(ie.x,ie.y,ie.width,ie.height),Rt===0&&(D.matrix.copy(ne.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),V===!0&&D.cameras.push(ne)}const Nt=n.enabledFeatures;if(Nt&&Nt.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&m){u=i.getBinding();const Rt=u.getDepthInformation(ot[0]);Rt&&Rt.isValid&&Rt.texture&&g.init(Rt,n.renderState)}if(Nt&&Nt.includes("camera-access")&&m){t.state.unbindTexture(),u=i.getBinding();for(let Rt=0;Rt<ot.length;Rt++){const Qt=ot[Rt].camera;if(Qt){let ie=v[Qt];ie||(ie=new IE,v[Qt]=ie);const ne=u.getCameraImage(Qt);ie.sourceTexture=ne}}}}for(let ot=0;ot<w.length;ot++){const V=S[ot],Nt=w[ot];V!==null&&Nt!==void 0&&Nt.update(V,ct,l||r)}Bt&&Bt(Z,ct),ct.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ct}),p=null}const Pt=new $E;Pt.setAnimationLoop(Zt),this.setAnimationLoop=function(Z){Bt=Z},this.dispose=function(){}}}const OO=new Wt,jE=new ue;jE.set(-1,0,0,0,1,0,0,0,1);function PO(o,t){function e(g,v){g.matrixAutoUpdate===!0&&g.updateMatrix(),v.value.copy(g.matrix)}function i(g,v){v.color.getRGB(g.fogColor.value,FE(o)),v.isFog?(g.fogNear.value=v.near,g.fogFar.value=v.far):v.isFogExp2&&(g.fogDensity.value=v.density)}function n(g,v,M,x,y){v.isNodeMaterial?v.uniformsNeedUpdate=!1:v.isMeshBasicMaterial?s(g,v):v.isMeshLambertMaterial?(s(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshToonMaterial?(s(g,v),u(g,v)):v.isMeshPhongMaterial?(s(g,v),h(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshStandardMaterial?(s(g,v),d(g,v),v.isMeshPhysicalMaterial&&f(g,v,y)):v.isMeshMatcapMaterial?(s(g,v),p(g,v)):v.isMeshDepthMaterial?s(g,v):v.isMeshDistanceMaterial?(s(g,v),m(g,v)):v.isMeshNormalMaterial?s(g,v):v.isLineBasicMaterial?(r(g,v),v.isLineDashedMaterial&&a(g,v)):v.isPointsMaterial?c(g,v,M,x):v.isSpriteMaterial?l(g,v):v.isShadowMaterial?(g.color.value.copy(v.color),g.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function s(g,v){g.opacity.value=v.opacity,v.color&&g.diffuse.value.copy(v.color),v.emissive&&g.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.bumpMap&&(g.bumpMap.value=v.bumpMap,e(v.bumpMap,g.bumpMapTransform),g.bumpScale.value=v.bumpScale,v.side===Oi&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,e(v.normalMap,g.normalMapTransform),g.normalScale.value.copy(v.normalScale),v.side===Oi&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,e(v.displacementMap,g.displacementMapTransform),g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap,e(v.emissiveMap,g.emissiveMapTransform)),v.specularMap&&(g.specularMap.value=v.specularMap,e(v.specularMap,g.specularMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);const M=t.get(v),x=M.envMap,y=M.envMapRotation;x&&(g.envMap.value=x,g.envMapRotation.value.setFromMatrix4(OO.makeRotationFromEuler(y)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(jE),g.reflectivity.value=v.reflectivity,g.ior.value=v.ior,g.refractionRatio.value=v.refractionRatio),v.lightMap&&(g.lightMap.value=v.lightMap,g.lightMapIntensity.value=v.lightMapIntensity,e(v.lightMap,g.lightMapTransform)),v.aoMap&&(g.aoMap.value=v.aoMap,g.aoMapIntensity.value=v.aoMapIntensity,e(v.aoMap,g.aoMapTransform))}function r(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform))}function a(g,v){g.dashSize.value=v.dashSize,g.totalSize.value=v.dashSize+v.gapSize,g.scale.value=v.scale}function c(g,v,M,x){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.size.value=v.size*M,g.scale.value=x*.5,v.map&&(g.map.value=v.map,e(v.map,g.uvTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function l(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.rotation.value=v.rotation,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function h(g,v){g.specular.value.copy(v.specular),g.shininess.value=Math.max(v.shininess,1e-4)}function u(g,v){v.gradientMap&&(g.gradientMap.value=v.gradientMap)}function d(g,v){g.metalness.value=v.metalness,v.metalnessMap&&(g.metalnessMap.value=v.metalnessMap,e(v.metalnessMap,g.metalnessMapTransform)),g.roughness.value=v.roughness,v.roughnessMap&&(g.roughnessMap.value=v.roughnessMap,e(v.roughnessMap,g.roughnessMapTransform)),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)}function f(g,v,M){g.ior.value=v.ior,v.sheen>0&&(g.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),g.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(g.sheenColorMap.value=v.sheenColorMap,e(v.sheenColorMap,g.sheenColorMapTransform)),v.sheenRoughnessMap&&(g.sheenRoughnessMap.value=v.sheenRoughnessMap,e(v.sheenRoughnessMap,g.sheenRoughnessMapTransform))),v.clearcoat>0&&(g.clearcoat.value=v.clearcoat,g.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(g.clearcoatMap.value=v.clearcoatMap,e(v.clearcoatMap,g.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,e(v.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(g.clearcoatNormalMap.value=v.clearcoatNormalMap,e(v.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Oi&&g.clearcoatNormalScale.value.negate())),v.dispersion>0&&(g.dispersion.value=v.dispersion),v.iridescence>0&&(g.iridescence.value=v.iridescence,g.iridescenceIOR.value=v.iridescenceIOR,g.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(g.iridescenceMap.value=v.iridescenceMap,e(v.iridescenceMap,g.iridescenceMapTransform)),v.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=v.iridescenceThicknessMap,e(v.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),v.transmission>0&&(g.transmission.value=v.transmission,g.transmissionSamplerMap.value=M.texture,g.transmissionSamplerSize.value.set(M.width,M.height),v.transmissionMap&&(g.transmissionMap.value=v.transmissionMap,e(v.transmissionMap,g.transmissionMapTransform)),g.thickness.value=v.thickness,v.thicknessMap&&(g.thicknessMap.value=v.thicknessMap,e(v.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=v.attenuationDistance,g.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(g.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(g.anisotropyMap.value=v.anisotropyMap,e(v.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=v.specularIntensity,g.specularColor.value.copy(v.specularColor),v.specularColorMap&&(g.specularColorMap.value=v.specularColorMap,e(v.specularColorMap,g.specularColorMapTransform)),v.specularIntensityMap&&(g.specularIntensityMap.value=v.specularIntensityMap,e(v.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,v){v.matcap&&(g.matcap.value=v.matcap)}function m(g,v){const M=t.get(v).light;g.referencePosition.value.setFromMatrixPosition(M.matrixWorld),g.nearDistance.value=M.shadow.camera.near,g.farDistance.value=M.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function NO(o,t,e,i){let n={},s={},r=[];const a=o.getParameter(o.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,w){const S=w.program;i.uniformBlockBinding(y,S)}function l(y,w){let S=n[y.id];S===void 0&&(g(y),S=h(y),n[y.id]=S,y.addEventListener("dispose",M));const E=w.program;i.updateUBOMapping(y,E);const b=t.render.frame;s[y.id]!==b&&(d(y),s[y.id]=b)}function h(y){const w=u();y.__bindingPointIndex=w;const S=o.createBuffer(),E=y.__size,b=y.usage;return o.bindBuffer(o.UNIFORM_BUFFER,S),o.bufferData(o.UNIFORM_BUFFER,E,b),o.bindBuffer(o.UNIFORM_BUFFER,null),o.bindBufferBase(o.UNIFORM_BUFFER,w,S),S}function u(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ce("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const w=n[y.id],S=y.uniforms,E=y.__cache;o.bindBuffer(o.UNIFORM_BUFFER,w);for(let b=0,A=S.length;b<A;b++){const _=S[b];if(Array.isArray(_))for(let I=0,D=_.length;I<D;I++)f(_[I],b,I,E);else f(_,b,0,E)}o.bindBuffer(o.UNIFORM_BUFFER,null)}function f(y,w,S,E){if(m(y,w,S,E)===!0){const b=y.__offset,A=y.value;if(Array.isArray(A)){let _=0;for(let I=0;I<A.length;I++){const D=A[I],O=v(D);p(D,y.__data,_),typeof D!="number"&&typeof D!="boolean"&&!D.isMatrix3&&!ArrayBuffer.isView(D)&&(_+=O.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);o.bufferSubData(o.UNIFORM_BUFFER,b,y.__data)}}function p(y,w,S){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,S)}function m(y,w,S,E){const b=y.value,A=w+"_"+S;if(E[A]===void 0)return typeof b=="number"||typeof b=="boolean"?E[A]=b:ArrayBuffer.isView(b)?E[A]=b.slice():E[A]=b.clone(),!0;{const _=E[A];if(typeof b=="number"||typeof b=="boolean"){if(_!==b)return E[A]=b,!0}else{if(ArrayBuffer.isView(b))return!0;if(_.equals(b)===!1)return _.copy(b),!0}}return!1}function g(y){const w=y.uniforms;let S=0;const E=16;for(let A=0,_=w.length;A<_;A++){const I=Array.isArray(w[A])?w[A]:[w[A]];for(let D=0,O=I.length;D<O;D++){const L=I[D],P=Array.isArray(L.value)?L.value:[L.value];for(let k=0,H=P.length;k<H;k++){const W=P[k],Q=v(W),q=S%E,nt=q%Q.boundary,at=q+nt;S+=nt,at!==0&&E-at<Q.storage&&(S+=E-at),L.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=S,S+=Q.storage}}}const b=S%E;return b>0&&(S+=E-b),y.__size=S,y.__cache={},this}function v(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?zt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):zt("WebGLRenderer: Unsupported uniform value type.",y),w}function M(y){const w=y.target;w.removeEventListener("dispose",M);const S=r.indexOf(w.__bindingPointIndex);r.splice(S,1),o.deleteBuffer(n[w.id]),delete n[w.id],delete s[w.id]}function x(){for(const y in n)o.deleteBuffer(n[y]);r=[],n={},s={}}return{bind:c,update:l,dispose:x}}const LO=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Br=null;function kO(){return Br===null&&(Br=new ys(LO,16,16,Qc,We),Br.name="DFG_LUT",Br.minFilter=ge,Br.magFilter=ge,Br.wrapS=Ki,Br.wrapT=Ki,Br.generateMipmaps=!1,Br.needsUpdate=!0),Br}class UO{constructor(t={}){const{canvas:e=C5(),context:i=null,depth:n=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=is}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=r;const m=f,g=new Set([IM,RM,TM]),v=new Set([is,dr,Fd,zd,AM,_M]),M=new Uint32Array(4),x=new Int32Array(4),y=new R;let w=null,S=null;const E=[],b=[];let A=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=xa,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let I=!1,D=null,O=null,L=null,P=null;this._outputColorSpace=Nn;let k=0,H=0,W=null,Q=-1,q=null;const nt=new _e,at=new _e;let Bt=null;const Zt=new rt(0);let Pt=0,Z=e.width,ct=e.height,ot=1,V=null,Nt=null;const Xt=new _e(0,0,Z,ct),Lt=new _e(0,0,Z,ct);let Rt=!1;const Qt=new nm;let ie=!1,ne=!1;const ei=new Wt,ii=new R,Hi=new _e,Li={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Gi=!1;function on(){return W===null?ot:1}let z=i;function ws(C,B){return e.getContext(C,B)}try{const C={alpha:!0,depth:n,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${tf}`),e.addEventListener("webglcontextlost",Vi,!1),e.addEventListener("webglcontextrestored",wi,!1),e.addEventListener("webglcontextcreationerror",Lr,!1),z===null){const B="webgl2";if(z=ws(B,C),z===null)throw ws(B)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(C){throw ce("WebGLRenderer: "+C.message),C}let ni,N,T,G,Y,J,ht,ft,j,it,mt,$t,xt,gt,Jt,se,be,F,dt,et,vt,At,st;function Vt(){ni=new kC(z),ni.init(),vt=new TO(z,ni),N=new RC(z,ni,t,vt),T=new AO(z,ni),N.reversedDepthBuffer&&d&&T.buffers.depth.setReversed(!0),O=z.createFramebuffer(),L=z.createFramebuffer(),P=z.createFramebuffer(),G=new zC(z),Y=new uO,J=new _O(z,ni,T,Y,N,vt,G),ht=new LC(_),ft=new V4(z),At=new _C(z,ft),j=new UC(z,ft,G,At),it=new HC(z,j,ft,At,G),F=new BC(z,N,J),Jt=new IC(Y),mt=new hO(_,ht,ni,N,At,Jt),$t=new PO(_,Y),xt=new fO,gt=new yO(ni),be=new AC(_,ht,T,it,p,c),se=new EO(_,it,N),st=new NO(z,G,N,T),dt=new TC(z,ni,G),et=new FC(z,ni,G),G.programs=mt.programs,_.capabilities=N,_.extensions=ni,_.properties=Y,_.renderLists=xt,_.shadowMap=se,_.state=T,_.info=G}Vt(),m!==is&&(A=new VC(m,e.width,e.height,a,n,s));const kt=new CO(_,z);this.xr=kt,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const C=ni.get("WEBGL_lose_context");C&&C.loseContext()},this.forceContextRestore=function(){const C=ni.get("WEBGL_lose_context");C&&C.restoreContext()},this.getPixelRatio=function(){return ot},this.setPixelRatio=function(C){C!==void 0&&(ot=C,this.setSize(Z,ct,!1))},this.getSize=function(C){return C.set(Z,ct)},this.setSize=function(C,B,K=!0){if(kt.isPresenting){zt("WebGLRenderer: Can't change size while VR device is presenting.");return}Z=C,ct=B,e.width=Math.floor(C*ot),e.height=Math.floor(B*ot),K===!0&&(e.style.width=C+"px",e.style.height=B+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,C,B)},this.getDrawingBufferSize=function(C){return C.set(Z*ot,ct*ot).floor()},this.setDrawingBufferSize=function(C,B,K){Z=C,ct=B,ot=K,e.width=Math.floor(C*K),e.height=Math.floor(B*K),this.setViewport(0,0,C,B)},this.setEffects=function(C){if(m===is){ce("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(C){for(let B=0;B<C.length;B++)if(C[B].isOutputPass===!0){zt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(C||[])},this.getCurrentViewport=function(C){return C.copy(nt)},this.getViewport=function(C){return C.copy(Xt)},this.setViewport=function(C,B,K,X){C.isVector4?Xt.set(C.x,C.y,C.z,C.w):Xt.set(C,B,K,X),T.viewport(nt.copy(Xt).multiplyScalar(ot).round())},this.getScissor=function(C){return C.copy(Lt)},this.setScissor=function(C,B,K,X){C.isVector4?Lt.set(C.x,C.y,C.z,C.w):Lt.set(C,B,K,X),T.scissor(at.copy(Lt).multiplyScalar(ot).round())},this.getScissorTest=function(){return Rt},this.setScissorTest=function(C){T.setScissorTest(Rt=C)},this.setOpaqueSort=function(C){V=C},this.setTransparentSort=function(C){Nt=C},this.getClearColor=function(C){return C.copy(be.getClearColor())},this.setClearColor=function(){be.setClearColor(...arguments)},this.getClearAlpha=function(){return be.getClearAlpha()},this.setClearAlpha=function(){be.setClearAlpha(...arguments)},this.clear=function(C=!0,B=!0,K=!0){let X=0;if(C){let $=!1;if(W!==null){const St=W.texture.format;$=g.has(St)}if($){const St=W.texture.type,It=v.has(St),bt=be.getClearColor(),Ut=be.getClearAlpha(),Yt=bt.r,Se=bt.g,Ie=bt.b;It?(M[0]=Yt,M[1]=Se,M[2]=Ie,M[3]=Ut,z.clearBufferuiv(z.COLOR,0,M)):(x[0]=Yt,x[1]=Se,x[2]=Ie,x[3]=Ut,z.clearBufferiv(z.COLOR,0,x))}else X|=z.COLOR_BUFFER_BIT}B&&(X|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),K&&(X|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),X!==0&&z.clear(X)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(C){C.setRenderer(this),D=C},this.dispose=function(){e.removeEventListener("webglcontextlost",Vi,!1),e.removeEventListener("webglcontextrestored",wi,!1),e.removeEventListener("webglcontextcreationerror",Lr,!1),be.dispose(),xt.dispose(),gt.dispose(),Y.dispose(),ht.dispose(),it.dispose(),At.dispose(),st.dispose(),mt.dispose(),kt.dispose(),kt.removeEventListener("sessionstart",xy),kt.removeEventListener("sessionend",wy),lc.stop()};function Vi(C){C.preventDefault(),xp("WebGLRenderer: Context Lost."),I=!0}function wi(){xp("WebGLRenderer: Context Restored."),I=!1;const C=G.autoReset,B=se.enabled,K=se.autoUpdate,X=se.needsUpdate,$=se.type;Vt(),G.autoReset=C,se.enabled=B,se.autoUpdate=K,se.needsUpdate=X,se.type=$}function Lr(C){ce("WebGLRenderer: A WebGL context could not be created. Reason: ",C.statusMessage)}function kr(C){const B=C.target;B.removeEventListener("dispose",kr),n3(B)}function n3(C){s3(C),Y.remove(C)}function s3(C){const B=Y.get(C).programs;B!==void 0&&(B.forEach(function(K){mt.releaseProgram(K)}),C.isShaderMaterial&&mt.releaseShaderCache(C))}this.renderBufferDirect=function(C,B,K,X,$,St){B===null&&(B=Li);const It=$.isMesh&&$.matrixWorld.determinantAffine()<0,bt=o3(C,B,K,X,$);T.setMaterial(X,It);let Ut=K.index,Yt=1;if(X.wireframe===!0){if(Ut=j.getWireframeAttribute(K),Ut===void 0)return;Yt=2}const Se=K.drawRange,Ie=K.attributes.position;let Kt=Se.start*Yt,di=(Se.start+Se.count)*Yt;St!==null&&(Kt=Math.max(Kt,St.start*Yt),di=Math.min(di,(St.start+St.count)*Yt)),Ut!==null?(Kt=Math.max(Kt,0),di=Math.min(di,Ut.count)):Ie!=null&&(Kt=Math.max(Kt,0),di=Math.min(di,Ie.count));const Ji=di-Kt;if(Ji<0||Ji===1/0)return;At.setup($,X,bt,K,Ut);let Wi,vi=dt;if(Ut!==null&&(Wi=ft.get(Ut),vi=et,vi.setIndex(Wi)),$.isMesh)X.wireframe===!0?(T.setLineWidth(X.wireframeLinewidth*on()),vi.setMode(z.LINES)):vi.setMode(z.TRIANGLES);else if($.isLine){let $n=X.linewidth;$n===void 0&&($n=1),T.setLineWidth($n*on()),$.isLineSegments?vi.setMode(z.LINES):$.isLineLoop?vi.setMode(z.LINE_LOOP):vi.setMode(z.LINE_STRIP)}else $.isPoints?vi.setMode(z.POINTS):$.isSprite&&vi.setMode(z.TRIANGLES);if($.isBatchedMesh)if(ni.get("WEBGL_multi_draw"))vi.renderMultiDraw($._multiDrawStarts,$._multiDrawCounts,$._multiDrawCount);else{const $n=$._multiDrawStarts,Tt=$._multiDrawCounts,Us=$._multiDrawCount,Be=Ut?ft.get(Ut).bytesPerElement:1,Qs=Y.get(X).currentProgram.getUniforms();for(let Ur=0;Ur<Us;Ur++)Qs.setValue(z,"_gl_DrawID",Ur),vi.render($n[Ur]/Be,Tt[Ur])}else if($.isInstancedMesh)vi.renderInstances(Kt,Ji,$.count);else if(K.isInstancedBufferGeometry){const $n=K._maxInstanceCount!==void 0?K._maxInstanceCount:1/0,Tt=Math.min(K.instanceCount,$n);vi.renderInstances(Kt,Ji,Tt)}else vi.render(Kt,Ji)};function yy(C,B,K){C.transparent===!0&&C.side===bn&&C.forceSinglePass===!1?(C.side=Oi,C.needsUpdate=!0,of(C,B,K),C.side=Sa,C.needsUpdate=!0,of(C,B,K),C.side=bn):of(C,B,K)}this.compile=function(C,B,K=null){K===null&&(K=C),S=gt.get(K),S.init(B),b.push(S),K.traverseVisible(function($){$.isLight&&$.layers.test(B.layers)&&(S.pushLight($),$.castShadow&&S.pushShadow($))}),C!==K&&C.traverseVisible(function($){$.isLight&&$.layers.test(B.layers)&&(S.pushLight($),$.castShadow&&S.pushShadow($))}),S.setupLights();const X=new Set;return C.traverse(function($){if(!($.isMesh||$.isPoints||$.isLine||$.isSprite))return;const St=$.material;if(St)if(Array.isArray(St))for(let It=0;It<St.length;It++){const bt=St[It];yy(bt,K,$),X.add(bt)}else yy(St,K,$),X.add(St)}),S=b.pop(),X},this.compileAsync=function(C,B,K=null){const X=this.compile(C,B,K);return new Promise($=>{function St(){if(X.forEach(function(It){Y.get(It).currentProgram.isReady()&&X.delete(It)}),X.size===0){$(C);return}setTimeout(St,10)}ni.get("KHR_parallel_shader_compile")!==null?St():setTimeout(St,10)})};let ym=null;function r3(C){ym&&ym(C)}function xy(){lc.stop()}function wy(){lc.start()}const lc=new $E;lc.setAnimationLoop(r3),typeof self<"u"&&lc.setContext(self),this.setAnimationLoop=function(C){ym=C,kt.setAnimationLoop(C),C===null?lc.stop():lc.start()},kt.addEventListener("sessionstart",xy),kt.addEventListener("sessionend",wy),this.render=function(C,B){if(B!==void 0&&B.isCamera!==!0){ce("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(I===!0)return;D!==null&&D.renderStart(C,B);const K=kt.enabled===!0&&kt.isPresenting===!0,X=A!==null&&(W===null||K)&&A.begin(_,W);if(C.matrixWorldAutoUpdate===!0&&C.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),kt.enabled===!0&&kt.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(kt.cameraAutoUpdate===!0&&kt.updateCamera(B),B=kt.getCamera()),C.isScene===!0&&C.onBeforeRender(_,C,B,W),S=gt.get(C,b.length),S.init(B),S.state.textureUnits=J.getTextureUnits(),b.push(S),ei.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Qt.setFromProjectionMatrix(ei,va,B.reversedDepth),ne=this.localClippingEnabled,ie=Jt.init(this.clippingPlanes,ne),w=xt.get(C,E.length),w.init(),E.push(w),kt.enabled===!0&&kt.isPresenting===!0){const It=_.xr.getDepthSensingMesh();It!==null&&xm(It,B,-1/0,_.sortObjects)}xm(C,B,0,_.sortObjects),w.finish(),_.sortObjects===!0&&w.sort(V,Nt,B.reversedDepth),Gi=kt.enabled===!1||kt.isPresenting===!1||kt.hasDepthSensing()===!1,Gi&&be.addToRenderList(w,C),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ie===!0&&Jt.beginShadows();const $=S.state.shadowsArray;if(se.render($,C,B),ie===!0&&Jt.endShadows(),(X&&A.hasRenderPass())===!1){const It=w.opaque,bt=w.transmissive;if(S.setupLights(),B.isArrayCamera){const Ut=B.cameras;if(bt.length>0)for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Ie=Ut[Yt];Sy(It,bt,C,Ie)}Gi&&be.render(C);for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Ie=Ut[Yt];by(w,C,Ie,Ie.viewport)}}else bt.length>0&&Sy(It,bt,C,B),Gi&&be.render(C),by(w,C,B)}W!==null&&H===0&&(J.updateMultisampleRenderTarget(W),J.updateRenderTargetMipmap(W)),X&&A.end(_),C.isScene===!0&&C.onAfterRender(_,C,B),At.resetDefaultState(),Q=-1,q=null,b.pop(),b.length>0?(S=b[b.length-1],J.setTextureUnits(S.state.textureUnits),ie===!0&&Jt.setGlobalState(_.clippingPlanes,S.state.camera)):S=null,E.pop(),E.length>0?w=E[E.length-1]:w=null,D!==null&&D.renderEnd()};function xm(C,B,K,X){if(C.visible===!1)return;if(C.layers.test(B.layers)){if(C.isGroup)K=C.renderOrder;else if(C.isLOD)C.autoUpdate===!0&&C.update(B);else if(C.isLightProbeGrid)S.pushLightProbeGrid(C);else if(C.isLight)S.pushLight(C),C.castShadow&&S.pushShadow(C);else if(C.isSprite){if(!C.frustumCulled||Qt.intersectsSprite(C)){X&&Hi.setFromMatrixPosition(C.matrixWorld).applyMatrix4(ei);const It=it.update(C),bt=C.material;bt.visible&&w.push(C,It,bt,K,Hi.z,null)}}else if((C.isMesh||C.isLine||C.isPoints)&&(!C.frustumCulled||Qt.intersectsObject(C))){const It=it.update(C),bt=C.material;if(X&&(C.boundingSphere!==void 0?(C.boundingSphere===null&&C.computeBoundingSphere(),Hi.copy(C.boundingSphere.center)):(It.boundingSphere===null&&It.computeBoundingSphere(),Hi.copy(It.boundingSphere.center)),Hi.applyMatrix4(C.matrixWorld).applyMatrix4(ei)),Array.isArray(bt)){const Ut=It.groups;for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Ie=Ut[Yt],Kt=bt[Ie.materialIndex];Kt&&Kt.visible&&w.push(C,It,Kt,K,Hi.z,Ie)}}else bt.visible&&w.push(C,It,bt,K,Hi.z,null)}}const St=C.children;for(let It=0,bt=St.length;It<bt;It++)xm(St[It],B,K,X)}function by(C,B,K,X){const{opaque:$,transmissive:St,transparent:It}=C;S.setupLightsView(K),ie===!0&&Jt.setGlobalState(_.clippingPlanes,K),X&&T.viewport(nt.copy(X)),$.length>0&&af($,B,K),St.length>0&&af(St,B,K),It.length>0&&af(It,B,K),T.buffers.depth.setTest(!0),T.buffers.depth.setMask(!0),T.buffers.color.setMask(!0),T.setPolygonOffset(!1)}function Sy(C,B,K,X){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[X.id]===void 0){const Kt=ni.has("EXT_color_buffer_half_float")||ni.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[X.id]=new qe(1,1,{generateMipmaps:!0,type:Kt?We:is,minFilter:qs,samples:Math.max(4,N.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Fe.workingColorSpace})}const St=S.state.transmissionRenderTarget[X.id],It=X.viewport||nt;St.setSize(It.z*_.transmissionResolutionScale,It.w*_.transmissionResolutionScale);const bt=_.getRenderTarget(),Ut=_.getActiveCubeFace(),Yt=_.getActiveMipmapLevel();_.setRenderTarget(St),_.getClearColor(Zt),Pt=_.getClearAlpha(),Pt<1&&_.setClearColor(16777215,.5),_.clear(),Gi&&be.render(K);const Se=_.toneMapping;_.toneMapping=xa;const Ie=X.viewport;if(X.viewport!==void 0&&(X.viewport=void 0),S.setupLightsView(X),ie===!0&&Jt.setGlobalState(_.clippingPlanes,X),af(C,K,X),J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St),ni.has("WEBGL_multisampled_render_to_texture")===!1){let Kt=!1;for(let di=0,Ji=B.length;di<Ji;di++){const Wi=B[di],{object:vi,geometry:$n,material:Tt,group:Us}=Wi;if(Tt.side===bn&&vi.layers.test(X.layers)){const Be=Tt.side;Tt.side=Oi,Tt.needsUpdate=!0,Ey(vi,K,X,$n,Tt,Us),Tt.side=Be,Tt.needsUpdate=!0,Kt=!0}}Kt===!0&&(J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St))}_.setRenderTarget(bt,Ut,Yt),_.setClearColor(Zt,Pt),Ie!==void 0&&(X.viewport=Ie),_.toneMapping=Se}function af(C,B,K){const X=B.isScene===!0?B.overrideMaterial:null;for(let $=0,St=C.length;$<St;$++){const It=C[$],{object:bt,geometry:Ut,group:Yt}=It;let Se=It.material;Se.allowOverride===!0&&X!==null&&(Se=X),bt.layers.test(K.layers)&&Ey(bt,B,K,Ut,Se,Yt)}}function Ey(C,B,K,X,$,St){C.onBeforeRender(_,B,K,X,$,St),C.modelViewMatrix.multiplyMatrices(K.matrixWorldInverse,C.matrixWorld),C.normalMatrix.getNormalMatrix(C.modelViewMatrix),$.onBeforeRender(_,B,K,X,C,St),$.transparent===!0&&$.side===bn&&$.forceSinglePass===!1?($.side=Oi,$.needsUpdate=!0,_.renderBufferDirect(K,B,X,$,C,St),$.side=Sa,$.needsUpdate=!0,_.renderBufferDirect(K,B,X,$,C,St),$.side=bn):_.renderBufferDirect(K,B,X,$,C,St),C.onAfterRender(_,B,K,X,$,St)}function of(C,B,K){B.isScene!==!0&&(B=Li);const X=Y.get(C),$=S.state.lights,St=S.state.shadowsArray,It=$.state.version,bt=mt.getParameters(C,$.state,St,B,K,S.state.lightProbeGridArray),Ut=mt.getProgramCacheKey(bt);let Yt=X.programs;X.environment=C.isMeshStandardMaterial||C.isMeshLambertMaterial||C.isMeshPhongMaterial?B.environment:null,X.fog=B.fog;const Se=C.isMeshStandardMaterial||C.isMeshLambertMaterial&&!C.envMap||C.isMeshPhongMaterial&&!C.envMap;X.envMap=ht.get(C.envMap||X.environment,Se),X.envMapRotation=X.environment!==null&&C.envMap===null?B.environmentRotation:C.envMapRotation,Yt===void 0&&(C.addEventListener("dispose",kr),Yt=new Map,X.programs=Yt);let Ie=Yt.get(Ut);if(Ie!==void 0){if(X.currentProgram===Ie&&X.lightsStateVersion===It)return _y(C,bt),Ie}else bt.uniforms=mt.getUniforms(C),D!==null&&C.isNodeMaterial&&D.build(C,K,bt),C.onBeforeCompile(bt,_),Ie=mt.acquireProgram(bt,Ut),Yt.set(Ut,Ie),X.uniforms=bt.uniforms;const Kt=X.uniforms;return(!C.isShaderMaterial&&!C.isRawShaderMaterial||C.clipping===!0)&&(Kt.clippingPlanes=Jt.uniform),_y(C,bt),X.needsLights=l3(C),X.lightsStateVersion=It,X.needsLights&&(Kt.ambientLightColor.value=$.state.ambient,Kt.lightProbe.value=$.state.probe,Kt.directionalLights.value=$.state.directional,Kt.directionalLightShadows.value=$.state.directionalShadow,Kt.spotLights.value=$.state.spot,Kt.spotLightShadows.value=$.state.spotShadow,Kt.rectAreaLights.value=$.state.rectArea,Kt.ltc_1.value=$.state.rectAreaLTC1,Kt.ltc_2.value=$.state.rectAreaLTC2,Kt.pointLights.value=$.state.point,Kt.pointLightShadows.value=$.state.pointShadow,Kt.hemisphereLights.value=$.state.hemi,Kt.directionalShadowMatrix.value=$.state.directionalShadowMatrix,Kt.spotLightMatrix.value=$.state.spotLightMatrix,Kt.spotLightMap.value=$.state.spotLightMap,Kt.pointShadowMatrix.value=$.state.pointShadowMatrix),X.lightProbeGrid=S.state.lightProbeGridArray.length>0,X.currentProgram=Ie,X.uniformsList=null,Ie}function Ay(C){if(C.uniformsList===null){const B=C.currentProgram.getUniforms();C.uniformsList=W0.seqWithValue(B.seq,C.uniforms)}return C.uniformsList}function _y(C,B){const K=Y.get(C);K.outputColorSpace=B.outputColorSpace,K.batching=B.batching,K.batchingColor=B.batchingColor,K.instancing=B.instancing,K.instancingColor=B.instancingColor,K.instancingMorph=B.instancingMorph,K.skinning=B.skinning,K.morphTargets=B.morphTargets,K.morphNormals=B.morphNormals,K.morphColors=B.morphColors,K.morphTargetsCount=B.morphTargetsCount,K.numClippingPlanes=B.numClippingPlanes,K.numIntersection=B.numClipIntersection,K.vertexAlphas=B.vertexAlphas,K.vertexTangents=B.vertexTangents,K.toneMapping=B.toneMapping}function a3(C,B){if(C.length===0)return null;if(C.length===1)return C[0].texture!==null?C[0]:null;y.setFromMatrixPosition(B.matrixWorld);for(let K=0,X=C.length;K<X;K++){const $=C[K];if($.texture!==null&&$.boundingBox.containsPoint(y))return $}return null}function o3(C,B,K,X,$){B.isScene!==!0&&(B=Li),J.resetTextureUnits();const St=B.fog,It=X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial?B.environment:null,bt=W===null?_.outputColorSpace:W.isXRRenderTarget===!0?W.texture.colorSpace:Fe.workingColorSpace,Ut=X.isMeshStandardMaterial||X.isMeshLambertMaterial&&!X.envMap||X.isMeshPhongMaterial&&!X.envMap,Yt=ht.get(X.envMap||It,Ut),Se=X.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,Ie=!!K.attributes.tangent&&(!!X.normalMap||X.anisotropy>0),Kt=!!K.morphAttributes.position,di=!!K.morphAttributes.normal,Ji=!!K.morphAttributes.color;let Wi=xa;X.toneMapped&&(W===null||W.isXRRenderTarget===!0)&&(Wi=_.toneMapping);const vi=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,$n=vi!==void 0?vi.length:0,Tt=Y.get(X),Us=S.state.lights;if(ie===!0&&(ne===!0||C!==q)){const bi=C===q&&X.id===Q;Jt.setState(X,C,bi)}let Be=!1;X.version===Tt.__version?(Tt.needsLights&&Tt.lightsStateVersion!==Us.state.version||Tt.outputColorSpace!==bt||$.isBatchedMesh&&Tt.batching===!1||!$.isBatchedMesh&&Tt.batching===!0||$.isBatchedMesh&&Tt.batchingColor===!0&&$.colorTexture===null||$.isBatchedMesh&&Tt.batchingColor===!1&&$.colorTexture!==null||$.isInstancedMesh&&Tt.instancing===!1||!$.isInstancedMesh&&Tt.instancing===!0||$.isSkinnedMesh&&Tt.skinning===!1||!$.isSkinnedMesh&&Tt.skinning===!0||$.isInstancedMesh&&Tt.instancingColor===!0&&$.instanceColor===null||$.isInstancedMesh&&Tt.instancingColor===!1&&$.instanceColor!==null||$.isInstancedMesh&&Tt.instancingMorph===!0&&$.morphTexture===null||$.isInstancedMesh&&Tt.instancingMorph===!1&&$.morphTexture!==null||Tt.envMap!==Yt||X.fog===!0&&Tt.fog!==St||Tt.numClippingPlanes!==void 0&&(Tt.numClippingPlanes!==Jt.numPlanes||Tt.numIntersection!==Jt.numIntersection)||Tt.vertexAlphas!==Se||Tt.vertexTangents!==Ie||Tt.morphTargets!==Kt||Tt.morphNormals!==di||Tt.morphColors!==Ji||Tt.toneMapping!==Wi||Tt.morphTargetsCount!==$n||!!Tt.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(Be=!0):(Be=!0,Tt.__version=X.version);let Qs=Tt.currentProgram;Be===!0&&(Qs=of(X,B,$),D&&X.isNodeMaterial&&D.onUpdateProgram(X,Qs,Tt));let Ur=!1,ho=!1,rl=!1;const Mi=Qs.getUniforms(),ji=Tt.uniforms;if(T.useProgram(Qs.program)&&(Ur=!0,ho=!0,rl=!0),X.id!==Q&&(Q=X.id,ho=!0),Tt.needsLights){const bi=a3(S.state.lightProbeGridArray,$);Tt.lightProbeGrid!==bi&&(Tt.lightProbeGrid=bi,ho=!0)}if(Ur||q!==C){T.buffers.depth.getReversed()&&C.reversedDepth!==!0&&(C._reversedDepth=!0,C.updateProjectionMatrix()),Mi.setValue(z,"projectionMatrix",C.projectionMatrix),Mi.setValue(z,"viewMatrix",C.matrixWorldInverse);const fo=Mi.map.cameraPosition;fo!==void 0&&fo.setValue(z,ii.setFromMatrixPosition(C.matrixWorld)),N.logarithmicDepthBuffer&&Mi.setValue(z,"logDepthBufFC",2/(Math.log(C.far+1)/Math.LN2)),(X.isMeshPhongMaterial||X.isMeshToonMaterial||X.isMeshLambertMaterial||X.isMeshBasicMaterial||X.isMeshStandardMaterial||X.isShaderMaterial)&&Mi.setValue(z,"isOrthographic",C.isOrthographicCamera===!0),q!==C&&(q=C,ho=!0,rl=!0)}if(Tt.needsLights&&(Us.state.directionalShadowMap.length>0&&Mi.setValue(z,"directionalShadowMap",Us.state.directionalShadowMap,J),Us.state.spotShadowMap.length>0&&Mi.setValue(z,"spotShadowMap",Us.state.spotShadowMap,J),Us.state.pointShadowMap.length>0&&Mi.setValue(z,"pointShadowMap",Us.state.pointShadowMap,J)),$.isSkinnedMesh){Mi.setOptional(z,$,"bindMatrix"),Mi.setOptional(z,$,"bindMatrixInverse");const bi=$.skeleton;bi&&(bi.boneTexture===null&&bi.computeBoneTexture(),Mi.setValue(z,"boneTexture",bi.boneTexture,J))}$.isBatchedMesh&&(Mi.setOptional(z,$,"batchingTexture"),Mi.setValue(z,"batchingTexture",$._matricesTexture,J),Mi.setOptional(z,$,"batchingIdTexture"),Mi.setValue(z,"batchingIdTexture",$._indirectTexture,J),Mi.setOptional(z,$,"batchingColorTexture"),$._colorsTexture!==null&&Mi.setValue(z,"batchingColorTexture",$._colorsTexture,J));const uo=K.morphAttributes;if((uo.position!==void 0||uo.normal!==void 0||uo.color!==void 0)&&F.update($,K,Qs),(ho||Tt.receiveShadow!==$.receiveShadow)&&(Tt.receiveShadow=$.receiveShadow,Mi.setValue(z,"receiveShadow",$.receiveShadow)),(X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial)&&X.envMap===null&&B.environment!==null&&(ji.envMapIntensity.value=B.environmentIntensity),ji.dfgLUT!==void 0&&(ji.dfgLUT.value=kO()),ho){if(Mi.setValue(z,"toneMappingExposure",_.toneMappingExposure),Tt.needsLights&&c3(ji,rl),St&&X.fog===!0&&$t.refreshFogUniforms(ji,St),$t.refreshMaterialUniforms(ji,X,ot,ct,S.state.transmissionRenderTarget[C.id]),Tt.needsLights&&Tt.lightProbeGrid){const bi=Tt.lightProbeGrid;ji.probesSH.value=bi.texture,ji.probesMin.value.copy(bi.boundingBox.min),ji.probesMax.value.copy(bi.boundingBox.max),ji.probesResolution.value.copy(bi.resolution)}W0.upload(z,Ay(Tt),ji,J)}if(X.isShaderMaterial&&X.uniformsNeedUpdate===!0&&(W0.upload(z,Ay(Tt),ji,J),X.uniformsNeedUpdate=!1),X.isSpriteMaterial&&Mi.setValue(z,"center",$.center),Mi.setValue(z,"modelViewMatrix",$.modelViewMatrix),Mi.setValue(z,"normalMatrix",$.normalMatrix),Mi.setValue(z,"modelMatrix",$.matrixWorld),X.uniformsGroups!==void 0){const bi=X.uniformsGroups;for(let fo=0,al=bi.length;fo<al;fo++){const Ty=bi[fo];st.update(Ty,Qs),st.bind(Ty,Qs)}}return Qs}function c3(C,B){C.ambientLightColor.needsUpdate=B,C.lightProbe.needsUpdate=B,C.directionalLights.needsUpdate=B,C.directionalLightShadows.needsUpdate=B,C.pointLights.needsUpdate=B,C.pointLightShadows.needsUpdate=B,C.spotLights.needsUpdate=B,C.spotLightShadows.needsUpdate=B,C.rectAreaLights.needsUpdate=B,C.hemisphereLights.needsUpdate=B}function l3(C){return C.isMeshLambertMaterial||C.isMeshToonMaterial||C.isMeshPhongMaterial||C.isMeshStandardMaterial||C.isShadowMaterial||C.isShaderMaterial&&C.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return H},this.getRenderTarget=function(){return W},this.setRenderTargetTextures=function(C,B,K){const X=Y.get(C);X.__autoAllocateDepthBuffer=C.resolveDepthBuffer===!1,X.__autoAllocateDepthBuffer===!1&&(X.__useRenderToTexture=!1),Y.get(C.texture).__webglTexture=B,Y.get(C.depthTexture).__webglTexture=X.__autoAllocateDepthBuffer?void 0:K,X.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(C,B){const K=Y.get(C);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0},this.setRenderTarget=function(C,B=0,K=0){W=C,k=B,H=K;let X=null,$=!1,St=!1;if(C){const bt=Y.get(C);if(bt.__useDefaultFramebuffer!==void 0){T.bindFramebuffer(z.FRAMEBUFFER,bt.__webglFramebuffer),nt.copy(C.viewport),at.copy(C.scissor),Bt=C.scissorTest,T.viewport(nt),T.scissor(at),T.setScissorTest(Bt),Q=-1;return}else if(bt.__webglFramebuffer===void 0)J.setupRenderTarget(C);else if(bt.__hasExternalTextures)J.rebindTextures(C,Y.get(C.texture).__webglTexture,Y.get(C.depthTexture).__webglTexture);else if(C.depthBuffer){const Se=C.depthTexture;if(bt.__boundDepthTexture!==Se){if(Se!==null&&Y.has(Se)&&(C.width!==Se.image.width||C.height!==Se.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");J.setupDepthRenderbuffer(C)}}const Ut=C.texture;(Ut.isData3DTexture||Ut.isDataArrayTexture||Ut.isCompressedArrayTexture)&&(St=!0);const Yt=Y.get(C).__webglFramebuffer;C.isWebGLCubeRenderTarget?(Array.isArray(Yt[B])?X=Yt[B][K]:X=Yt[B],$=!0):C.samples>0&&J.useMultisampledRTT(C)===!1?X=Y.get(C).__webglMultisampledFramebuffer:Array.isArray(Yt)?X=Yt[K]:X=Yt,nt.copy(C.viewport),at.copy(C.scissor),Bt=C.scissorTest}else nt.copy(Xt).multiplyScalar(ot).floor(),at.copy(Lt).multiplyScalar(ot).floor(),Bt=Rt;if(K!==0&&(X=O),T.bindFramebuffer(z.FRAMEBUFFER,X)&&T.drawBuffers(C,X),T.viewport(nt),T.scissor(at),T.setScissorTest(Bt),$){const bt=Y.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+B,bt.__webglTexture,K)}else if(St){const bt=B;for(let Ut=0;Ut<C.textures.length;Ut++){const Yt=Y.get(C.textures[Ut]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+Ut,Yt.__webglTexture,K,bt)}}else if(C!==null&&K!==0){const bt=Y.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,bt.__webglTexture,K)}Q=-1},this.readRenderTargetPixels=function(C,B,K,X,$,St,It,bt=0){if(!(C&&C.isWebGLRenderTarget)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ut=Y.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&It!==void 0&&(Ut=Ut[It]),Ut){T.bindFramebuffer(z.FRAMEBUFFER,Ut);try{const Yt=C.textures[bt],Se=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+bt),!N.textureFormatReadable(Se)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!N.textureTypeReadable(Ie)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}B>=0&&B<=C.width-X&&K>=0&&K<=C.height-$&&z.readPixels(B,K,X,$,vt.convert(Se),vt.convert(Ie),St)}finally{const Yt=W!==null?Y.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,Yt)}}},this.readRenderTargetPixelsAsync=async function(C,B,K,X,$,St,It,bt=0){if(!(C&&C.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ut=Y.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&It!==void 0&&(Ut=Ut[It]),Ut)if(B>=0&&B<=C.width-X&&K>=0&&K<=C.height-$){T.bindFramebuffer(z.FRAMEBUFFER,Ut);const Yt=C.textures[bt],Se=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+bt),!N.textureFormatReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!N.textureTypeReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Kt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.bufferData(z.PIXEL_PACK_BUFFER,St.byteLength,z.STREAM_READ),z.readPixels(B,K,X,$,vt.convert(Se),vt.convert(Ie),0);const di=W!==null?Y.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,di);const Ji=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await O5(z,Ji,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,St),z.deleteBuffer(Kt),z.deleteSync(Ji),St}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(C,B=null,K=0){const X=Math.pow(2,-K),$=Math.floor(C.image.width*X),St=Math.floor(C.image.height*X),It=B!==null?B.x:0,bt=B!==null?B.y:0;J.setTexture2D(C,0),z.copyTexSubImage2D(z.TEXTURE_2D,K,0,0,It,bt,$,St),T.unbindTexture()},this.copyTextureToTexture=function(C,B,K=null,X=null,$=0,St=0){let It,bt,Ut,Yt,Se,Ie,Kt,di,Ji;const Wi=C.isCompressedTexture?C.mipmaps[St]:C.image;if(K!==null)It=K.max.x-K.min.x,bt=K.max.y-K.min.y,Ut=K.isBox3?K.max.z-K.min.z:1,Yt=K.min.x,Se=K.min.y,Ie=K.isBox3?K.min.z:0;else{const ji=Math.pow(2,-$);It=Math.floor(Wi.width*ji),bt=Math.floor(Wi.height*ji),C.isDataArrayTexture?Ut=Wi.depth:C.isData3DTexture?Ut=Math.floor(Wi.depth*ji):Ut=1,Yt=0,Se=0,Ie=0}X!==null?(Kt=X.x,di=X.y,Ji=X.z):(Kt=0,di=0,Ji=0);const vi=vt.convert(B.format),$n=vt.convert(B.type);let Tt;B.isData3DTexture?(J.setTexture3D(B,0),Tt=z.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(J.setTexture2DArray(B,0),Tt=z.TEXTURE_2D_ARRAY):(J.setTexture2D(B,0),Tt=z.TEXTURE_2D),T.activeTexture(z.TEXTURE0),T.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,B.flipY),T.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),T.pixelStorei(z.UNPACK_ALIGNMENT,B.unpackAlignment);const Us=T.getParameter(z.UNPACK_ROW_LENGTH),Be=T.getParameter(z.UNPACK_IMAGE_HEIGHT),Qs=T.getParameter(z.UNPACK_SKIP_PIXELS),Ur=T.getParameter(z.UNPACK_SKIP_ROWS),ho=T.getParameter(z.UNPACK_SKIP_IMAGES);T.pixelStorei(z.UNPACK_ROW_LENGTH,Wi.width),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Wi.height),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Yt),T.pixelStorei(z.UNPACK_SKIP_ROWS,Se),T.pixelStorei(z.UNPACK_SKIP_IMAGES,Ie);const rl=C.isDataArrayTexture||C.isData3DTexture,Mi=B.isDataArrayTexture||B.isData3DTexture;if(C.isDepthTexture){const ji=Y.get(C),uo=Y.get(B),bi=Y.get(ji.__renderTarget),fo=Y.get(uo.__renderTarget);T.bindFramebuffer(z.READ_FRAMEBUFFER,bi.__webglFramebuffer),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,fo.__webglFramebuffer);for(let al=0;al<Ut;al++)rl&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(C).__webglTexture,$,Ie+al),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(B).__webglTexture,St,Ji+al)),z.blitFramebuffer(Yt,Se,It,bt,Kt,di,It,bt,z.DEPTH_BUFFER_BIT,z.NEAREST);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if($!==0||C.isRenderTargetTexture||Y.has(C)){const ji=Y.get(C),uo=Y.get(B);T.bindFramebuffer(z.READ_FRAMEBUFFER,L),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,P);for(let bi=0;bi<Ut;bi++)rl?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,ji.__webglTexture,$,Ie+bi):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,ji.__webglTexture,$),Mi?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,uo.__webglTexture,St,Ji+bi):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,uo.__webglTexture,St),$!==0?z.blitFramebuffer(Yt,Se,It,bt,Kt,di,It,bt,z.COLOR_BUFFER_BIT,z.NEAREST):Mi?z.copyTexSubImage3D(Tt,St,Kt,di,Ji+bi,Yt,Se,It,bt):z.copyTexSubImage2D(Tt,St,Kt,di,Yt,Se,It,bt);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else Mi?C.isDataTexture||C.isData3DTexture?z.texSubImage3D(Tt,St,Kt,di,Ji,It,bt,Ut,vi,$n,Wi.data):B.isCompressedArrayTexture?z.compressedTexSubImage3D(Tt,St,Kt,di,Ji,It,bt,Ut,vi,Wi.data):z.texSubImage3D(Tt,St,Kt,di,Ji,It,bt,Ut,vi,$n,Wi):C.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,St,Kt,di,It,bt,vi,$n,Wi.data):C.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,St,Kt,di,Wi.width,Wi.height,vi,Wi.data):z.texSubImage2D(z.TEXTURE_2D,St,Kt,di,It,bt,vi,$n,Wi);T.pixelStorei(z.UNPACK_ROW_LENGTH,Us),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Be),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Qs),T.pixelStorei(z.UNPACK_SKIP_ROWS,Ur),T.pixelStorei(z.UNPACK_SKIP_IMAGES,ho),St===0&&B.generateMipmaps&&z.generateMipmap(Tt),T.unbindTexture()},this.initRenderTarget=function(C){Y.get(C).__webglFramebuffer===void 0&&J.setupRenderTarget(C)},this.initTexture=function(C){C.isCubeTexture?J.setTextureCube(C,0):C.isData3DTexture?J.setTexture3D(C,0):C.isDataArrayTexture||C.isCompressedArrayTexture?J.setTexture2DArray(C,0):J.setTexture2D(C,0),T.unbindTexture()},this.resetState=function(){k=0,H=0,W=null,T.reset(),At.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return va}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=Fe._getDrawingBufferColorSpace(t),e.unpackColorSpace=Fe._getUnpackColorSpace()}}const FO=`
|
|
6555
|
+
}`;class DO{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new IE(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new Re({vertexShader:RO,fragmentShader:IO,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Mt(new os(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class CO extends oc{constructor(t,e){super();const i=this;let n=null,s=1,r=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,p=null;const m=typeof XRWebGLBinding<"u",g=new DO,v={},M=e.getContextAttributes();let x=null,y=null;const w=[],S=[],E=new tt;let b=null;const A=new Wn;A.viewport=new _e;const _=new Wn;_.viewport=new _e;const I=[A,_],D=new _4;let O=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ct=w[Z];return ct===void 0&&(ct=new Km,w[Z]=ct),ct.getTargetRaySpace()},this.getControllerGrip=function(Z){let ct=w[Z];return ct===void 0&&(ct=new Km,w[Z]=ct),ct.getGripSpace()},this.getHand=function(Z){let ct=w[Z];return ct===void 0&&(ct=new Km,w[Z]=ct),ct.getHandSpace()};function P(Z){const ct=S.indexOf(Z.inputSource);if(ct===-1)return;const ot=w[ct];ot!==void 0&&(ot.update(Z.inputSource,Z.frame,l||r),ot.dispatchEvent({type:Z.type,data:Z.inputSource}))}function k(){n.removeEventListener("select",P),n.removeEventListener("selectstart",P),n.removeEventListener("selectend",P),n.removeEventListener("squeeze",P),n.removeEventListener("squeezestart",P),n.removeEventListener("squeezeend",P),n.removeEventListener("end",k),n.removeEventListener("inputsourceschange",H);for(let Z=0;Z<w.length;Z++){const ct=S[Z];ct!==null&&(S[Z]=null,w[Z].disconnect(ct))}O=null,L=null,g.reset();for(const Z in v)delete v[Z];t.setRenderTarget(x),f=null,d=null,u=null,n=null,y=null,Pt.stop(),i.isPresenting=!1,t.setPixelRatio(b),t.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){s=Z,i.isPresenting===!0&&zt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,i.isPresenting===!0&&zt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(Z){l=Z},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(n,e)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(Z){if(n=Z,n!==null){if(x=t.getRenderTarget(),n.addEventListener("select",P),n.addEventListener("selectstart",P),n.addEventListener("selectend",P),n.addEventListener("squeeze",P),n.addEventListener("squeezestart",P),n.addEventListener("squeezeend",P),n.addEventListener("end",k),n.addEventListener("inputsourceschange",H),M.xrCompatible!==!0&&await e.makeXRCompatible(),b=t.getPixelRatio(),t.getSize(E),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let ot=null,V=null,Nt=null;M.depth&&(Nt=M.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,ot=M.stencil?kc:so,V=M.stencil?zd:dr);const Xt={colorFormat:e.RGBA8,depthFormat:Nt,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Xt),n.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new qe(d.textureWidth,d.textureHeight,{format:qi,type:is,depthTexture:new nc(d.textureWidth,d.textureHeight,V,void 0,void 0,void 0,void 0,void 0,void 0,ot),stencilBuffer:M.stencil,colorSpace:t.outputColorSpace,samples:M.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const ot={antialias:M.antialias,alpha:!0,depth:M.depth,stencil:M.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(n,e,ot),n.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new qe(f.framebufferWidth,f.framebufferHeight,{format:qi,type:is,colorSpace:t.outputColorSpace,stencilBuffer:M.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,r=await n.requestReferenceSpace(a),Pt.setContext(n),Pt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function H(Z){for(let ct=0;ct<Z.removed.length;ct++){const ot=Z.removed[ct],V=S.indexOf(ot);V>=0&&(S[V]=null,w[V].disconnect(ot))}for(let ct=0;ct<Z.added.length;ct++){const ot=Z.added[ct];let V=S.indexOf(ot);if(V===-1){for(let Xt=0;Xt<w.length;Xt++)if(Xt>=S.length){S.push(ot),V=Xt;break}else if(S[Xt]===null){S[Xt]=ot,V=Xt;break}if(V===-1)break}const Nt=w[V];Nt&&Nt.connect(ot)}}const W=new R,Q=new R;function q(Z,ct,ot){W.setFromMatrixPosition(ct.matrixWorld),Q.setFromMatrixPosition(ot.matrixWorld);const V=W.distanceTo(Q),Nt=ct.projectionMatrix.elements,Xt=ot.projectionMatrix.elements,Lt=Nt[14]/(Nt[10]-1),Rt=Nt[14]/(Nt[10]+1),Qt=(Nt[9]+1)/Nt[5],ie=(Nt[9]-1)/Nt[5],ne=(Nt[8]-1)/Nt[0],ei=(Xt[8]+1)/Xt[0],ii=Lt*ne,Hi=Lt*ei,Li=V/(-ne+ei),Gi=Li*-ne;if(ct.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(Gi),Z.translateZ(Li),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Nt[10]===-1)Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse);else{const on=Lt+Li,z=Rt+Li,ws=ii-Gi,ni=Hi+(V-Gi),N=Qt*Rt/z*on,T=ie*Rt/z*on;Z.projectionMatrix.makePerspective(ws,ni,N,T,on,z),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function nt(Z,ct){ct===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ct.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(n===null)return;let ct=Z.near,ot=Z.far;g.texture!==null&&(g.depthNear>0&&(ct=g.depthNear),g.depthFar>0&&(ot=g.depthFar)),D.near=_.near=A.near=ct,D.far=_.far=A.far=ot,(O!==D.near||L!==D.far)&&(n.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,L=D.far),D.layers.mask=Z.layers.mask|6,A.layers.mask=D.layers.mask&-5,_.layers.mask=D.layers.mask&-3;const V=Z.parent,Nt=D.cameras;nt(D,V);for(let Xt=0;Xt<Nt.length;Xt++)nt(Nt[Xt],V);Nt.length===2?q(D,A,_):D.projectionMatrix.copy(A.projectionMatrix),at(Z,D,V)};function at(Z,ct,ot){ot===null?Z.matrix.copy(ct.matrixWorld):(Z.matrix.copy(ot.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ct.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=Zh*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(Z){c=Z,d!==null&&(d.fixedFoveation=Z),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Z)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(D)},this.getCameraTexture=function(Z){return v[Z]};let Bt=null;function Zt(Z,ct){if(h=ct.getViewerPose(l||r),p=ct,h!==null){const ot=h.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let V=!1;ot.length!==D.cameras.length&&(D.cameras.length=0,V=!0);for(let Rt=0;Rt<ot.length;Rt++){const Qt=ot[Rt];let ie=null;if(f!==null)ie=f.getViewport(Qt);else{const ei=u.getViewSubImage(d,Qt);ie=ei.viewport,Rt===0&&(t.setRenderTargetTextures(y,ei.colorTexture,ei.depthStencilTexture),t.setRenderTarget(y))}let ne=I[Rt];ne===void 0&&(ne=new Wn,ne.layers.enable(Rt),ne.viewport=new _e,I[Rt]=ne),ne.matrix.fromArray(Qt.transform.matrix),ne.matrix.decompose(ne.position,ne.quaternion,ne.scale),ne.projectionMatrix.fromArray(Qt.projectionMatrix),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert(),ne.viewport.set(ie.x,ie.y,ie.width,ie.height),Rt===0&&(D.matrix.copy(ne.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),V===!0&&D.cameras.push(ne)}const Nt=n.enabledFeatures;if(Nt&&Nt.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&m){u=i.getBinding();const Rt=u.getDepthInformation(ot[0]);Rt&&Rt.isValid&&Rt.texture&&g.init(Rt,n.renderState)}if(Nt&&Nt.includes("camera-access")&&m){t.state.unbindTexture(),u=i.getBinding();for(let Rt=0;Rt<ot.length;Rt++){const Qt=ot[Rt].camera;if(Qt){let ie=v[Qt];ie||(ie=new IE,v[Qt]=ie);const ne=u.getCameraImage(Qt);ie.sourceTexture=ne}}}}for(let ot=0;ot<w.length;ot++){const V=S[ot],Nt=w[ot];V!==null&&Nt!==void 0&&Nt.update(V,ct,l||r)}Bt&&Bt(Z,ct),ct.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ct}),p=null}const Pt=new $E;Pt.setAnimationLoop(Zt),this.setAnimationLoop=function(Z){Bt=Z},this.dispose=function(){}}}const OO=new Wt,jE=new ue;jE.set(-1,0,0,0,1,0,0,0,1);function PO(o,t){function e(g,v){g.matrixAutoUpdate===!0&&g.updateMatrix(),v.value.copy(g.matrix)}function i(g,v){v.color.getRGB(g.fogColor.value,FE(o)),v.isFog?(g.fogNear.value=v.near,g.fogFar.value=v.far):v.isFogExp2&&(g.fogDensity.value=v.density)}function n(g,v,M,x,y){v.isNodeMaterial?v.uniformsNeedUpdate=!1:v.isMeshBasicMaterial?s(g,v):v.isMeshLambertMaterial?(s(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshToonMaterial?(s(g,v),u(g,v)):v.isMeshPhongMaterial?(s(g,v),h(g,v),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)):v.isMeshStandardMaterial?(s(g,v),d(g,v),v.isMeshPhysicalMaterial&&f(g,v,y)):v.isMeshMatcapMaterial?(s(g,v),p(g,v)):v.isMeshDepthMaterial?s(g,v):v.isMeshDistanceMaterial?(s(g,v),m(g,v)):v.isMeshNormalMaterial?s(g,v):v.isLineBasicMaterial?(r(g,v),v.isLineDashedMaterial&&a(g,v)):v.isPointsMaterial?c(g,v,M,x):v.isSpriteMaterial?l(g,v):v.isShadowMaterial?(g.color.value.copy(v.color),g.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function s(g,v){g.opacity.value=v.opacity,v.color&&g.diffuse.value.copy(v.color),v.emissive&&g.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.bumpMap&&(g.bumpMap.value=v.bumpMap,e(v.bumpMap,g.bumpMapTransform),g.bumpScale.value=v.bumpScale,v.side===Oi&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,e(v.normalMap,g.normalMapTransform),g.normalScale.value.copy(v.normalScale),v.side===Oi&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,e(v.displacementMap,g.displacementMapTransform),g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap,e(v.emissiveMap,g.emissiveMapTransform)),v.specularMap&&(g.specularMap.value=v.specularMap,e(v.specularMap,g.specularMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);const M=t.get(v),x=M.envMap,y=M.envMapRotation;x&&(g.envMap.value=x,g.envMapRotation.value.setFromMatrix4(OO.makeRotationFromEuler(y)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(jE),g.reflectivity.value=v.reflectivity,g.ior.value=v.ior,g.refractionRatio.value=v.refractionRatio),v.lightMap&&(g.lightMap.value=v.lightMap,g.lightMapIntensity.value=v.lightMapIntensity,e(v.lightMap,g.lightMapTransform)),v.aoMap&&(g.aoMap.value=v.aoMap,g.aoMapIntensity.value=v.aoMapIntensity,e(v.aoMap,g.aoMapTransform))}function r(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform))}function a(g,v){g.dashSize.value=v.dashSize,g.totalSize.value=v.dashSize+v.gapSize,g.scale.value=v.scale}function c(g,v,M,x){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.size.value=v.size*M,g.scale.value=x*.5,v.map&&(g.map.value=v.map,e(v.map,g.uvTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function l(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.rotation.value=v.rotation,v.map&&(g.map.value=v.map,e(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,e(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function h(g,v){g.specular.value.copy(v.specular),g.shininess.value=Math.max(v.shininess,1e-4)}function u(g,v){v.gradientMap&&(g.gradientMap.value=v.gradientMap)}function d(g,v){g.metalness.value=v.metalness,v.metalnessMap&&(g.metalnessMap.value=v.metalnessMap,e(v.metalnessMap,g.metalnessMapTransform)),g.roughness.value=v.roughness,v.roughnessMap&&(g.roughnessMap.value=v.roughnessMap,e(v.roughnessMap,g.roughnessMapTransform)),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)}function f(g,v,M){g.ior.value=v.ior,v.sheen>0&&(g.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),g.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(g.sheenColorMap.value=v.sheenColorMap,e(v.sheenColorMap,g.sheenColorMapTransform)),v.sheenRoughnessMap&&(g.sheenRoughnessMap.value=v.sheenRoughnessMap,e(v.sheenRoughnessMap,g.sheenRoughnessMapTransform))),v.clearcoat>0&&(g.clearcoat.value=v.clearcoat,g.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(g.clearcoatMap.value=v.clearcoatMap,e(v.clearcoatMap,g.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,e(v.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(g.clearcoatNormalMap.value=v.clearcoatNormalMap,e(v.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Oi&&g.clearcoatNormalScale.value.negate())),v.dispersion>0&&(g.dispersion.value=v.dispersion),v.iridescence>0&&(g.iridescence.value=v.iridescence,g.iridescenceIOR.value=v.iridescenceIOR,g.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(g.iridescenceMap.value=v.iridescenceMap,e(v.iridescenceMap,g.iridescenceMapTransform)),v.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=v.iridescenceThicknessMap,e(v.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),v.transmission>0&&(g.transmission.value=v.transmission,g.transmissionSamplerMap.value=M.texture,g.transmissionSamplerSize.value.set(M.width,M.height),v.transmissionMap&&(g.transmissionMap.value=v.transmissionMap,e(v.transmissionMap,g.transmissionMapTransform)),g.thickness.value=v.thickness,v.thicknessMap&&(g.thicknessMap.value=v.thicknessMap,e(v.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=v.attenuationDistance,g.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(g.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(g.anisotropyMap.value=v.anisotropyMap,e(v.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=v.specularIntensity,g.specularColor.value.copy(v.specularColor),v.specularColorMap&&(g.specularColorMap.value=v.specularColorMap,e(v.specularColorMap,g.specularColorMapTransform)),v.specularIntensityMap&&(g.specularIntensityMap.value=v.specularIntensityMap,e(v.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,v){v.matcap&&(g.matcap.value=v.matcap)}function m(g,v){const M=t.get(v).light;g.referencePosition.value.setFromMatrixPosition(M.matrixWorld),g.nearDistance.value=M.shadow.camera.near,g.farDistance.value=M.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function NO(o,t,e,i){let n={},s={},r=[];const a=o.getParameter(o.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,w){const S=w.program;i.uniformBlockBinding(y,S)}function l(y,w){let S=n[y.id];S===void 0&&(g(y),S=h(y),n[y.id]=S,y.addEventListener("dispose",M));const E=w.program;i.updateUBOMapping(y,E);const b=t.render.frame;s[y.id]!==b&&(d(y),s[y.id]=b)}function h(y){const w=u();y.__bindingPointIndex=w;const S=o.createBuffer(),E=y.__size,b=y.usage;return o.bindBuffer(o.UNIFORM_BUFFER,S),o.bufferData(o.UNIFORM_BUFFER,E,b),o.bindBuffer(o.UNIFORM_BUFFER,null),o.bindBufferBase(o.UNIFORM_BUFFER,w,S),S}function u(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ce("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const w=n[y.id],S=y.uniforms,E=y.__cache;o.bindBuffer(o.UNIFORM_BUFFER,w);for(let b=0,A=S.length;b<A;b++){const _=S[b];if(Array.isArray(_))for(let I=0,D=_.length;I<D;I++)f(_[I],b,I,E);else f(_,b,0,E)}o.bindBuffer(o.UNIFORM_BUFFER,null)}function f(y,w,S,E){if(m(y,w,S,E)===!0){const b=y.__offset,A=y.value;if(Array.isArray(A)){let _=0;for(let I=0;I<A.length;I++){const D=A[I],O=v(D);p(D,y.__data,_),typeof D!="number"&&typeof D!="boolean"&&!D.isMatrix3&&!ArrayBuffer.isView(D)&&(_+=O.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);o.bufferSubData(o.UNIFORM_BUFFER,b,y.__data)}}function p(y,w,S){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,S)}function m(y,w,S,E){const b=y.value,A=w+"_"+S;if(E[A]===void 0)return typeof b=="number"||typeof b=="boolean"?E[A]=b:ArrayBuffer.isView(b)?E[A]=b.slice():E[A]=b.clone(),!0;{const _=E[A];if(typeof b=="number"||typeof b=="boolean"){if(_!==b)return E[A]=b,!0}else{if(ArrayBuffer.isView(b))return!0;if(_.equals(b)===!1)return _.copy(b),!0}}return!1}function g(y){const w=y.uniforms;let S=0;const E=16;for(let A=0,_=w.length;A<_;A++){const I=Array.isArray(w[A])?w[A]:[w[A]];for(let D=0,O=I.length;D<O;D++){const L=I[D],P=Array.isArray(L.value)?L.value:[L.value];for(let k=0,H=P.length;k<H;k++){const W=P[k],Q=v(W),q=S%E,nt=q%Q.boundary,at=q+nt;S+=nt,at!==0&&E-at<Q.storage&&(S+=E-at),L.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=S,S+=Q.storage}}}const b=S%E;return b>0&&(S+=E-b),y.__size=S,y.__cache={},this}function v(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?zt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):zt("WebGLRenderer: Unsupported uniform value type.",y),w}function M(y){const w=y.target;w.removeEventListener("dispose",M);const S=r.indexOf(w.__bindingPointIndex);r.splice(S,1),o.deleteBuffer(n[w.id]),delete n[w.id],delete s[w.id]}function x(){for(const y in n)o.deleteBuffer(n[y]);r=[],n={},s={}}return{bind:c,update:l,dispose:x}}const LO=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Br=null;function kO(){return Br===null&&(Br=new ys(LO,16,16,Qc,We),Br.name="DFG_LUT",Br.minFilter=ge,Br.magFilter=ge,Br.wrapS=Ki,Br.wrapT=Ki,Br.generateMipmaps=!1,Br.needsUpdate=!0),Br}class UO{constructor(t={}){const{canvas:e=C5(),context:i=null,depth:n=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=is}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=r;const m=f,g=new Set([IM,RM,TM]),v=new Set([is,dr,Fd,zd,AM,_M]),M=new Uint32Array(4),x=new Int32Array(4),y=new R;let w=null,S=null;const E=[],b=[];let A=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=xa,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let I=!1,D=null,O=null,L=null,P=null;this._outputColorSpace=Nn;let k=0,H=0,W=null,Q=-1,q=null;const nt=new _e,at=new _e;let Bt=null;const Zt=new rt(0);let Pt=0,Z=e.width,ct=e.height,ot=1,V=null,Nt=null;const Xt=new _e(0,0,Z,ct),Lt=new _e(0,0,Z,ct);let Rt=!1;const Qt=new nm;let ie=!1,ne=!1;const ei=new Wt,ii=new R,Hi=new _e,Li={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Gi=!1;function on(){return W===null?ot:1}let z=i;function ws(C,B){return e.getContext(C,B)}try{const C={alpha:!0,depth:n,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${tf}`),e.addEventListener("webglcontextlost",Vi,!1),e.addEventListener("webglcontextrestored",wi,!1),e.addEventListener("webglcontextcreationerror",Lr,!1),z===null){const B="webgl2";if(z=ws(B,C),z===null)throw ws(B)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(C){throw ce("WebGLRenderer: "+C.message),C}let ni,N,T,G,Y,J,ht,ft,j,it,mt,$t,xt,gt,Jt,se,be,F,dt,et,vt,At,st;function Vt(){ni=new kC(z),ni.init(),vt=new TO(z,ni),N=new RC(z,ni,t,vt),T=new AO(z,ni),N.reversedDepthBuffer&&d&&T.buffers.depth.setReversed(!0),O=z.createFramebuffer(),L=z.createFramebuffer(),P=z.createFramebuffer(),G=new zC(z),Y=new uO,J=new _O(z,ni,T,Y,N,vt,G),ht=new LC(_),ft=new V4(z),At=new _C(z,ft),j=new UC(z,ft,G,At),it=new HC(z,j,ft,At,G),F=new BC(z,N,J),Jt=new IC(Y),mt=new hO(_,ht,ni,N,At,Jt),$t=new PO(_,Y),xt=new fO,gt=new yO(ni),be=new AC(_,ht,T,it,p,c),se=new EO(_,it,N),st=new NO(z,G,N,T),dt=new TC(z,ni,G),et=new FC(z,ni,G),G.programs=mt.programs,_.capabilities=N,_.extensions=ni,_.properties=Y,_.renderLists=xt,_.shadowMap=se,_.state=T,_.info=G}Vt(),m!==is&&(A=new VC(m,e.width,e.height,a,n,s));const kt=new CO(_,z);this.xr=kt,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const C=ni.get("WEBGL_lose_context");C&&C.loseContext()},this.forceContextRestore=function(){const C=ni.get("WEBGL_lose_context");C&&C.restoreContext()},this.getPixelRatio=function(){return ot},this.setPixelRatio=function(C){C!==void 0&&(ot=C,this.setSize(Z,ct,!1))},this.getSize=function(C){return C.set(Z,ct)},this.setSize=function(C,B,K=!0){if(kt.isPresenting){zt("WebGLRenderer: Can't change size while VR device is presenting.");return}Z=C,ct=B,e.width=Math.floor(C*ot),e.height=Math.floor(B*ot),K===!0&&(e.style.width=C+"px",e.style.height=B+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,C,B)},this.getDrawingBufferSize=function(C){return C.set(Z*ot,ct*ot).floor()},this.setDrawingBufferSize=function(C,B,K){Z=C,ct=B,ot=K,e.width=Math.floor(C*K),e.height=Math.floor(B*K),this.setViewport(0,0,C,B)},this.setEffects=function(C){if(m===is){ce("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(C){for(let B=0;B<C.length;B++)if(C[B].isOutputPass===!0){zt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(C||[])},this.getCurrentViewport=function(C){return C.copy(nt)},this.getViewport=function(C){return C.copy(Xt)},this.setViewport=function(C,B,K,X){C.isVector4?Xt.set(C.x,C.y,C.z,C.w):Xt.set(C,B,K,X),T.viewport(nt.copy(Xt).multiplyScalar(ot).round())},this.getScissor=function(C){return C.copy(Lt)},this.setScissor=function(C,B,K,X){C.isVector4?Lt.set(C.x,C.y,C.z,C.w):Lt.set(C,B,K,X),T.scissor(at.copy(Lt).multiplyScalar(ot).round())},this.getScissorTest=function(){return Rt},this.setScissorTest=function(C){T.setScissorTest(Rt=C)},this.setOpaqueSort=function(C){V=C},this.setTransparentSort=function(C){Nt=C},this.getClearColor=function(C){return C.copy(be.getClearColor())},this.setClearColor=function(){be.setClearColor(...arguments)},this.getClearAlpha=function(){return be.getClearAlpha()},this.setClearAlpha=function(){be.setClearAlpha(...arguments)},this.clear=function(C=!0,B=!0,K=!0){let X=0;if(C){let $=!1;if(W!==null){const St=W.texture.format;$=g.has(St)}if($){const St=W.texture.type,It=v.has(St),bt=be.getClearColor(),Ut=be.getClearAlpha(),Yt=bt.r,Se=bt.g,Ie=bt.b;It?(M[0]=Yt,M[1]=Se,M[2]=Ie,M[3]=Ut,z.clearBufferuiv(z.COLOR,0,M)):(x[0]=Yt,x[1]=Se,x[2]=Ie,x[3]=Ut,z.clearBufferiv(z.COLOR,0,x))}else X|=z.COLOR_BUFFER_BIT}B&&(X|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),K&&(X|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),X!==0&&z.clear(X)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(C){C.setRenderer(this),D=C},this.dispose=function(){e.removeEventListener("webglcontextlost",Vi,!1),e.removeEventListener("webglcontextrestored",wi,!1),e.removeEventListener("webglcontextcreationerror",Lr,!1),be.dispose(),xt.dispose(),gt.dispose(),Y.dispose(),ht.dispose(),it.dispose(),At.dispose(),st.dispose(),mt.dispose(),kt.dispose(),kt.removeEventListener("sessionstart",xy),kt.removeEventListener("sessionend",wy),lc.stop()};function Vi(C){C.preventDefault(),xp("WebGLRenderer: Context Lost."),I=!0}function wi(){xp("WebGLRenderer: Context Restored."),I=!1;const C=G.autoReset,B=se.enabled,K=se.autoUpdate,X=se.needsUpdate,$=se.type;Vt(),G.autoReset=C,se.enabled=B,se.autoUpdate=K,se.needsUpdate=X,se.type=$}function Lr(C){ce("WebGLRenderer: A WebGL context could not be created. Reason: ",C.statusMessage)}function kr(C){const B=C.target;B.removeEventListener("dispose",kr),n3(B)}function n3(C){s3(C),Y.remove(C)}function s3(C){const B=Y.get(C).programs;B!==void 0&&(B.forEach(function(K){mt.releaseProgram(K)}),C.isShaderMaterial&&mt.releaseShaderCache(C))}this.renderBufferDirect=function(C,B,K,X,$,St){B===null&&(B=Li);const It=$.isMesh&&$.matrixWorld.determinantAffine()<0,bt=o3(C,B,K,X,$);T.setMaterial(X,It);let Ut=K.index,Yt=1;if(X.wireframe===!0){if(Ut=j.getWireframeAttribute(K),Ut===void 0)return;Yt=2}const Se=K.drawRange,Ie=K.attributes.position;let Kt=Se.start*Yt,di=(Se.start+Se.count)*Yt;St!==null&&(Kt=Math.max(Kt,St.start*Yt),di=Math.min(di,(St.start+St.count)*Yt)),Ut!==null?(Kt=Math.max(Kt,0),di=Math.min(di,Ut.count)):Ie!=null&&(Kt=Math.max(Kt,0),di=Math.min(di,Ie.count));const Ji=di-Kt;if(Ji<0||Ji===1/0)return;At.setup($,X,bt,K,Ut);let Wi,vi=dt;if(Ut!==null&&(Wi=ft.get(Ut),vi=et,vi.setIndex(Wi)),$.isMesh)X.wireframe===!0?(T.setLineWidth(X.wireframeLinewidth*on()),vi.setMode(z.LINES)):vi.setMode(z.TRIANGLES);else if($.isLine){let $n=X.linewidth;$n===void 0&&($n=1),T.setLineWidth($n*on()),$.isLineSegments?vi.setMode(z.LINES):$.isLineLoop?vi.setMode(z.LINE_LOOP):vi.setMode(z.LINE_STRIP)}else $.isPoints?vi.setMode(z.POINTS):$.isSprite&&vi.setMode(z.TRIANGLES);if($.isBatchedMesh)if(ni.get("WEBGL_multi_draw"))vi.renderMultiDraw($._multiDrawStarts,$._multiDrawCounts,$._multiDrawCount);else{const $n=$._multiDrawStarts,Tt=$._multiDrawCounts,Us=$._multiDrawCount,He=Ut?ft.get(Ut).bytesPerElement:1,Qs=Y.get(X).currentProgram.getUniforms();for(let Ur=0;Ur<Us;Ur++)Qs.setValue(z,"_gl_DrawID",Ur),vi.render($n[Ur]/He,Tt[Ur])}else if($.isInstancedMesh)vi.renderInstances(Kt,Ji,$.count);else if(K.isInstancedBufferGeometry){const $n=K._maxInstanceCount!==void 0?K._maxInstanceCount:1/0,Tt=Math.min(K.instanceCount,$n);vi.renderInstances(Kt,Ji,Tt)}else vi.render(Kt,Ji)};function yy(C,B,K){C.transparent===!0&&C.side===bn&&C.forceSinglePass===!1?(C.side=Oi,C.needsUpdate=!0,of(C,B,K),C.side=Sa,C.needsUpdate=!0,of(C,B,K),C.side=bn):of(C,B,K)}this.compile=function(C,B,K=null){K===null&&(K=C),S=gt.get(K),S.init(B),b.push(S),K.traverseVisible(function($){$.isLight&&$.layers.test(B.layers)&&(S.pushLight($),$.castShadow&&S.pushShadow($))}),C!==K&&C.traverseVisible(function($){$.isLight&&$.layers.test(B.layers)&&(S.pushLight($),$.castShadow&&S.pushShadow($))}),S.setupLights();const X=new Set;return C.traverse(function($){if(!($.isMesh||$.isPoints||$.isLine||$.isSprite))return;const St=$.material;if(St)if(Array.isArray(St))for(let It=0;It<St.length;It++){const bt=St[It];yy(bt,K,$),X.add(bt)}else yy(St,K,$),X.add(St)}),S=b.pop(),X},this.compileAsync=function(C,B,K=null){const X=this.compile(C,B,K);return new Promise($=>{function St(){if(X.forEach(function(It){Y.get(It).currentProgram.isReady()&&X.delete(It)}),X.size===0){$(C);return}setTimeout(St,10)}ni.get("KHR_parallel_shader_compile")!==null?St():setTimeout(St,10)})};let ym=null;function r3(C){ym&&ym(C)}function xy(){lc.stop()}function wy(){lc.start()}const lc=new $E;lc.setAnimationLoop(r3),typeof self<"u"&&lc.setContext(self),this.setAnimationLoop=function(C){ym=C,kt.setAnimationLoop(C),C===null?lc.stop():lc.start()},kt.addEventListener("sessionstart",xy),kt.addEventListener("sessionend",wy),this.render=function(C,B){if(B!==void 0&&B.isCamera!==!0){ce("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(I===!0)return;D!==null&&D.renderStart(C,B);const K=kt.enabled===!0&&kt.isPresenting===!0,X=A!==null&&(W===null||K)&&A.begin(_,W);if(C.matrixWorldAutoUpdate===!0&&C.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),kt.enabled===!0&&kt.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(kt.cameraAutoUpdate===!0&&kt.updateCamera(B),B=kt.getCamera()),C.isScene===!0&&C.onBeforeRender(_,C,B,W),S=gt.get(C,b.length),S.init(B),S.state.textureUnits=J.getTextureUnits(),b.push(S),ei.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Qt.setFromProjectionMatrix(ei,va,B.reversedDepth),ne=this.localClippingEnabled,ie=Jt.init(this.clippingPlanes,ne),w=xt.get(C,E.length),w.init(),E.push(w),kt.enabled===!0&&kt.isPresenting===!0){const It=_.xr.getDepthSensingMesh();It!==null&&xm(It,B,-1/0,_.sortObjects)}xm(C,B,0,_.sortObjects),w.finish(),_.sortObjects===!0&&w.sort(V,Nt,B.reversedDepth),Gi=kt.enabled===!1||kt.isPresenting===!1||kt.hasDepthSensing()===!1,Gi&&be.addToRenderList(w,C),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ie===!0&&Jt.beginShadows();const $=S.state.shadowsArray;if(se.render($,C,B),ie===!0&&Jt.endShadows(),(X&&A.hasRenderPass())===!1){const It=w.opaque,bt=w.transmissive;if(S.setupLights(),B.isArrayCamera){const Ut=B.cameras;if(bt.length>0)for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Ie=Ut[Yt];Sy(It,bt,C,Ie)}Gi&&be.render(C);for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Ie=Ut[Yt];by(w,C,Ie,Ie.viewport)}}else bt.length>0&&Sy(It,bt,C,B),Gi&&be.render(C),by(w,C,B)}W!==null&&H===0&&(J.updateMultisampleRenderTarget(W),J.updateRenderTargetMipmap(W)),X&&A.end(_),C.isScene===!0&&C.onAfterRender(_,C,B),At.resetDefaultState(),Q=-1,q=null,b.pop(),b.length>0?(S=b[b.length-1],J.setTextureUnits(S.state.textureUnits),ie===!0&&Jt.setGlobalState(_.clippingPlanes,S.state.camera)):S=null,E.pop(),E.length>0?w=E[E.length-1]:w=null,D!==null&&D.renderEnd()};function xm(C,B,K,X){if(C.visible===!1)return;if(C.layers.test(B.layers)){if(C.isGroup)K=C.renderOrder;else if(C.isLOD)C.autoUpdate===!0&&C.update(B);else if(C.isLightProbeGrid)S.pushLightProbeGrid(C);else if(C.isLight)S.pushLight(C),C.castShadow&&S.pushShadow(C);else if(C.isSprite){if(!C.frustumCulled||Qt.intersectsSprite(C)){X&&Hi.setFromMatrixPosition(C.matrixWorld).applyMatrix4(ei);const It=it.update(C),bt=C.material;bt.visible&&w.push(C,It,bt,K,Hi.z,null)}}else if((C.isMesh||C.isLine||C.isPoints)&&(!C.frustumCulled||Qt.intersectsObject(C))){const It=it.update(C),bt=C.material;if(X&&(C.boundingSphere!==void 0?(C.boundingSphere===null&&C.computeBoundingSphere(),Hi.copy(C.boundingSphere.center)):(It.boundingSphere===null&&It.computeBoundingSphere(),Hi.copy(It.boundingSphere.center)),Hi.applyMatrix4(C.matrixWorld).applyMatrix4(ei)),Array.isArray(bt)){const Ut=It.groups;for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Ie=Ut[Yt],Kt=bt[Ie.materialIndex];Kt&&Kt.visible&&w.push(C,It,Kt,K,Hi.z,Ie)}}else bt.visible&&w.push(C,It,bt,K,Hi.z,null)}}const St=C.children;for(let It=0,bt=St.length;It<bt;It++)xm(St[It],B,K,X)}function by(C,B,K,X){const{opaque:$,transmissive:St,transparent:It}=C;S.setupLightsView(K),ie===!0&&Jt.setGlobalState(_.clippingPlanes,K),X&&T.viewport(nt.copy(X)),$.length>0&&af($,B,K),St.length>0&&af(St,B,K),It.length>0&&af(It,B,K),T.buffers.depth.setTest(!0),T.buffers.depth.setMask(!0),T.buffers.color.setMask(!0),T.setPolygonOffset(!1)}function Sy(C,B,K,X){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[X.id]===void 0){const Kt=ni.has("EXT_color_buffer_half_float")||ni.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[X.id]=new qe(1,1,{generateMipmaps:!0,type:Kt?We:is,minFilter:qs,samples:Math.max(4,N.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Fe.workingColorSpace})}const St=S.state.transmissionRenderTarget[X.id],It=X.viewport||nt;St.setSize(It.z*_.transmissionResolutionScale,It.w*_.transmissionResolutionScale);const bt=_.getRenderTarget(),Ut=_.getActiveCubeFace(),Yt=_.getActiveMipmapLevel();_.setRenderTarget(St),_.getClearColor(Zt),Pt=_.getClearAlpha(),Pt<1&&_.setClearColor(16777215,.5),_.clear(),Gi&&be.render(K);const Se=_.toneMapping;_.toneMapping=xa;const Ie=X.viewport;if(X.viewport!==void 0&&(X.viewport=void 0),S.setupLightsView(X),ie===!0&&Jt.setGlobalState(_.clippingPlanes,X),af(C,K,X),J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St),ni.has("WEBGL_multisampled_render_to_texture")===!1){let Kt=!1;for(let di=0,Ji=B.length;di<Ji;di++){const Wi=B[di],{object:vi,geometry:$n,material:Tt,group:Us}=Wi;if(Tt.side===bn&&vi.layers.test(X.layers)){const He=Tt.side;Tt.side=Oi,Tt.needsUpdate=!0,Ey(vi,K,X,$n,Tt,Us),Tt.side=He,Tt.needsUpdate=!0,Kt=!0}}Kt===!0&&(J.updateMultisampleRenderTarget(St),J.updateRenderTargetMipmap(St))}_.setRenderTarget(bt,Ut,Yt),_.setClearColor(Zt,Pt),Ie!==void 0&&(X.viewport=Ie),_.toneMapping=Se}function af(C,B,K){const X=B.isScene===!0?B.overrideMaterial:null;for(let $=0,St=C.length;$<St;$++){const It=C[$],{object:bt,geometry:Ut,group:Yt}=It;let Se=It.material;Se.allowOverride===!0&&X!==null&&(Se=X),bt.layers.test(K.layers)&&Ey(bt,B,K,Ut,Se,Yt)}}function Ey(C,B,K,X,$,St){C.onBeforeRender(_,B,K,X,$,St),C.modelViewMatrix.multiplyMatrices(K.matrixWorldInverse,C.matrixWorld),C.normalMatrix.getNormalMatrix(C.modelViewMatrix),$.onBeforeRender(_,B,K,X,C,St),$.transparent===!0&&$.side===bn&&$.forceSinglePass===!1?($.side=Oi,$.needsUpdate=!0,_.renderBufferDirect(K,B,X,$,C,St),$.side=Sa,$.needsUpdate=!0,_.renderBufferDirect(K,B,X,$,C,St),$.side=bn):_.renderBufferDirect(K,B,X,$,C,St),C.onAfterRender(_,B,K,X,$,St)}function of(C,B,K){B.isScene!==!0&&(B=Li);const X=Y.get(C),$=S.state.lights,St=S.state.shadowsArray,It=$.state.version,bt=mt.getParameters(C,$.state,St,B,K,S.state.lightProbeGridArray),Ut=mt.getProgramCacheKey(bt);let Yt=X.programs;X.environment=C.isMeshStandardMaterial||C.isMeshLambertMaterial||C.isMeshPhongMaterial?B.environment:null,X.fog=B.fog;const Se=C.isMeshStandardMaterial||C.isMeshLambertMaterial&&!C.envMap||C.isMeshPhongMaterial&&!C.envMap;X.envMap=ht.get(C.envMap||X.environment,Se),X.envMapRotation=X.environment!==null&&C.envMap===null?B.environmentRotation:C.envMapRotation,Yt===void 0&&(C.addEventListener("dispose",kr),Yt=new Map,X.programs=Yt);let Ie=Yt.get(Ut);if(Ie!==void 0){if(X.currentProgram===Ie&&X.lightsStateVersion===It)return _y(C,bt),Ie}else bt.uniforms=mt.getUniforms(C),D!==null&&C.isNodeMaterial&&D.build(C,K,bt),C.onBeforeCompile(bt,_),Ie=mt.acquireProgram(bt,Ut),Yt.set(Ut,Ie),X.uniforms=bt.uniforms;const Kt=X.uniforms;return(!C.isShaderMaterial&&!C.isRawShaderMaterial||C.clipping===!0)&&(Kt.clippingPlanes=Jt.uniform),_y(C,bt),X.needsLights=l3(C),X.lightsStateVersion=It,X.needsLights&&(Kt.ambientLightColor.value=$.state.ambient,Kt.lightProbe.value=$.state.probe,Kt.directionalLights.value=$.state.directional,Kt.directionalLightShadows.value=$.state.directionalShadow,Kt.spotLights.value=$.state.spot,Kt.spotLightShadows.value=$.state.spotShadow,Kt.rectAreaLights.value=$.state.rectArea,Kt.ltc_1.value=$.state.rectAreaLTC1,Kt.ltc_2.value=$.state.rectAreaLTC2,Kt.pointLights.value=$.state.point,Kt.pointLightShadows.value=$.state.pointShadow,Kt.hemisphereLights.value=$.state.hemi,Kt.directionalShadowMatrix.value=$.state.directionalShadowMatrix,Kt.spotLightMatrix.value=$.state.spotLightMatrix,Kt.spotLightMap.value=$.state.spotLightMap,Kt.pointShadowMatrix.value=$.state.pointShadowMatrix),X.lightProbeGrid=S.state.lightProbeGridArray.length>0,X.currentProgram=Ie,X.uniformsList=null,Ie}function Ay(C){if(C.uniformsList===null){const B=C.currentProgram.getUniforms();C.uniformsList=W0.seqWithValue(B.seq,C.uniforms)}return C.uniformsList}function _y(C,B){const K=Y.get(C);K.outputColorSpace=B.outputColorSpace,K.batching=B.batching,K.batchingColor=B.batchingColor,K.instancing=B.instancing,K.instancingColor=B.instancingColor,K.instancingMorph=B.instancingMorph,K.skinning=B.skinning,K.morphTargets=B.morphTargets,K.morphNormals=B.morphNormals,K.morphColors=B.morphColors,K.morphTargetsCount=B.morphTargetsCount,K.numClippingPlanes=B.numClippingPlanes,K.numIntersection=B.numClipIntersection,K.vertexAlphas=B.vertexAlphas,K.vertexTangents=B.vertexTangents,K.toneMapping=B.toneMapping}function a3(C,B){if(C.length===0)return null;if(C.length===1)return C[0].texture!==null?C[0]:null;y.setFromMatrixPosition(B.matrixWorld);for(let K=0,X=C.length;K<X;K++){const $=C[K];if($.texture!==null&&$.boundingBox.containsPoint(y))return $}return null}function o3(C,B,K,X,$){B.isScene!==!0&&(B=Li),J.resetTextureUnits();const St=B.fog,It=X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial?B.environment:null,bt=W===null?_.outputColorSpace:W.isXRRenderTarget===!0?W.texture.colorSpace:Fe.workingColorSpace,Ut=X.isMeshStandardMaterial||X.isMeshLambertMaterial&&!X.envMap||X.isMeshPhongMaterial&&!X.envMap,Yt=ht.get(X.envMap||It,Ut),Se=X.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,Ie=!!K.attributes.tangent&&(!!X.normalMap||X.anisotropy>0),Kt=!!K.morphAttributes.position,di=!!K.morphAttributes.normal,Ji=!!K.morphAttributes.color;let Wi=xa;X.toneMapped&&(W===null||W.isXRRenderTarget===!0)&&(Wi=_.toneMapping);const vi=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,$n=vi!==void 0?vi.length:0,Tt=Y.get(X),Us=S.state.lights;if(ie===!0&&(ne===!0||C!==q)){const bi=C===q&&X.id===Q;Jt.setState(X,C,bi)}let He=!1;X.version===Tt.__version?(Tt.needsLights&&Tt.lightsStateVersion!==Us.state.version||Tt.outputColorSpace!==bt||$.isBatchedMesh&&Tt.batching===!1||!$.isBatchedMesh&&Tt.batching===!0||$.isBatchedMesh&&Tt.batchingColor===!0&&$.colorTexture===null||$.isBatchedMesh&&Tt.batchingColor===!1&&$.colorTexture!==null||$.isInstancedMesh&&Tt.instancing===!1||!$.isInstancedMesh&&Tt.instancing===!0||$.isSkinnedMesh&&Tt.skinning===!1||!$.isSkinnedMesh&&Tt.skinning===!0||$.isInstancedMesh&&Tt.instancingColor===!0&&$.instanceColor===null||$.isInstancedMesh&&Tt.instancingColor===!1&&$.instanceColor!==null||$.isInstancedMesh&&Tt.instancingMorph===!0&&$.morphTexture===null||$.isInstancedMesh&&Tt.instancingMorph===!1&&$.morphTexture!==null||Tt.envMap!==Yt||X.fog===!0&&Tt.fog!==St||Tt.numClippingPlanes!==void 0&&(Tt.numClippingPlanes!==Jt.numPlanes||Tt.numIntersection!==Jt.numIntersection)||Tt.vertexAlphas!==Se||Tt.vertexTangents!==Ie||Tt.morphTargets!==Kt||Tt.morphNormals!==di||Tt.morphColors!==Ji||Tt.toneMapping!==Wi||Tt.morphTargetsCount!==$n||!!Tt.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(He=!0):(He=!0,Tt.__version=X.version);let Qs=Tt.currentProgram;He===!0&&(Qs=of(X,B,$),D&&X.isNodeMaterial&&D.onUpdateProgram(X,Qs,Tt));let Ur=!1,ho=!1,rl=!1;const Mi=Qs.getUniforms(),ji=Tt.uniforms;if(T.useProgram(Qs.program)&&(Ur=!0,ho=!0,rl=!0),X.id!==Q&&(Q=X.id,ho=!0),Tt.needsLights){const bi=a3(S.state.lightProbeGridArray,$);Tt.lightProbeGrid!==bi&&(Tt.lightProbeGrid=bi,ho=!0)}if(Ur||q!==C){T.buffers.depth.getReversed()&&C.reversedDepth!==!0&&(C._reversedDepth=!0,C.updateProjectionMatrix()),Mi.setValue(z,"projectionMatrix",C.projectionMatrix),Mi.setValue(z,"viewMatrix",C.matrixWorldInverse);const fo=Mi.map.cameraPosition;fo!==void 0&&fo.setValue(z,ii.setFromMatrixPosition(C.matrixWorld)),N.logarithmicDepthBuffer&&Mi.setValue(z,"logDepthBufFC",2/(Math.log(C.far+1)/Math.LN2)),(X.isMeshPhongMaterial||X.isMeshToonMaterial||X.isMeshLambertMaterial||X.isMeshBasicMaterial||X.isMeshStandardMaterial||X.isShaderMaterial)&&Mi.setValue(z,"isOrthographic",C.isOrthographicCamera===!0),q!==C&&(q=C,ho=!0,rl=!0)}if(Tt.needsLights&&(Us.state.directionalShadowMap.length>0&&Mi.setValue(z,"directionalShadowMap",Us.state.directionalShadowMap,J),Us.state.spotShadowMap.length>0&&Mi.setValue(z,"spotShadowMap",Us.state.spotShadowMap,J),Us.state.pointShadowMap.length>0&&Mi.setValue(z,"pointShadowMap",Us.state.pointShadowMap,J)),$.isSkinnedMesh){Mi.setOptional(z,$,"bindMatrix"),Mi.setOptional(z,$,"bindMatrixInverse");const bi=$.skeleton;bi&&(bi.boneTexture===null&&bi.computeBoneTexture(),Mi.setValue(z,"boneTexture",bi.boneTexture,J))}$.isBatchedMesh&&(Mi.setOptional(z,$,"batchingTexture"),Mi.setValue(z,"batchingTexture",$._matricesTexture,J),Mi.setOptional(z,$,"batchingIdTexture"),Mi.setValue(z,"batchingIdTexture",$._indirectTexture,J),Mi.setOptional(z,$,"batchingColorTexture"),$._colorsTexture!==null&&Mi.setValue(z,"batchingColorTexture",$._colorsTexture,J));const uo=K.morphAttributes;if((uo.position!==void 0||uo.normal!==void 0||uo.color!==void 0)&&F.update($,K,Qs),(ho||Tt.receiveShadow!==$.receiveShadow)&&(Tt.receiveShadow=$.receiveShadow,Mi.setValue(z,"receiveShadow",$.receiveShadow)),(X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial)&&X.envMap===null&&B.environment!==null&&(ji.envMapIntensity.value=B.environmentIntensity),ji.dfgLUT!==void 0&&(ji.dfgLUT.value=kO()),ho){if(Mi.setValue(z,"toneMappingExposure",_.toneMappingExposure),Tt.needsLights&&c3(ji,rl),St&&X.fog===!0&&$t.refreshFogUniforms(ji,St),$t.refreshMaterialUniforms(ji,X,ot,ct,S.state.transmissionRenderTarget[C.id]),Tt.needsLights&&Tt.lightProbeGrid){const bi=Tt.lightProbeGrid;ji.probesSH.value=bi.texture,ji.probesMin.value.copy(bi.boundingBox.min),ji.probesMax.value.copy(bi.boundingBox.max),ji.probesResolution.value.copy(bi.resolution)}W0.upload(z,Ay(Tt),ji,J)}if(X.isShaderMaterial&&X.uniformsNeedUpdate===!0&&(W0.upload(z,Ay(Tt),ji,J),X.uniformsNeedUpdate=!1),X.isSpriteMaterial&&Mi.setValue(z,"center",$.center),Mi.setValue(z,"modelViewMatrix",$.modelViewMatrix),Mi.setValue(z,"normalMatrix",$.normalMatrix),Mi.setValue(z,"modelMatrix",$.matrixWorld),X.uniformsGroups!==void 0){const bi=X.uniformsGroups;for(let fo=0,al=bi.length;fo<al;fo++){const Ty=bi[fo];st.update(Ty,Qs),st.bind(Ty,Qs)}}return Qs}function c3(C,B){C.ambientLightColor.needsUpdate=B,C.lightProbe.needsUpdate=B,C.directionalLights.needsUpdate=B,C.directionalLightShadows.needsUpdate=B,C.pointLights.needsUpdate=B,C.pointLightShadows.needsUpdate=B,C.spotLights.needsUpdate=B,C.spotLightShadows.needsUpdate=B,C.rectAreaLights.needsUpdate=B,C.hemisphereLights.needsUpdate=B}function l3(C){return C.isMeshLambertMaterial||C.isMeshToonMaterial||C.isMeshPhongMaterial||C.isMeshStandardMaterial||C.isShadowMaterial||C.isShaderMaterial&&C.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return H},this.getRenderTarget=function(){return W},this.setRenderTargetTextures=function(C,B,K){const X=Y.get(C);X.__autoAllocateDepthBuffer=C.resolveDepthBuffer===!1,X.__autoAllocateDepthBuffer===!1&&(X.__useRenderToTexture=!1),Y.get(C.texture).__webglTexture=B,Y.get(C.depthTexture).__webglTexture=X.__autoAllocateDepthBuffer?void 0:K,X.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(C,B){const K=Y.get(C);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0},this.setRenderTarget=function(C,B=0,K=0){W=C,k=B,H=K;let X=null,$=!1,St=!1;if(C){const bt=Y.get(C);if(bt.__useDefaultFramebuffer!==void 0){T.bindFramebuffer(z.FRAMEBUFFER,bt.__webglFramebuffer),nt.copy(C.viewport),at.copy(C.scissor),Bt=C.scissorTest,T.viewport(nt),T.scissor(at),T.setScissorTest(Bt),Q=-1;return}else if(bt.__webglFramebuffer===void 0)J.setupRenderTarget(C);else if(bt.__hasExternalTextures)J.rebindTextures(C,Y.get(C.texture).__webglTexture,Y.get(C.depthTexture).__webglTexture);else if(C.depthBuffer){const Se=C.depthTexture;if(bt.__boundDepthTexture!==Se){if(Se!==null&&Y.has(Se)&&(C.width!==Se.image.width||C.height!==Se.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");J.setupDepthRenderbuffer(C)}}const Ut=C.texture;(Ut.isData3DTexture||Ut.isDataArrayTexture||Ut.isCompressedArrayTexture)&&(St=!0);const Yt=Y.get(C).__webglFramebuffer;C.isWebGLCubeRenderTarget?(Array.isArray(Yt[B])?X=Yt[B][K]:X=Yt[B],$=!0):C.samples>0&&J.useMultisampledRTT(C)===!1?X=Y.get(C).__webglMultisampledFramebuffer:Array.isArray(Yt)?X=Yt[K]:X=Yt,nt.copy(C.viewport),at.copy(C.scissor),Bt=C.scissorTest}else nt.copy(Xt).multiplyScalar(ot).floor(),at.copy(Lt).multiplyScalar(ot).floor(),Bt=Rt;if(K!==0&&(X=O),T.bindFramebuffer(z.FRAMEBUFFER,X)&&T.drawBuffers(C,X),T.viewport(nt),T.scissor(at),T.setScissorTest(Bt),$){const bt=Y.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+B,bt.__webglTexture,K)}else if(St){const bt=B;for(let Ut=0;Ut<C.textures.length;Ut++){const Yt=Y.get(C.textures[Ut]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+Ut,Yt.__webglTexture,K,bt)}}else if(C!==null&&K!==0){const bt=Y.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,bt.__webglTexture,K)}Q=-1},this.readRenderTargetPixels=function(C,B,K,X,$,St,It,bt=0){if(!(C&&C.isWebGLRenderTarget)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ut=Y.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&It!==void 0&&(Ut=Ut[It]),Ut){T.bindFramebuffer(z.FRAMEBUFFER,Ut);try{const Yt=C.textures[bt],Se=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+bt),!N.textureFormatReadable(Se)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!N.textureTypeReadable(Ie)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}B>=0&&B<=C.width-X&&K>=0&&K<=C.height-$&&z.readPixels(B,K,X,$,vt.convert(Se),vt.convert(Ie),St)}finally{const Yt=W!==null?Y.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,Yt)}}},this.readRenderTargetPixelsAsync=async function(C,B,K,X,$,St,It,bt=0){if(!(C&&C.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ut=Y.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&It!==void 0&&(Ut=Ut[It]),Ut)if(B>=0&&B<=C.width-X&&K>=0&&K<=C.height-$){T.bindFramebuffer(z.FRAMEBUFFER,Ut);const Yt=C.textures[bt],Se=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+bt),!N.textureFormatReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!N.textureTypeReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Kt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.bufferData(z.PIXEL_PACK_BUFFER,St.byteLength,z.STREAM_READ),z.readPixels(B,K,X,$,vt.convert(Se),vt.convert(Ie),0);const di=W!==null?Y.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,di);const Ji=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await O5(z,Ji,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,St),z.deleteBuffer(Kt),z.deleteSync(Ji),St}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(C,B=null,K=0){const X=Math.pow(2,-K),$=Math.floor(C.image.width*X),St=Math.floor(C.image.height*X),It=B!==null?B.x:0,bt=B!==null?B.y:0;J.setTexture2D(C,0),z.copyTexSubImage2D(z.TEXTURE_2D,K,0,0,It,bt,$,St),T.unbindTexture()},this.copyTextureToTexture=function(C,B,K=null,X=null,$=0,St=0){let It,bt,Ut,Yt,Se,Ie,Kt,di,Ji;const Wi=C.isCompressedTexture?C.mipmaps[St]:C.image;if(K!==null)It=K.max.x-K.min.x,bt=K.max.y-K.min.y,Ut=K.isBox3?K.max.z-K.min.z:1,Yt=K.min.x,Se=K.min.y,Ie=K.isBox3?K.min.z:0;else{const ji=Math.pow(2,-$);It=Math.floor(Wi.width*ji),bt=Math.floor(Wi.height*ji),C.isDataArrayTexture?Ut=Wi.depth:C.isData3DTexture?Ut=Math.floor(Wi.depth*ji):Ut=1,Yt=0,Se=0,Ie=0}X!==null?(Kt=X.x,di=X.y,Ji=X.z):(Kt=0,di=0,Ji=0);const vi=vt.convert(B.format),$n=vt.convert(B.type);let Tt;B.isData3DTexture?(J.setTexture3D(B,0),Tt=z.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(J.setTexture2DArray(B,0),Tt=z.TEXTURE_2D_ARRAY):(J.setTexture2D(B,0),Tt=z.TEXTURE_2D),T.activeTexture(z.TEXTURE0),T.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,B.flipY),T.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),T.pixelStorei(z.UNPACK_ALIGNMENT,B.unpackAlignment);const Us=T.getParameter(z.UNPACK_ROW_LENGTH),He=T.getParameter(z.UNPACK_IMAGE_HEIGHT),Qs=T.getParameter(z.UNPACK_SKIP_PIXELS),Ur=T.getParameter(z.UNPACK_SKIP_ROWS),ho=T.getParameter(z.UNPACK_SKIP_IMAGES);T.pixelStorei(z.UNPACK_ROW_LENGTH,Wi.width),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Wi.height),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Yt),T.pixelStorei(z.UNPACK_SKIP_ROWS,Se),T.pixelStorei(z.UNPACK_SKIP_IMAGES,Ie);const rl=C.isDataArrayTexture||C.isData3DTexture,Mi=B.isDataArrayTexture||B.isData3DTexture;if(C.isDepthTexture){const ji=Y.get(C),uo=Y.get(B),bi=Y.get(ji.__renderTarget),fo=Y.get(uo.__renderTarget);T.bindFramebuffer(z.READ_FRAMEBUFFER,bi.__webglFramebuffer),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,fo.__webglFramebuffer);for(let al=0;al<Ut;al++)rl&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(C).__webglTexture,$,Ie+al),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(B).__webglTexture,St,Ji+al)),z.blitFramebuffer(Yt,Se,It,bt,Kt,di,It,bt,z.DEPTH_BUFFER_BIT,z.NEAREST);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if($!==0||C.isRenderTargetTexture||Y.has(C)){const ji=Y.get(C),uo=Y.get(B);T.bindFramebuffer(z.READ_FRAMEBUFFER,L),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,P);for(let bi=0;bi<Ut;bi++)rl?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,ji.__webglTexture,$,Ie+bi):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,ji.__webglTexture,$),Mi?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,uo.__webglTexture,St,Ji+bi):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,uo.__webglTexture,St),$!==0?z.blitFramebuffer(Yt,Se,It,bt,Kt,di,It,bt,z.COLOR_BUFFER_BIT,z.NEAREST):Mi?z.copyTexSubImage3D(Tt,St,Kt,di,Ji+bi,Yt,Se,It,bt):z.copyTexSubImage2D(Tt,St,Kt,di,Yt,Se,It,bt);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else Mi?C.isDataTexture||C.isData3DTexture?z.texSubImage3D(Tt,St,Kt,di,Ji,It,bt,Ut,vi,$n,Wi.data):B.isCompressedArrayTexture?z.compressedTexSubImage3D(Tt,St,Kt,di,Ji,It,bt,Ut,vi,Wi.data):z.texSubImage3D(Tt,St,Kt,di,Ji,It,bt,Ut,vi,$n,Wi):C.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,St,Kt,di,It,bt,vi,$n,Wi.data):C.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,St,Kt,di,Wi.width,Wi.height,vi,Wi.data):z.texSubImage2D(z.TEXTURE_2D,St,Kt,di,It,bt,vi,$n,Wi);T.pixelStorei(z.UNPACK_ROW_LENGTH,Us),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,He),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Qs),T.pixelStorei(z.UNPACK_SKIP_ROWS,Ur),T.pixelStorei(z.UNPACK_SKIP_IMAGES,ho),St===0&&B.generateMipmaps&&z.generateMipmap(Tt),T.unbindTexture()},this.initRenderTarget=function(C){Y.get(C).__webglFramebuffer===void 0&&J.setupRenderTarget(C)},this.initTexture=function(C){C.isCubeTexture?J.setTextureCube(C,0):C.isData3DTexture?J.setTexture3D(C,0):C.isDataArrayTexture||C.isCompressedArrayTexture?J.setTexture2DArray(C,0):J.setTexture2D(C,0),T.unbindTexture()},this.resetState=function(){k=0,H=0,W=null,T.reset(),At.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return va}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=Fe._getDrawingBufferColorSpace(t),e.unpackColorSpace=Fe._getUnpackColorSpace()}}const FO=`
|
|
6556
6556
|
varying vec3 vDir;
|
|
6557
6557
|
varying vec3 vWorldDir;
|
|
6558
6558
|
|
|
@@ -7565,7 +7565,7 @@ void main() {`).replace(qr.ANCHOR,`float sigma = max(${Gt.MIN_SIGMA_PX.toFixed(2
|
|
|
7565
7565
|
diffuseColor.a *= 1.0 + level * ${Qu.PER_LEVEL.toFixed(2)};
|
|
7566
7566
|
}
|
|
7567
7567
|
#endif
|
|
7568
|
-
${he.alphatest_fragment}`)}}class le{static WIDTH=160;static HEIGHT=90;static BLEACHING_CD_M2_S=22e7;static REGENERATION_S=110;static SPREAD_DEG=.5;static JUMP_MS=2e3;static POSITIVE_FADE_S=1.5;static POSITIVE_GAIN=20;static FLIGHT=[{ageS:0,rgb:[1,1,1]},{ageS:.6,rgb:[.35,1.05,.95]},{ageS:1.4,rgb:[.55,.6,3.6]},{ageS:2.4,rgb:[1.7,.6,1.5]},{ageS:3.5,rgb:[1.9,.75,.25]}];texture;left=new Float32Array(le.WIDTH*le.HEIGHT).fill(1);glow=new Float32Array(le.WIDTH*le.HEIGHT);age=new Float32Array(le.WIDTH*le.HEIGHT);bytes=le.freshBytes();lastMs;bleached=!1;constructor(){this.texture=new ys(this.bytes,le.WIDTH,le.HEIGHT,qi,We),this.texture.minFilter=ge,this.texture.magFilter=ge,this.texture.needsUpdate=!0}get any(){return this.bleached}advance(t,e,i){const n=this.lastMs===void 0?1/0:t-this.lastMs;if(this.lastMs=t,n===0)return!1;const s=le.SPREAD_DEG*Math.PI/180,r=e.map(u=>({x:u.ndcX*i.width/2,y:u.ndcY*i.height/2,peak:u.lux/(2*Math.PI*s*s)})).filter(u=>u.peak>=le.FAINTEST_CD_M2);if(n<0||n>le.JUMP_MS)return this.previous=r,this.reset();if(!this.bleached&&e.length===0)return this.previous=void 0,!1;const a=this.previous?.length===r.length?this.previous:void 0,c=a?Math.max(0,...r.map((u,d)=>Math.hypot(u.x-a[d].x,u.y-a[d].y))):0,l=Math.min(le.MAX_STEPS,Math.max(1,Math.ceil(c/(le.SPREAD_DEG/3)))),h=n/1e3/l;for(let u=1;u<=l;u++){const d=u/l;this.bleach(a?r.map((f,p)=>({...f,x:a[p].x+(f.x-a[p].x)*d,y:a[p].y+(f.y-a[p].y)*d})):r,h,i)}return this.previous=r,this.texture.needsUpdate=!0,!0}static FAINTEST_CD_M2=le.BLEACHING_CD_M2_S/le.REGENERATION_S*1e-4;static MAX_STEPS=64;previous;bleach(t,e,i){const n=le.WIDTH,s=le.HEIGHT,r=le.SPREAD_DEG,a=1/le.REGENERATION_S,c=this.light.fill(0);for(const h of t){const u=Math.max(0,Math.floor(((h.x-5*r)/i.width+.5)*n)),d=Math.min(n-1,Math.ceil(((h.x+5*r)/i.width+.5)*n)),f=Math.max(0,Math.floor(((h.y-5*r)/i.height+.5)*s)),p=Math.min(s-1,Math.ceil(((h.y+5*r)/i.height+.5)*s));for(let m=f;m<=p;m++){const g=((m+.5)/s*2-1)*i.height/2;for(let v=u;v<=d;v++){const x=(((v+.5)/n*2-1)*i.width/2-h.x)**2+(g-h.y)**2;x<25*r*r&&(c[m*n+v]+=h.peak*Math.exp(-x/(2*r*r)))}}}let l=!1;for(let h=0;h<s;h++)for(let u=0;u<n;u++){const d=h*n+u,f=c[d],p=this.left[d],m=this.glow[d];if(f===0&&p>=.9995&&m<le.GLOW_SEEN)continue;const g=a+f/le.BLEACHING_CD_M2_S,v=a/g,M=v+(p-v)*Math.exp(-g*e);this.left[d]=M;const x=Math.max(0,p-M)*le.POSITIVE_GAIN,y=m*Math.exp(-e/le.POSITIVE_FADE_S),w=y+x;this.age[d]=w>0?y*(this.age[d]+e)/w:0,this.glow[d]=w;const S=le.flightAt(this.age[d]),E=d*4;this.bytes[E]=kn.toHalfFloat(M);for(let b=0;b<3;b++)this.bytes[E+1+b]=kn.toHalfFloat(w*S[b]);(M<.995||w>=le.GLOW_SEEN)&&(l=!0)}this.bleached=l}light=new Float32Array(le.WIDTH*le.HEIGHT);static GLOW_SEEN=.002;static flightAt(t){const e=le.FLIGHT;for(let i=1;i<e.length;i++){if(t>e[i].ageS)continue;const n=(t-e[i-1].ageS)/(e[i].ageS-e[i-1].ageS),s=e[i-1].rgb,r=e[i].rgb;return[s[0]+(r[0]-s[0])*n,s[1]+(r[1]-s[1])*n,s[2]+(r[2]-s[2])*n]}return e[e.length-1].rgb}static freshBytes(){const t=new Uint16Array(le.WIDTH*le.HEIGHT*4),e=kn.toHalfFloat(1);for(let i=0;i<t.length;i+=4)t[i]=e;return t}leftAt(t,e){const i=Math.min(le.WIDTH-1,Math.max(0,Math.floor((t+1)/2*le.WIDTH))),n=Math.min(le.HEIGHT-1,Math.max(0,Math.floor((e+1)/2*le.HEIGHT)));return this.left[n*le.WIDTH+i]}get atMs(){return this.lastMs}replay(t,e,i,n,s){const r=new Map,a=d=>{let f=r.get(d);return f||r.set(d,f=i(d)),f};s!==this.snapshotsOf&&(this.snapshots.clear(),this.snapshotsOf=s);let c=t;for(const d of this.snapshots.keys())d<=e&&d>c&&(c=d);c>t?this.restore(c):this.reset(),this.previous=void 0,this.lastMs=c;let l=c,h=0;const u=d=>{const f=d%le.REPLAY_STRIDE_MS===0&&a(d).length>0?le.REPLAY_STRIDE_MS:le.SNAPSHOT_MS;d%f!==0||this.snapshots.has(d)||(h>0&&this.rest(h),h=0,this.snapshots.set(d,{left:this.left.slice(),glow:this.glow.slice(),age:this.age.slice(),bleached:this.bleached}))};for(;l<e;){u(l);const d=Math.min(e,(Math.floor(l/le.REPLAY_STRIDE_MS)+1)*le.REPLAY_STRIDE_MS);if(a(d).length===0&&a(l).length===0){h+=d-l,l=d;continue}h>0&&this.rest(h),h=0;const f=Math.min(e,(Math.floor(l/le.REPLAY_STEP_MS)+1)*le.REPLAY_STEP_MS);this.lastMs=l,this.advance(f,a(f),n),l=f}h>0&&this.rest(h),this.lastMs=e}static SNAPSHOT_MS=5e3;snapshots=new Map;snapshotsOf;restore(t){const e=this.snapshots.get(t);this.left.set(e.left),this.glow.set(e.glow),this.age.set(e.age),this.bleached=e.bleached;for(let i=0;i<this.left.length;i++){const n=i*4,s=le.flightAt(this.age[i]);this.bytes[n]=kn.toHalfFloat(this.left[i]);for(let r=0;r<3;r++)this.bytes[n+1+r]=kn.toHalfFloat(this.glow[i]*s[r])}this.texture.needsUpdate=!0}static REPLAY_STEP_MS=100;static REPLAY_STRIDE_MS=1e3;rest(t){this.previous=void 0,this.bleached&&(this.bleach([],t/1e3,{width:1,height:1}),this.texture.needsUpdate=!0)}reset(){return this.bleached?(this.left.fill(1),this.glow.fill(0),this.age.fill(0),this.bytes.set(le.freshBytes()),this.bleached=!1,this.texture.needsUpdate=!0,!0):!1}dispose(){this.texture.dispose()}}class us{constructor(t,e,i=us.NO_SHADOW){this.parent=t,this.sceneUnitsPerLux=e,this.shadow=i}static NEAR=4;static FAR=2;static FAR_DISTANCE=1e3;static SYSTEMS={BodySystem:"emitters: the bodies that glow whole, the named lights of a model (a craft's lights), and their flames",MeteorSystem:"emitters: the heads of meteors, far, from their magnitude",ReentrySystem:"emitters: the heads of re-entries, far, from their magnitude",PhenomenonSystem:"none yet: a phenomenon states no luminance, only a colour as seen and a 0..1 dazzle, which say nothing of the light it gives",BeamSystem:"none: a laser beam is a thread of scattered light, too faint to light the ground; where it ends lit is in the sky",PlumeSystem:"none: a launch plume is lit by the Sun, it gives out no light of its own",CloudSystem:"none: clouds are lit, they do not give out light",LayeredCloudSystem:"none: clouds are lit, they do not give out light",DecorSystem:"own lights: the streetlamps, with shadows for the nearest (SceneRenderer.addStreetlightLight); NOT YET its lesser lamps (traffic lights, a car's rear lights), drawn lit but lighting nothing",RoadSystem:"own lights: the lamps it places along a street are the decor's streetlamps (see DecorSystem)",RailwaySystem:"none: rails mirror the lamps, they give out no light",ContrailSystem:"none: a contrail is lit by the Sun, it gives out no light",WaterSystem:"none: water mirrors, it gives out no light",TraceSystem:"none: a trace on the ground is lit, it gives out no light",ReferenceSystem:"none: a photograph laid over the scene, not in it",MirrorSystem:"none: a mirror shows the scene's light, it gives out none",HeadlightSystem:"own lights: a vehicle's headlamps are spot lights, aimed",FlameEffect:"emitters: through BodySystem, which states each flame",LensFlareEffect:"none: a dazzle in the eye, nothing in the world",IceHaloEffect:"none: sunlight bent by ice, seen, not cast on the ground",RainbowEffect:"none: sunlight bent by drops, seen, not cast on the ground",SkyGlowEffect:"none: the Milky Way and the zodiacal light are in the sky's own light (ScatteredSky)",RainSystem:"none: rain gives out no light",SatelliteField:"none: a satellite is a speck of reflected sunlight, far too faint to light anything"};near;far;nearBy=new Map;farBy=new Map;static NO_SHADOW={halfExtentM:0,depthHalfRangeM:0,biasM:0,normalBiasM:0,mapSize:0};set(t,e,i=[]){this.nearBy.set(t,e.filter(n=>n.candela>0)),this.farBy.set(t,i.filter(n=>Math.max(...n.lux)>0))}cast(t){const e=[...this.nearBy.values()].flat(),i=[...this.farBy.values()].flat(),n=this.sceneUnitsPerLux();if(e.length>0||this.near){this.near??=this.build(us.NEAR,()=>new WE(16777215,0,0,2));const s=a=>t?a.candela/Math.max(a.position.distanceToSquared(t),1e-6):a.candela,r=e.sort((a,c)=>s(c)-s(a));this.near.forEach((a,c)=>{const l=r[c];if(!l){a.intensity=0;return}a.position.copy(l.position);const h=us.luminanceOf(l.colour);a.color.setRGB(l.colour[0]/h,l.colour[1]/h,l.colour[2]/h),a.intensity=l.candela*n})}if(i.length>0||this.far){this.far??=this.buildFar();const s=i.sort((r,a)=>us.luminanceOf(a.lux)-us.luminanceOf(r.lux));this.far.forEach((r,a)=>{const c=s[a];if(r.castShadow&&(r.shadow.autoUpdate=c!==void 0),!c){r.intensity=0;return}r.position.copy(c.direction).multiplyScalar(us.FAR_DISTANCE).add(t??us.ORIGIN),r.target.position.copy(t??us.ORIGIN),r.target.updateMatrixWorld();const l=us.luminanceOf(c.lux);r.color.setRGB(c.lux[0]/l,c.lux[1]/l,c.lux[2]/l),r.intensity=l*n})}}static SKY_LIGHTING_MAGNITUDE=-8;get farEmitters(){return[...this.farBy.values()].flat()}get brightestInSky(){let t;for(const e of[...this.farBy.values()].flat())e.sky.magnitude<(t?.magnitude??us.SKY_LIGHTING_MAGNITUDE)&&(t=e.sky);return t}get all(){return[...this.near??[],...this.far??[]]}buildFar(){const t=this.build(us.FAR,()=>new Ep(16777215,0)),e=this.shadow;if(e.mapSize>0){const i=t[0].shadow;t[0].castShadow=!0,i.mapSize.set(e.mapSize,e.mapSize);const n=i.camera;n.left=-e.halfExtentM,n.right=e.halfExtentM,n.top=e.halfExtentM,n.bottom=-e.halfExtentM,n.near=us.FAR_DISTANCE-e.depthHalfRangeM,n.far=us.FAR_DISTANCE+e.depthHalfRangeM,n.updateProjectionMatrix(),i.bias=-e.biasM/(2*e.depthHalfRangeM),i.normalBias=e.normalBiasM,i.autoUpdate=!1}return t}build(t,e){return Array.from({length:t},()=>{const i=e();return i.name="emitter-light",this.parent.add(i),i instanceof Ep&&this.parent.add(i.target),i})}static luminanceOf(t){return .2126*t[0]+.7152*t[1]+.0722*t[2]||1}static ORIGIN=new R}class br{static MAX_STRENGTH=32;static MID_GREY=.18;static shown(t,e){const i=Math.min(1,Math.max(0,t));return e<.001?i:Math.log(1+e*i)/Math.log(1+e)}static strengthFor(t){if(!(t>0)||t>=br.MID_GREY)return 0;if(br.shown(t,br.MAX_STRENGTH)<=br.MID_GREY)return br.MAX_STRENGTH;let e=0,i=br.MAX_STRENGTH;for(let n=0;n<40;n++){const s=(e+i)/2;br.shown(t,s)<br.MID_GREY?e=s:i=s}return(e+i)/2}}const RN=[{name:"Sirius",raHours:6.7525,decDeg:-16.7161,mag:-1.44},{name:"Canopus",raHours:6.3992,decDeg:-52.6957,mag:-.62},{name:"Arcturus",raHours:14.261,decDeg:19.1824,mag:-.05},{name:"Rigil Kentaurus",raHours:14.6608,decDeg:-60.834,mag:-.01},{name:"Vega",raHours:18.6156,decDeg:38.7837,mag:.03},{name:"Capella",raHours:5.2782,decDeg:45.998,mag:.08},{name:"Rigel",raHours:5.2423,decDeg:-8.2016,mag:.18},{name:"Procyon",raHours:7.655,decDeg:5.225,mag:.4},{name:"Achernar",raHours:1.6286,decDeg:-57.2368,mag:.45},{name:"Betelgeuse",raHours:5.9195,decDeg:7.4071,mag:.45},{name:"Hadar",raHours:14.0637,decDeg:-60.373,mag:.61},{name:"Altair",raHours:19.8464,decDeg:8.8683,mag:.76},{name:"Acrux",raHours:12.4433,decDeg:-63.0991,mag:.77},{name:"Aldebaran",raHours:4.5987,decDeg:16.5093,mag:.87},{name:"Spica",raHours:13.4199,decDeg:-11.1613,mag:.98},{name:"Antares",raHours:16.4901,decDeg:-26.432,mag:1.06},{name:"Pollux",raHours:7.7553,decDeg:28.0262,mag:1.16},{name:"Fomalhaut",raHours:22.9608,decDeg:-29.6222,mag:1.17},{name:"Mimosa",raHours:12.7954,decDeg:-59.6888,mag:1.25},{name:"Deneb",raHours:20.6905,decDeg:45.2803,mag:1.25},{name:"Toliman",raHours:14.6603,decDeg:-60.8383,mag:1.35},{name:"Regulus",raHours:10.1395,decDeg:11.9672,mag:1.36},{name:"Adhara",raHours:6.9771,decDeg:-28.9721,mag:1.5},{name:"Castor",raHours:7.5766,decDeg:31.8883,mag:1.58},{name:"Gacrux",raHours:12.5194,decDeg:-57.1132,mag:1.59},{name:"Shaula",raHours:17.5601,decDeg:-37.1038,mag:1.62},{name:"Bellatrix",raHours:5.4189,decDeg:6.3497,mag:1.64},{name:"Elnath",raHours:5.4382,decDeg:28.6075,mag:1.65},{name:"Miaplacidus",raHours:9.22,decDeg:-69.7172,mag:1.67},{name:"Alnilam",raHours:5.6036,decDeg:-1.2019,mag:1.69},{name:"Alnair",raHours:22.1372,decDeg:-46.961,mag:1.73},{name:"Alnitak",raHours:5.6793,decDeg:-1.9426,mag:1.74},{name:"γ² Velorum",raHours:8.1589,decDeg:-47.3366,mag:1.75},{name:"Alioth",raHours:12.9005,decDeg:55.9598,mag:1.76},{name:"Mirfak",raHours:3.4054,decDeg:49.8612,mag:1.79},{name:"Kaus Australis",raHours:18.4029,decDeg:-34.3846,mag:1.79},{name:"Dubhe",raHours:11.0622,decDeg:61.751,mag:1.81},{name:"Wezen",raHours:7.1399,decDeg:-26.3932,mag:1.83},{name:"Alkaid",raHours:13.7924,decDeg:49.3133,mag:1.85},{name:"Avior",raHours:8.3752,decDeg:-59.5095,mag:1.86},{name:"Sargas",raHours:17.622,decDeg:-42.9978,mag:1.86},{name:"Menkalinan",raHours:5.9921,decDeg:44.9474,mag:1.9},{name:"Atria",raHours:16.8111,decDeg:-69.0277,mag:1.91},{name:"Alhena",raHours:6.6285,decDeg:16.3993,mag:1.93},{name:"Alsephina",raHours:8.7451,decDeg:-54.7088,mag:1.93},{name:"Peacock",raHours:20.4275,decDeg:-56.7351,mag:1.94},{name:"Polaris",raHours:2.5297,decDeg:89.2641,mag:1.97},{name:"Mirzam",raHours:6.3783,decDeg:-17.9559,mag:1.98},{name:"Alphard",raHours:9.4598,decDeg:-8.6586,mag:1.99},{name:"Hamal",raHours:2.1196,decDeg:23.4624,mag:2.01},{name:"Algieba",raHours:10.3329,decDeg:19.8415,mag:2.01},{name:"Diphda",raHours:.7265,decDeg:-17.9866,mag:2.04},{name:"Nunki",raHours:18.9211,decDeg:-26.2967,mag:2.05},{name:"Menkent",raHours:14.1114,decDeg:-36.37,mag:2.06},{name:"Alpheratz",raHours:.1398,decDeg:29.0904,mag:2.07},{name:"Mirach",raHours:1.1622,decDeg:35.6206,mag:2.07},{name:"Saiph",raHours:5.7959,decDeg:-9.6696,mag:2.07},{name:"Kochab",raHours:14.8451,decDeg:74.1555,mag:2.07},{name:"Tiaki",raHours:22.7111,decDeg:-46.8846,mag:2.07},{name:"Rasalhague",raHours:17.5822,decDeg:12.56,mag:2.08},{name:"Algol",raHours:3.1361,decDeg:40.9556,mag:2.09},{name:"Almach",raHours:2.065,decDeg:42.3297,mag:2.1},{name:"Denebola",raHours:11.8177,decDeg:14.5721,mag:2.14},{name:"Cih",raHours:.9451,decDeg:60.7167,mag:2.15},{name:"γ Centauri",raHours:12.692,decDeg:-48.9599,mag:2.2},{name:"Naos",raHours:8.0597,decDeg:-40.0031,mag:2.21},{name:"Aspidiske",raHours:9.2848,decDeg:-59.2752,mag:2.21},{name:"Alphecca",raHours:15.5781,decDeg:26.7147,mag:2.22},{name:"Suhail",raHours:9.1333,decDeg:-43.4326,mag:2.23},{name:"Mizar",raHours:13.3987,decDeg:54.9254,mag:2.23},{name:"Sadr",raHours:20.3705,decDeg:40.2567,mag:2.23},{name:"Schedar",raHours:.6751,decDeg:56.5373,mag:2.24},{name:"Eltanin",raHours:17.9434,decDeg:51.4889,mag:2.24},{name:"Mintaka",raHours:5.5334,decDeg:-.2991,mag:2.25},{name:"Caph",raHours:.1529,decDeg:59.1498,mag:2.28},{name:"ε Centauri",raHours:13.6648,decDeg:-53.4664,mag:2.29},{name:"Dschubba",raHours:16.0056,decDeg:-22.6217,mag:2.29},{name:"Larawag",raHours:16.8361,decDeg:-34.2932,mag:2.29},{name:"α Lupi",raHours:14.6988,decDeg:-47.3882,mag:2.3},{name:"η Centauri",raHours:14.5918,decDeg:-42.1578,mag:2.33},{name:"Merak",raHours:11.0307,decDeg:56.3824,mag:2.34},{name:"Izar",raHours:14.7498,decDeg:27.0742,mag:2.35},{name:"Enif",raHours:21.7364,decDeg:9.875,mag:2.38},{name:"κ Scorpii",raHours:17.7081,decDeg:-39.03,mag:2.39},{name:"Ankaa",raHours:.4381,decDeg:-42.306,mag:2.4},{name:"Phecda",raHours:11.8972,decDeg:53.6948,mag:2.41},{name:"Sabik",raHours:17.173,decDeg:-15.7249,mag:2.43},{name:"Scheat",raHours:23.0629,decDeg:28.0828,mag:2.44},{name:"Aludra",raHours:7.4016,decDeg:-29.3031,mag:2.45},{name:"Alderamin",raHours:21.3096,decDeg:62.5856,mag:2.45},{name:"Markeb",raHours:9.3686,decDeg:-55.0107,mag:2.47},{name:"Aljanah",raHours:20.7702,decDeg:33.9703,mag:2.48},{name:"Markab",raHours:23.0793,decDeg:15.2053,mag:2.49},{name:"Menkar",raHours:3.038,decDeg:4.0897,mag:2.54},{name:"ζ Ophiuchi",raHours:16.6193,decDeg:-10.5671,mag:2.54},{name:"ζ Centauri",raHours:13.9257,decDeg:-47.2884,mag:2.55},{name:"Zosma",raHours:11.2351,decDeg:20.5237,mag:2.56},{name:"Acrab",raHours:16.0906,decDeg:-19.8055,mag:2.56},{name:"Arneb",raHours:5.5455,decDeg:-17.8223,mag:2.58},{name:"δ Centauri",raHours:12.1393,decDeg:-50.7224,mag:2.58},{name:"Gienah",raHours:12.2634,decDeg:-17.5419,mag:2.58},{name:"Ascella",raHours:19.0435,decDeg:-29.8801,mag:2.6},{name:"Zubeneschamali",raHours:15.2834,decDeg:-9.3829,mag:2.61},{name:"Unukalhai",raHours:15.7378,decDeg:6.4256,mag:2.63},{name:"Sheratan",raHours:1.9107,decDeg:20.808,mag:2.64},{name:"Phact",raHours:5.6608,decDeg:-34.0741,mag:2.65},{name:"Mahasim",raHours:5.9954,decDeg:37.2126,mag:2.65},{name:"Kraz",raHours:12.5731,decDeg:-23.3968,mag:2.65},{name:"Ruchbah",raHours:1.4302,decDeg:60.2353,mag:2.66},{name:"Muphrid",raHours:13.9114,decDeg:18.3977,mag:2.68},{name:"β Lupi",raHours:14.9755,decDeg:-43.134,mag:2.68},{name:"Hassaleh",raHours:4.9499,decDeg:33.1661,mag:2.69},{name:"μ Velorum",raHours:10.7795,decDeg:-49.4203,mag:2.69},{name:"α Muscae",raHours:12.6197,decDeg:-69.1356,mag:2.69},{name:"Lesath",raHours:17.5127,decDeg:-37.2958,mag:2.7},{name:"π Puppis",raHours:7.2857,decDeg:-37.0975,mag:2.71},{name:"Kaus Media",raHours:18.3499,decDeg:-29.8281,mag:2.72},{name:"Tarazed",raHours:19.771,decDeg:10.6133,mag:2.72},{name:"Yed Prior",raHours:16.2391,decDeg:-3.6943,mag:2.73},{name:"Athebyne",raHours:16.3999,decDeg:61.5142,mag:2.73},{name:"θ Carinae",raHours:10.7159,decDeg:-64.3945,mag:2.74},{name:"Porrima",raHours:12.6943,decDeg:-1.4494,mag:2.74},{name:"Hatysa",raHours:5.5906,decDeg:-5.9099,mag:2.75},{name:"ι Centauri",raHours:13.3433,decDeg:-36.7123,mag:2.75},{name:"Zubenelgenubi",raHours:14.848,decDeg:-16.0418,mag:2.75},{name:"Cebalrai",raHours:17.7245,decDeg:4.5673,mag:2.76},{name:"Cursa",raHours:5.1308,decDeg:-5.0864,mag:2.78},{name:"Kornephoros",raHours:16.5037,decDeg:21.4896,mag:2.78},{name:"Rasalgethi",raHours:17.2441,decDeg:14.3903,mag:2.78},{name:"Imai",raHours:12.2524,decDeg:-58.7489,mag:2.79},{name:"Rastaban",raHours:17.5072,decDeg:52.3014,mag:2.79},{name:"γ Lupi",raHours:15.5857,decDeg:-41.1668,mag:2.8},{name:"Nihal",raHours:5.4708,decDeg:-20.7594,mag:2.81},{name:"ζ Herculis",raHours:16.6881,decDeg:31.6027,mag:2.81},{name:"β Hydri",raHours:.4279,decDeg:-77.2542,mag:2.82},{name:"Paikauhale",raHours:16.598,decDeg:-28.216,mag:2.82},{name:"Kaus Borealis",raHours:18.4662,decDeg:-25.4217,mag:2.82},{name:"Algenib",raHours:.2206,decDeg:15.1836,mag:2.83},{name:"Tureis",raHours:8.1257,decDeg:-24.3043,mag:2.83},{name:"β Trianguli Australis",raHours:15.9191,decDeg:-63.4307,mag:2.83},{name:"ζ Persei",raHours:3.9022,decDeg:31.8836,mag:2.84},{name:"β Arae",raHours:17.4217,decDeg:-55.5299,mag:2.84},{name:"α Arae",raHours:17.5307,decDeg:-49.8761,mag:2.84},{name:"Alcyone",raHours:3.7914,decDeg:24.1051,mag:2.85},{name:"Vindemiatrix",raHours:13.0363,decDeg:10.9591,mag:2.85},{name:"Deneb Algedi",raHours:21.784,decDeg:-16.1273,mag:2.85},{name:"Castor B",raHours:7.5768,decDeg:31.8905,mag:2.85},{name:"α Hydri",raHours:1.9795,decDeg:-61.5699,mag:2.86},{name:"Fawaris",raHours:19.7496,decDeg:45.1308,mag:2.86},{name:"Tejat",raHours:6.3827,decDeg:22.5136,mag:2.87},{name:"γ Trianguli Australis",raHours:15.3152,decDeg:-68.6795,mag:2.87},{name:"α Tucanae",raHours:22.3084,decDeg:-60.2596,mag:2.87},{name:"Acamar",raHours:2.971,decDeg:-40.3047,mag:2.88},{name:"Albaldah",raHours:19.1627,decDeg:-21.0236,mag:2.88},{name:"Gomeisa",raHours:7.4525,decDeg:8.2893,mag:2.89},{name:"Cor Caroli",raHours:12.9338,decDeg:38.3184,mag:2.89},{name:"Fang",raHours:15.9809,decDeg:-26.1141,mag:2.89},{name:"ε Persei",raHours:3.9642,decDeg:40.0102,mag:2.9},{name:"Alniyat",raHours:16.3531,decDeg:-25.5928,mag:2.9},{name:"Sadalsuud",raHours:21.526,decDeg:-5.5712,mag:2.9},{name:"γ Persei",raHours:3.0799,decDeg:53.5064,mag:2.91},{name:"υ Carinae",raHours:9.785,decDeg:-65.072,mag:2.92},{name:"Matar",raHours:22.7167,decDeg:30.2212,mag:2.93},{name:"τ Puppis",raHours:6.8323,decDeg:-50.6146,mag:2.94},{name:"Algorab",raHours:12.4977,decDeg:-16.5154,mag:2.94},{name:"Sadalmelik",raHours:22.0964,decDeg:-.3199,mag:2.95},{name:"Zaurak",raHours:3.9672,decDeg:-13.5085,mag:2.97},{name:"Tianguan",raHours:5.6274,decDeg:21.1425,mag:2.97},{name:"Ras Elased Australis",raHours:9.7642,decDeg:23.7743,mag:2.97},{name:"Alnasl",raHours:18.0968,decDeg:-30.4241,mag:2.98},{name:"γ Hydrae",raHours:13.3154,decDeg:-23.1715,mag:2.99},{name:"ι¹ Scorpii",raHours:17.7931,decDeg:-40.127,mag:2.99},{name:"Okab",raHours:19.0902,decDeg:13.8635,mag:2.99},{name:"β Trianguli",raHours:2.1591,decDeg:34.9873,mag:3},{name:"ψ Ursae Majoris",raHours:11.1611,decDeg:44.4985,mag:3},{name:"Pherkad",raHours:15.3455,decDeg:71.834,mag:3},{name:"Xamidimura",raHours:16.8645,decDeg:-38.0474,mag:3},{name:"Aldhanab",raHours:21.8988,decDeg:-37.3649,mag:3}];class Ge{static GROUND_RADIUS_M=900;static EARTH_RADIUS_M=6371e3;static MAX_GROUND_VISIBILITY_M=3e4;static REBUILD_DISTANCE_M=150;static ROADS_MAX_RADIUS_M=5e3;static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;static groundRadiusFor(t){const e=Math.sqrt(2*Ge.EARTH_RADIUS_M*Math.max(t,0));return Math.max(Ge.GROUND_RADIUS_M,Math.min(e,Ge.MAX_GROUND_VISIBILITY_M))}static AIRBORNE_FROM_M=300;static SHARP_GROUND_HEIGHTS=4;static SHARP_GROUND_MIN_M=6e3;static SHARP_GROUND_MAX_M=12e3;static patchRadiusFor(t,e){if(e<Ge.AIRBORNE_FROM_M)return t;const i=Math.min(Ge.SHARP_GROUND_MAX_M,Math.max(Ge.SHARP_GROUND_MIN_M,e*Ge.SHARP_GROUND_HEIGHTS));return Math.min(t,i)}static LOOK_PATCH_SHARE=.4;static LOOK_WITHIN_SHARE=.6;static LOOK_DOWN_FROM_DEG=3;static lookPatchFor(t,e,i){if(t<Ge.AIRBORNE_FROM_M||e>-3)return;const n=t/Math.tan(-e*Math.PI/180);if(!(n<=i*Ge.LOOK_WITHIN_SHARE||n>Ge.MAX_GROUND_VISIBILITY_M))return{distanceM:n,radiusM:Math.max(Ge.SHARP_GROUND_MIN_M,n*Ge.LOOK_PATCH_SHARE)}}static rebuildDistanceFor(t){return Ge.REBUILD_DISTANCE_M*(t/Ge.GROUND_RADIUS_M)}static decorReachFor(t,e){if(e&&e.length>=2){const s=e[0];for(const r of e){const a=ae(r.lat,r.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)>Ge.STILL_OBSERVER_M)return 0}}let i=0;for(const s of t){if(s.kind==="aircraft"||s.kind==="observer"||s.track)continue;const r=Math.max(s.sizeM?.widthM??0,s.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(s.eastM,s.northM)+r)}const n=Math.ceil(i/Ge.PATCH_WHOLE_SHARE/100)*100;return n>Ge.GROUND_RADIUS_M*Ge.PATCH_WHOLE_SHARE?Math.min(n,Ge.MAX_DECOR_TERRAIN_M):0}static FAR_RING_RADIUS_M=Ge.MAX_GROUND_VISIBILITY_M;static OVERLOOK_M=20;static needsFarRing(t,e,i){return t>=Ge.FAR_RING_RADIUS_M?!1:e>=Ge.OVERLOOK_M||i>t}static beamReachFor(t,e){let i=0;for(const n of t)for(const s of[...n.path,...(n.moves??[]).flatMap(r=>r.path)]){const r=ae(s.lat,s.lng,e.lat,e.lng);i=Math.max(i,Math.hypot(r.x,r.z))}return i}}class Lh{static GREEN_FROM=.22;static GREEN_FULL=.5;static CONTRAST=.5;static install(t,e=!1){const i=new tt;t.userData.grassOrigin=i,t.onBeforeCompile=n=>{n.uniforms.uGrassContrast={value:Lh.CONTRAST},n.uniforms.uGrassOrigin={value:i},n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
|
|
7568
|
+
${he.alphatest_fragment}`)}}class le{static WIDTH=160;static HEIGHT=90;static BLEACHING_CD_M2_S=22e7;static REGENERATION_S=110;static SPREAD_DEG=.5;static JUMP_MS=2e3;static POSITIVE_FADE_S=1.5;static POSITIVE_GAIN=20;static FLIGHT=[{ageS:0,rgb:[1,1,1]},{ageS:.6,rgb:[.35,1.05,.95]},{ageS:1.4,rgb:[.55,.6,3.6]},{ageS:2.4,rgb:[1.7,.6,1.5]},{ageS:3.5,rgb:[1.9,.75,.25]}];texture;left=new Float32Array(le.WIDTH*le.HEIGHT).fill(1);glow=new Float32Array(le.WIDTH*le.HEIGHT);age=new Float32Array(le.WIDTH*le.HEIGHT);bytes=le.freshBytes();lastMs;bleached=!1;constructor(){this.texture=new ys(this.bytes,le.WIDTH,le.HEIGHT,qi,We),this.texture.minFilter=ge,this.texture.magFilter=ge,this.texture.needsUpdate=!0}get any(){return this.bleached}advance(t,e,i){const n=this.lastMs===void 0?1/0:t-this.lastMs;if(this.lastMs=t,n===0)return!1;const s=le.SPREAD_DEG*Math.PI/180,r=e.map(u=>({x:u.ndcX*i.width/2,y:u.ndcY*i.height/2,peak:u.lux/(2*Math.PI*s*s)})).filter(u=>u.peak>=le.FAINTEST_CD_M2);if(n<0||n>le.JUMP_MS)return this.previous=r,this.reset();if(!this.bleached&&e.length===0)return this.previous=void 0,!1;const a=this.previous?.length===r.length?this.previous:void 0,c=a?Math.max(0,...r.map((u,d)=>Math.hypot(u.x-a[d].x,u.y-a[d].y))):0,l=Math.min(le.MAX_STEPS,Math.max(1,Math.ceil(c/(le.SPREAD_DEG/3)))),h=n/1e3/l;for(let u=1;u<=l;u++){const d=u/l;this.bleach(a?r.map((f,p)=>({...f,x:a[p].x+(f.x-a[p].x)*d,y:a[p].y+(f.y-a[p].y)*d})):r,h,i)}return this.previous=r,this.texture.needsUpdate=!0,!0}static FAINTEST_CD_M2=le.BLEACHING_CD_M2_S/le.REGENERATION_S*1e-4;static MAX_STEPS=64;previous;bleach(t,e,i){const n=le.WIDTH,s=le.HEIGHT,r=le.SPREAD_DEG,a=1/le.REGENERATION_S,c=this.light.fill(0);for(const h of t){const u=Math.max(0,Math.floor(((h.x-5*r)/i.width+.5)*n)),d=Math.min(n-1,Math.ceil(((h.x+5*r)/i.width+.5)*n)),f=Math.max(0,Math.floor(((h.y-5*r)/i.height+.5)*s)),p=Math.min(s-1,Math.ceil(((h.y+5*r)/i.height+.5)*s));for(let m=f;m<=p;m++){const g=((m+.5)/s*2-1)*i.height/2;for(let v=u;v<=d;v++){const x=(((v+.5)/n*2-1)*i.width/2-h.x)**2+(g-h.y)**2;x<25*r*r&&(c[m*n+v]+=h.peak*Math.exp(-x/(2*r*r)))}}}let l=!1;for(let h=0;h<s;h++)for(let u=0;u<n;u++){const d=h*n+u,f=c[d],p=this.left[d],m=this.glow[d];if(f===0&&p>=.9995&&m<le.GLOW_SEEN)continue;const g=a+f/le.BLEACHING_CD_M2_S,v=a/g,M=v+(p-v)*Math.exp(-g*e);this.left[d]=M;const x=Math.max(0,p-M)*le.POSITIVE_GAIN,y=m*Math.exp(-e/le.POSITIVE_FADE_S),w=y+x;this.age[d]=w>0?y*(this.age[d]+e)/w:0,this.glow[d]=w;const S=le.flightAt(this.age[d]),E=d*4;this.bytes[E]=kn.toHalfFloat(M);for(let b=0;b<3;b++)this.bytes[E+1+b]=kn.toHalfFloat(w*S[b]);(M<.995||w>=le.GLOW_SEEN)&&(l=!0)}this.bleached=l}light=new Float32Array(le.WIDTH*le.HEIGHT);static GLOW_SEEN=.002;static flightAt(t){const e=le.FLIGHT;for(let i=1;i<e.length;i++){if(t>e[i].ageS)continue;const n=(t-e[i-1].ageS)/(e[i].ageS-e[i-1].ageS),s=e[i-1].rgb,r=e[i].rgb;return[s[0]+(r[0]-s[0])*n,s[1]+(r[1]-s[1])*n,s[2]+(r[2]-s[2])*n]}return e[e.length-1].rgb}static freshBytes(){const t=new Uint16Array(le.WIDTH*le.HEIGHT*4),e=kn.toHalfFloat(1);for(let i=0;i<t.length;i+=4)t[i]=e;return t}leftAt(t,e){const i=Math.min(le.WIDTH-1,Math.max(0,Math.floor((t+1)/2*le.WIDTH))),n=Math.min(le.HEIGHT-1,Math.max(0,Math.floor((e+1)/2*le.HEIGHT)));return this.left[n*le.WIDTH+i]}get atMs(){return this.lastMs}replay(t,e,i,n,s){const r=new Map,a=d=>{let f=r.get(d);return f||r.set(d,f=i(d)),f};s!==this.snapshotsOf&&(this.snapshots.clear(),this.snapshotsOf=s);let c=t;for(const d of this.snapshots.keys())d<=e&&d>c&&(c=d);c>t?this.restore(c):this.reset(),this.previous=void 0,this.lastMs=c;let l=c,h=0;const u=d=>{const f=d%le.REPLAY_STRIDE_MS===0&&a(d).length>0?le.REPLAY_STRIDE_MS:le.SNAPSHOT_MS;d%f!==0||this.snapshots.has(d)||(h>0&&this.rest(h),h=0,this.snapshots.set(d,{left:this.left.slice(),glow:this.glow.slice(),age:this.age.slice(),bleached:this.bleached}))};for(;l<e;){u(l);const d=Math.min(e,(Math.floor(l/le.REPLAY_STRIDE_MS)+1)*le.REPLAY_STRIDE_MS);if(a(d).length===0&&a(l).length===0){h+=d-l,l=d;continue}h>0&&this.rest(h),h=0;const f=Math.min(e,(Math.floor(l/le.REPLAY_STEP_MS)+1)*le.REPLAY_STEP_MS);this.lastMs=l,this.advance(f,a(f),n),l=f}h>0&&this.rest(h),this.lastMs=e}static SNAPSHOT_MS=5e3;snapshots=new Map;snapshotsOf;restore(t){const e=this.snapshots.get(t);this.left.set(e.left),this.glow.set(e.glow),this.age.set(e.age),this.bleached=e.bleached;for(let i=0;i<this.left.length;i++){const n=i*4,s=le.flightAt(this.age[i]);this.bytes[n]=kn.toHalfFloat(this.left[i]);for(let r=0;r<3;r++)this.bytes[n+1+r]=kn.toHalfFloat(this.glow[i]*s[r])}this.texture.needsUpdate=!0}static REPLAY_STEP_MS=100;static REPLAY_STRIDE_MS=1e3;rest(t){this.previous=void 0,this.bleached&&(this.bleach([],t/1e3,{width:1,height:1}),this.texture.needsUpdate=!0)}reset(){return this.bleached?(this.left.fill(1),this.glow.fill(0),this.age.fill(0),this.bytes.set(le.freshBytes()),this.bleached=!1,this.texture.needsUpdate=!0,!0):!1}dispose(){this.texture.dispose()}}class us{constructor(t,e,i=us.NO_SHADOW){this.parent=t,this.sceneUnitsPerLux=e,this.shadow=i}static NEAR=4;static FAR=2;static FAR_DISTANCE=1e3;static SYSTEMS={BodySystem:"emitters: the bodies that glow whole, the named lights of a model (a craft's lights), and their flames",MeteorSystem:"emitters: the heads of meteors, far, from their magnitude",ReentrySystem:"emitters: the heads of re-entries, far, from their magnitude",PhenomenonSystem:"none yet: a phenomenon states no luminance, only a colour as seen and a 0..1 dazzle, which say nothing of the light it gives",BeamSystem:"none: a laser beam is a thread of scattered light, too faint to light the ground; where it ends lit is in the sky",PlumeSystem:"none: a launch plume is lit by the Sun, it gives out no light of its own",CloudSystem:"none: clouds are lit, they do not give out light",LayeredCloudSystem:"none: clouds are lit, they do not give out light",DecorSystem:"own lights: the streetlamps, with shadows for the nearest (SceneRenderer.addStreetlightLight); NOT YET its lesser lamps (traffic lights, a car's rear lights), drawn lit but lighting nothing",RoadSystem:"own lights: the lamps it places along a street are the decor's streetlamps (see DecorSystem)",RailwaySystem:"none: rails mirror the lamps, they give out no light",ContrailSystem:"none: a contrail is lit by the Sun, it gives out no light",WaterSystem:"none: water mirrors, it gives out no light",TraceSystem:"none: a trace on the ground is lit, it gives out no light",ReferenceSystem:"none: a photograph laid over the scene, not in it",MirrorSystem:"none: a mirror shows the scene's light, it gives out none",HeadlightSystem:"own lights: a vehicle's headlamps are spot lights, aimed",FlameEffect:"emitters: through BodySystem, which states each flame",LensFlareEffect:"none: a dazzle in the eye, nothing in the world",IceHaloEffect:"none: sunlight bent by ice, seen, not cast on the ground",RainbowEffect:"none: sunlight bent by drops, seen, not cast on the ground",SkyGlowEffect:"none: the Milky Way and the zodiacal light are in the sky's own light (ScatteredSky)",RainSystem:"none: rain gives out no light",SatelliteField:"none: a satellite is a speck of reflected sunlight, far too faint to light anything"};near;far;nearBy=new Map;farBy=new Map;static NO_SHADOW={halfExtentM:0,depthHalfRangeM:0,biasM:0,normalBiasM:0,mapSize:0};set(t,e,i=[]){this.nearBy.set(t,e.filter(n=>n.candela>0)),this.farBy.set(t,i.filter(n=>Math.max(...n.lux)>0))}cast(t){const e=[...this.nearBy.values()].flat(),i=[...this.farBy.values()].flat(),n=this.sceneUnitsPerLux();if(e.length>0||this.near){this.near??=this.build(us.NEAR,()=>new WE(16777215,0,0,2));const s=a=>t?a.candela/Math.max(a.position.distanceToSquared(t),1e-6):a.candela,r=e.sort((a,c)=>s(c)-s(a));this.near.forEach((a,c)=>{const l=r[c];if(!l){a.intensity=0;return}a.position.copy(l.position);const h=us.luminanceOf(l.colour);a.color.setRGB(l.colour[0]/h,l.colour[1]/h,l.colour[2]/h),a.intensity=l.candela*n})}if(i.length>0||this.far){this.far??=this.buildFar();const s=i.sort((r,a)=>us.luminanceOf(a.lux)-us.luminanceOf(r.lux));this.far.forEach((r,a)=>{const c=s[a];if(r.castShadow&&(r.shadow.autoUpdate=c!==void 0),!c){r.intensity=0;return}r.position.copy(c.direction).multiplyScalar(us.FAR_DISTANCE).add(t??us.ORIGIN),r.target.position.copy(t??us.ORIGIN),r.target.updateMatrixWorld();const l=us.luminanceOf(c.lux);r.color.setRGB(c.lux[0]/l,c.lux[1]/l,c.lux[2]/l),r.intensity=l*n})}}static SKY_LIGHTING_MAGNITUDE=-8;get farEmitters(){return[...this.farBy.values()].flat()}get brightestInSky(){let t;for(const e of[...this.farBy.values()].flat())e.sky.magnitude<(t?.magnitude??us.SKY_LIGHTING_MAGNITUDE)&&(t=e.sky);return t}get all(){return[...this.near??[],...this.far??[]]}buildFar(){const t=this.build(us.FAR,()=>new Ep(16777215,0)),e=this.shadow;if(e.mapSize>0){const i=t[0].shadow;t[0].castShadow=!0,i.mapSize.set(e.mapSize,e.mapSize);const n=i.camera;n.left=-e.halfExtentM,n.right=e.halfExtentM,n.top=e.halfExtentM,n.bottom=-e.halfExtentM,n.near=us.FAR_DISTANCE-e.depthHalfRangeM,n.far=us.FAR_DISTANCE+e.depthHalfRangeM,n.updateProjectionMatrix(),i.bias=-e.biasM/(2*e.depthHalfRangeM),i.normalBias=e.normalBiasM,i.autoUpdate=!1}return t}build(t,e){return Array.from({length:t},()=>{const i=e();return i.name="emitter-light",this.parent.add(i),i instanceof Ep&&this.parent.add(i.target),i})}static luminanceOf(t){return .2126*t[0]+.7152*t[1]+.0722*t[2]||1}static ORIGIN=new R}class br{static MAX_STRENGTH=32;static MID_GREY=.18;static shown(t,e){const i=Math.min(1,Math.max(0,t));return e<.001?i:Math.log(1+e*i)/Math.log(1+e)}static strengthFor(t){if(!(t>0)||t>=br.MID_GREY)return 0;if(br.shown(t,br.MAX_STRENGTH)<=br.MID_GREY)return br.MAX_STRENGTH;let e=0,i=br.MAX_STRENGTH;for(let n=0;n<40;n++){const s=(e+i)/2;br.shown(t,s)<br.MID_GREY?e=s:i=s}return(e+i)/2}}const RN=[{name:"Sirius",raHours:6.7525,decDeg:-16.7161,mag:-1.44},{name:"Canopus",raHours:6.3992,decDeg:-52.6957,mag:-.62},{name:"Arcturus",raHours:14.261,decDeg:19.1824,mag:-.05},{name:"Rigil Kentaurus",raHours:14.6608,decDeg:-60.834,mag:-.01},{name:"Vega",raHours:18.6156,decDeg:38.7837,mag:.03},{name:"Capella",raHours:5.2782,decDeg:45.998,mag:.08},{name:"Rigel",raHours:5.2423,decDeg:-8.2016,mag:.18},{name:"Procyon",raHours:7.655,decDeg:5.225,mag:.4},{name:"Achernar",raHours:1.6286,decDeg:-57.2368,mag:.45},{name:"Betelgeuse",raHours:5.9195,decDeg:7.4071,mag:.45},{name:"Hadar",raHours:14.0637,decDeg:-60.373,mag:.61},{name:"Altair",raHours:19.8464,decDeg:8.8683,mag:.76},{name:"Acrux",raHours:12.4433,decDeg:-63.0991,mag:.77},{name:"Aldebaran",raHours:4.5987,decDeg:16.5093,mag:.87},{name:"Spica",raHours:13.4199,decDeg:-11.1613,mag:.98},{name:"Antares",raHours:16.4901,decDeg:-26.432,mag:1.06},{name:"Pollux",raHours:7.7553,decDeg:28.0262,mag:1.16},{name:"Fomalhaut",raHours:22.9608,decDeg:-29.6222,mag:1.17},{name:"Mimosa",raHours:12.7954,decDeg:-59.6888,mag:1.25},{name:"Deneb",raHours:20.6905,decDeg:45.2803,mag:1.25},{name:"Toliman",raHours:14.6603,decDeg:-60.8383,mag:1.35},{name:"Regulus",raHours:10.1395,decDeg:11.9672,mag:1.36},{name:"Adhara",raHours:6.9771,decDeg:-28.9721,mag:1.5},{name:"Castor",raHours:7.5766,decDeg:31.8883,mag:1.58},{name:"Gacrux",raHours:12.5194,decDeg:-57.1132,mag:1.59},{name:"Shaula",raHours:17.5601,decDeg:-37.1038,mag:1.62},{name:"Bellatrix",raHours:5.4189,decDeg:6.3497,mag:1.64},{name:"Elnath",raHours:5.4382,decDeg:28.6075,mag:1.65},{name:"Miaplacidus",raHours:9.22,decDeg:-69.7172,mag:1.67},{name:"Alnilam",raHours:5.6036,decDeg:-1.2019,mag:1.69},{name:"Alnair",raHours:22.1372,decDeg:-46.961,mag:1.73},{name:"Alnitak",raHours:5.6793,decDeg:-1.9426,mag:1.74},{name:"γ² Velorum",raHours:8.1589,decDeg:-47.3366,mag:1.75},{name:"Alioth",raHours:12.9005,decDeg:55.9598,mag:1.76},{name:"Mirfak",raHours:3.4054,decDeg:49.8612,mag:1.79},{name:"Kaus Australis",raHours:18.4029,decDeg:-34.3846,mag:1.79},{name:"Dubhe",raHours:11.0622,decDeg:61.751,mag:1.81},{name:"Wezen",raHours:7.1399,decDeg:-26.3932,mag:1.83},{name:"Alkaid",raHours:13.7924,decDeg:49.3133,mag:1.85},{name:"Avior",raHours:8.3752,decDeg:-59.5095,mag:1.86},{name:"Sargas",raHours:17.622,decDeg:-42.9978,mag:1.86},{name:"Menkalinan",raHours:5.9921,decDeg:44.9474,mag:1.9},{name:"Atria",raHours:16.8111,decDeg:-69.0277,mag:1.91},{name:"Alhena",raHours:6.6285,decDeg:16.3993,mag:1.93},{name:"Alsephina",raHours:8.7451,decDeg:-54.7088,mag:1.93},{name:"Peacock",raHours:20.4275,decDeg:-56.7351,mag:1.94},{name:"Polaris",raHours:2.5297,decDeg:89.2641,mag:1.97},{name:"Mirzam",raHours:6.3783,decDeg:-17.9559,mag:1.98},{name:"Alphard",raHours:9.4598,decDeg:-8.6586,mag:1.99},{name:"Hamal",raHours:2.1196,decDeg:23.4624,mag:2.01},{name:"Algieba",raHours:10.3329,decDeg:19.8415,mag:2.01},{name:"Diphda",raHours:.7265,decDeg:-17.9866,mag:2.04},{name:"Nunki",raHours:18.9211,decDeg:-26.2967,mag:2.05},{name:"Menkent",raHours:14.1114,decDeg:-36.37,mag:2.06},{name:"Alpheratz",raHours:.1398,decDeg:29.0904,mag:2.07},{name:"Mirach",raHours:1.1622,decDeg:35.6206,mag:2.07},{name:"Saiph",raHours:5.7959,decDeg:-9.6696,mag:2.07},{name:"Kochab",raHours:14.8451,decDeg:74.1555,mag:2.07},{name:"Tiaki",raHours:22.7111,decDeg:-46.8846,mag:2.07},{name:"Rasalhague",raHours:17.5822,decDeg:12.56,mag:2.08},{name:"Algol",raHours:3.1361,decDeg:40.9556,mag:2.09},{name:"Almach",raHours:2.065,decDeg:42.3297,mag:2.1},{name:"Denebola",raHours:11.8177,decDeg:14.5721,mag:2.14},{name:"Cih",raHours:.9451,decDeg:60.7167,mag:2.15},{name:"γ Centauri",raHours:12.692,decDeg:-48.9599,mag:2.2},{name:"Naos",raHours:8.0597,decDeg:-40.0031,mag:2.21},{name:"Aspidiske",raHours:9.2848,decDeg:-59.2752,mag:2.21},{name:"Alphecca",raHours:15.5781,decDeg:26.7147,mag:2.22},{name:"Suhail",raHours:9.1333,decDeg:-43.4326,mag:2.23},{name:"Mizar",raHours:13.3987,decDeg:54.9254,mag:2.23},{name:"Sadr",raHours:20.3705,decDeg:40.2567,mag:2.23},{name:"Schedar",raHours:.6751,decDeg:56.5373,mag:2.24},{name:"Eltanin",raHours:17.9434,decDeg:51.4889,mag:2.24},{name:"Mintaka",raHours:5.5334,decDeg:-.2991,mag:2.25},{name:"Caph",raHours:.1529,decDeg:59.1498,mag:2.28},{name:"ε Centauri",raHours:13.6648,decDeg:-53.4664,mag:2.29},{name:"Dschubba",raHours:16.0056,decDeg:-22.6217,mag:2.29},{name:"Larawag",raHours:16.8361,decDeg:-34.2932,mag:2.29},{name:"α Lupi",raHours:14.6988,decDeg:-47.3882,mag:2.3},{name:"η Centauri",raHours:14.5918,decDeg:-42.1578,mag:2.33},{name:"Merak",raHours:11.0307,decDeg:56.3824,mag:2.34},{name:"Izar",raHours:14.7498,decDeg:27.0742,mag:2.35},{name:"Enif",raHours:21.7364,decDeg:9.875,mag:2.38},{name:"κ Scorpii",raHours:17.7081,decDeg:-39.03,mag:2.39},{name:"Ankaa",raHours:.4381,decDeg:-42.306,mag:2.4},{name:"Phecda",raHours:11.8972,decDeg:53.6948,mag:2.41},{name:"Sabik",raHours:17.173,decDeg:-15.7249,mag:2.43},{name:"Scheat",raHours:23.0629,decDeg:28.0828,mag:2.44},{name:"Aludra",raHours:7.4016,decDeg:-29.3031,mag:2.45},{name:"Alderamin",raHours:21.3096,decDeg:62.5856,mag:2.45},{name:"Markeb",raHours:9.3686,decDeg:-55.0107,mag:2.47},{name:"Aljanah",raHours:20.7702,decDeg:33.9703,mag:2.48},{name:"Markab",raHours:23.0793,decDeg:15.2053,mag:2.49},{name:"Menkar",raHours:3.038,decDeg:4.0897,mag:2.54},{name:"ζ Ophiuchi",raHours:16.6193,decDeg:-10.5671,mag:2.54},{name:"ζ Centauri",raHours:13.9257,decDeg:-47.2884,mag:2.55},{name:"Zosma",raHours:11.2351,decDeg:20.5237,mag:2.56},{name:"Acrab",raHours:16.0906,decDeg:-19.8055,mag:2.56},{name:"Arneb",raHours:5.5455,decDeg:-17.8223,mag:2.58},{name:"δ Centauri",raHours:12.1393,decDeg:-50.7224,mag:2.58},{name:"Gienah",raHours:12.2634,decDeg:-17.5419,mag:2.58},{name:"Ascella",raHours:19.0435,decDeg:-29.8801,mag:2.6},{name:"Zubeneschamali",raHours:15.2834,decDeg:-9.3829,mag:2.61},{name:"Unukalhai",raHours:15.7378,decDeg:6.4256,mag:2.63},{name:"Sheratan",raHours:1.9107,decDeg:20.808,mag:2.64},{name:"Phact",raHours:5.6608,decDeg:-34.0741,mag:2.65},{name:"Mahasim",raHours:5.9954,decDeg:37.2126,mag:2.65},{name:"Kraz",raHours:12.5731,decDeg:-23.3968,mag:2.65},{name:"Ruchbah",raHours:1.4302,decDeg:60.2353,mag:2.66},{name:"Muphrid",raHours:13.9114,decDeg:18.3977,mag:2.68},{name:"β Lupi",raHours:14.9755,decDeg:-43.134,mag:2.68},{name:"Hassaleh",raHours:4.9499,decDeg:33.1661,mag:2.69},{name:"μ Velorum",raHours:10.7795,decDeg:-49.4203,mag:2.69},{name:"α Muscae",raHours:12.6197,decDeg:-69.1356,mag:2.69},{name:"Lesath",raHours:17.5127,decDeg:-37.2958,mag:2.7},{name:"π Puppis",raHours:7.2857,decDeg:-37.0975,mag:2.71},{name:"Kaus Media",raHours:18.3499,decDeg:-29.8281,mag:2.72},{name:"Tarazed",raHours:19.771,decDeg:10.6133,mag:2.72},{name:"Yed Prior",raHours:16.2391,decDeg:-3.6943,mag:2.73},{name:"Athebyne",raHours:16.3999,decDeg:61.5142,mag:2.73},{name:"θ Carinae",raHours:10.7159,decDeg:-64.3945,mag:2.74},{name:"Porrima",raHours:12.6943,decDeg:-1.4494,mag:2.74},{name:"Hatysa",raHours:5.5906,decDeg:-5.9099,mag:2.75},{name:"ι Centauri",raHours:13.3433,decDeg:-36.7123,mag:2.75},{name:"Zubenelgenubi",raHours:14.848,decDeg:-16.0418,mag:2.75},{name:"Cebalrai",raHours:17.7245,decDeg:4.5673,mag:2.76},{name:"Cursa",raHours:5.1308,decDeg:-5.0864,mag:2.78},{name:"Kornephoros",raHours:16.5037,decDeg:21.4896,mag:2.78},{name:"Rasalgethi",raHours:17.2441,decDeg:14.3903,mag:2.78},{name:"Imai",raHours:12.2524,decDeg:-58.7489,mag:2.79},{name:"Rastaban",raHours:17.5072,decDeg:52.3014,mag:2.79},{name:"γ Lupi",raHours:15.5857,decDeg:-41.1668,mag:2.8},{name:"Nihal",raHours:5.4708,decDeg:-20.7594,mag:2.81},{name:"ζ Herculis",raHours:16.6881,decDeg:31.6027,mag:2.81},{name:"β Hydri",raHours:.4279,decDeg:-77.2542,mag:2.82},{name:"Paikauhale",raHours:16.598,decDeg:-28.216,mag:2.82},{name:"Kaus Borealis",raHours:18.4662,decDeg:-25.4217,mag:2.82},{name:"Algenib",raHours:.2206,decDeg:15.1836,mag:2.83},{name:"Tureis",raHours:8.1257,decDeg:-24.3043,mag:2.83},{name:"β Trianguli Australis",raHours:15.9191,decDeg:-63.4307,mag:2.83},{name:"ζ Persei",raHours:3.9022,decDeg:31.8836,mag:2.84},{name:"β Arae",raHours:17.4217,decDeg:-55.5299,mag:2.84},{name:"α Arae",raHours:17.5307,decDeg:-49.8761,mag:2.84},{name:"Alcyone",raHours:3.7914,decDeg:24.1051,mag:2.85},{name:"Vindemiatrix",raHours:13.0363,decDeg:10.9591,mag:2.85},{name:"Deneb Algedi",raHours:21.784,decDeg:-16.1273,mag:2.85},{name:"Castor B",raHours:7.5768,decDeg:31.8905,mag:2.85},{name:"α Hydri",raHours:1.9795,decDeg:-61.5699,mag:2.86},{name:"Fawaris",raHours:19.7496,decDeg:45.1308,mag:2.86},{name:"Tejat",raHours:6.3827,decDeg:22.5136,mag:2.87},{name:"γ Trianguli Australis",raHours:15.3152,decDeg:-68.6795,mag:2.87},{name:"α Tucanae",raHours:22.3084,decDeg:-60.2596,mag:2.87},{name:"Acamar",raHours:2.971,decDeg:-40.3047,mag:2.88},{name:"Albaldah",raHours:19.1627,decDeg:-21.0236,mag:2.88},{name:"Gomeisa",raHours:7.4525,decDeg:8.2893,mag:2.89},{name:"Cor Caroli",raHours:12.9338,decDeg:38.3184,mag:2.89},{name:"Fang",raHours:15.9809,decDeg:-26.1141,mag:2.89},{name:"ε Persei",raHours:3.9642,decDeg:40.0102,mag:2.9},{name:"Alniyat",raHours:16.3531,decDeg:-25.5928,mag:2.9},{name:"Sadalsuud",raHours:21.526,decDeg:-5.5712,mag:2.9},{name:"γ Persei",raHours:3.0799,decDeg:53.5064,mag:2.91},{name:"υ Carinae",raHours:9.785,decDeg:-65.072,mag:2.92},{name:"Matar",raHours:22.7167,decDeg:30.2212,mag:2.93},{name:"τ Puppis",raHours:6.8323,decDeg:-50.6146,mag:2.94},{name:"Algorab",raHours:12.4977,decDeg:-16.5154,mag:2.94},{name:"Sadalmelik",raHours:22.0964,decDeg:-.3199,mag:2.95},{name:"Zaurak",raHours:3.9672,decDeg:-13.5085,mag:2.97},{name:"Tianguan",raHours:5.6274,decDeg:21.1425,mag:2.97},{name:"Ras Elased Australis",raHours:9.7642,decDeg:23.7743,mag:2.97},{name:"Alnasl",raHours:18.0968,decDeg:-30.4241,mag:2.98},{name:"γ Hydrae",raHours:13.3154,decDeg:-23.1715,mag:2.99},{name:"ι¹ Scorpii",raHours:17.7931,decDeg:-40.127,mag:2.99},{name:"Okab",raHours:19.0902,decDeg:13.8635,mag:2.99},{name:"β Trianguli",raHours:2.1591,decDeg:34.9873,mag:3},{name:"ψ Ursae Majoris",raHours:11.1611,decDeg:44.4985,mag:3},{name:"Pherkad",raHours:15.3455,decDeg:71.834,mag:3},{name:"Xamidimura",raHours:16.8645,decDeg:-38.0474,mag:3},{name:"Aldhanab",raHours:21.8988,decDeg:-37.3649,mag:3}];class Be{static GROUND_RADIUS_M=900;static EARTH_RADIUS_M=6371e3;static MAX_GROUND_VISIBILITY_M=3e4;static REBUILD_DISTANCE_M=150;static ROADS_MAX_RADIUS_M=5e3;static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;static groundRadiusFor(t){const e=Math.sqrt(2*Be.EARTH_RADIUS_M*Math.max(t,0));return Math.max(Be.GROUND_RADIUS_M,Math.min(e,Be.MAX_GROUND_VISIBILITY_M))}static AIRBORNE_FROM_M=300;static SHARP_GROUND_HEIGHTS=4;static SHARP_GROUND_MIN_M=6e3;static SHARP_GROUND_MAX_M=12e3;static patchRadiusFor(t,e){if(e<Be.AIRBORNE_FROM_M)return t;const i=Math.min(Be.SHARP_GROUND_MAX_M,Math.max(Be.SHARP_GROUND_MIN_M,e*Be.SHARP_GROUND_HEIGHTS));return Math.min(t,i)}static LOOK_PATCH_SHARE=.4;static LOOK_WITHIN_SHARE=.6;static LOOK_DOWN_FROM_DEG=3;static lookPatchFor(t,e,i){if(t<Be.AIRBORNE_FROM_M||e>-3)return;const n=t/Math.tan(-e*Math.PI/180);if(!(n<=i*Be.LOOK_WITHIN_SHARE||n>Be.MAX_GROUND_VISIBILITY_M))return{distanceM:n,radiusM:Math.max(Be.SHARP_GROUND_MIN_M,n*Be.LOOK_PATCH_SHARE)}}static rebuildDistanceFor(t){return Be.REBUILD_DISTANCE_M*(t/Be.GROUND_RADIUS_M)}static decorReachFor(t,e){if(e&&e.length>=2){const s=e[0];for(const r of e){const a=ae(r.lat,r.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)>Be.STILL_OBSERVER_M)return 0}}let i=0;for(const s of t){if(s.kind==="aircraft"||s.kind==="observer"||s.track)continue;const r=Math.max(s.sizeM?.widthM??0,s.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(s.eastM,s.northM)+r)}const n=Math.ceil(i/Be.PATCH_WHOLE_SHARE/100)*100;return n>Be.GROUND_RADIUS_M*Be.PATCH_WHOLE_SHARE?Math.min(n,Be.MAX_DECOR_TERRAIN_M):0}static FAR_RING_RADIUS_M=Be.MAX_GROUND_VISIBILITY_M;static OVERLOOK_M=20;static needsFarRing(t,e,i){return t>=Be.FAR_RING_RADIUS_M?!1:e>=Be.OVERLOOK_M||i>t}static beamReachFor(t,e){let i=0;for(const n of t)for(const s of[...n.path,...(n.moves??[]).flatMap(r=>r.path)]){const r=ae(s.lat,s.lng,e.lat,e.lng);i=Math.max(i,Math.hypot(r.x,r.z))}return i}}class Lh{static GREEN_FROM=.22;static GREEN_FULL=.5;static CONTRAST=.5;static install(t,e=!1){const i=new tt;t.userData.grassOrigin=i,t.onBeforeCompile=n=>{n.uniforms.uGrassContrast={value:Lh.CONTRAST},n.uniforms.uGrassOrigin={value:i},n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
|
|
7569
7569
|
varying vec2 vGrassPatchXZ;
|
|
7570
7570
|
uniform vec2 uGrassOrigin;`).replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
7571
7571
|
vGrassPatchXZ = position.xz + uGrassOrigin;`),n.fragmentShader=n.fragmentShader.replace("#include <common>",`#include <common>
|
|
@@ -7595,7 +7595,7 @@ float grassNoise(vec2 p) {
|
|
|
7595
7595
|
+ (grassNoise(vGrassPatchXZ * 21.0) - 0.5) * 0.6 * (1.0 - smoothstep(2.5, 12.0, eye));
|
|
7596
7596
|
float d = grain * uGrassContrast * grass;
|
|
7597
7597
|
diffuseColor.rgb *= vec3(1.0 + d * 1.1, 1.0 + d, 1.0 + d * 1.25);
|
|
7598
|
-
}`)},t.customProgramCacheKey=()=>e?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class Vr{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(t,e,i){const n=i&&i.length>=2?Vr.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=Vr.fill(t,r).filter(h=>!n?.[h]);if(a.length===0)continue;const c=a.map(h=>t.heights[h]).filter(Number.isFinite).sort((h,u)=>h-u);if(c.length===0)continue;const l=c[Math.floor((c.length-1)*Vr.LEVEL_QUANTILE)];for(const h of a)t.heights[h]>l&&(t.heights[h]=l,s++)}return s}static fill(t,e){const{width:i,height:n,bounds:s}=t,r=d=>(d-s.west)/(s.east-s.west)*(i-1),a=d=>(s.north-d)/(s.north-s.south)*(n-1),c=[];for(const d of e.rings)for(let f=0;f<d.length;f++){const p=d[f],m=d[(f+1)%d.length],g={r0:a(p.lat),c0:r(p.lng),r1:a(m.lat),c1:r(m.lng)};g.r0!==g.r1&&c.push(g)}const l=[];if(c.length===0)return l;const h=Math.max(0,Math.ceil(Math.min(...c.map(d=>Math.min(d.r0,d.r1))))),u=Math.min(n-1,Math.floor(Math.max(...c.map(d=>Math.max(d.r0,d.r1)))));for(let d=h;d<=u;d++){const f=[];for(const{r0:p,c0:m,r1:g,c1:v}of c)p<=d!=g<=d&&f.push(m+(v-m)*(d-p)/(g-p));f.sort((p,m)=>p-m);for(let p=0;p+1<f.length;p+=2){const m=Math.max(0,Math.ceil(f[p])),g=Math.min(i-1,Math.floor(f[p+1]));for(let v=m;v<=g;v++)l.push(d*i+v)}}return l}static alongRoute(t,e){const{width:i,height:n,bounds:s}=t,r=(s.east-s.west)*Vr.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*Vr.METRES_PER_DEGREE/(n-1),c=Math.ceil(Vr.ROUTE_CLEARANCE_M/r),l=Math.ceil(Vr.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*n),u=f=>(f-s.west)/(s.east-s.west)*(i-1),d=f=>(s.north-f)/(s.north-s.south)*(n-1);for(let f=0;f+1<e.length;f++){const[p,m,g,v]=[u(e[f].lng),d(e[f].lat),u(e[f+1].lng),d(e[f+1].lat)];if(Math.max(p,g)<-c||Math.min(p,g)>i-1+c||Math.max(m,v)<-l||Math.min(m,v)>n-1+l)continue;const M=Math.max(1,Math.ceil(Math.hypot(g-p,v-m)*2));for(let x=0;x<=M;x++){const y=Math.round(p+(g-p)*x/M),w=Math.round(m+(v-m)*x/M);for(let S=-l;S<=l;S++)for(let E=-c;E<=c;E++){const b=w+S,A=y+E;b<0||A<0||b>=n||A>=i||Math.hypot(E*r,S*a)<=Vr.ROUTE_CLEARANCE_M&&(h[b*i+A]=1)}}}return h}}const IN=64,Xw=IN+1,$w=2048,DN=900,CN=700/900,ON=0,PN=.01,NN=1500;function td(o,t,e){return{north:Ps(0,-e,o,t).lat,south:Ps(0,e,o,t).lat,east:Ps(e,0,o,t).lng,west:Ps(-e,0,o,t).lng}}async function Og(o,t,e,i=DN,n,s){const r=i,a=i*CN,c=td(o,t,r),l={width:Xw,height:Xw},h=s?void 0:e.water?.getWater(c).catch(O=>(console.warn("Water unavailable, drawing none:",O),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,l,n),e.imagery.getImageryTexture(c,{width:$w,height:$w})]);let f;const p=h?await Promise.race([h,new Promise(O=>{f=setTimeout(()=>O(void 0),NN)})]):void 0;if(clearTimeout(f),u.width!==u.height||u.width<3||u.heights.length!==u.width*u.height)throw new Error("The ground came as a grid that is not square");Np.fill(u.heights,u.width),p&&p.length>0&&Vr.flatten(u,p,n?.route);const m=u.width,g=m-1,v=Math.floor(m/2),M=u.heights[v*m+v],x=s?.referenceElevationM??M,y=new Float32Array(m*m*3),w=new Float32Array(m*m*2),S=new Float32Array(m*m*4);for(let O=0;O<m;O++){const L=O/(m-1),P=c.north+(c.south-c.north)*L;for(let k=0;k<m;k++){const H=k/(m-1),W=c.west+(c.east-c.west)*H,{x:Q,z:q}=ae(P,W,o,t),nt=u.heights[O*m+k],at=Math.max(Math.abs(Q),Math.abs(q)),Bt=s&&at<s.innerM?0:1-LN((at-a)/(r-a),0,1),Zt=ON+PN+(nt-x),Pt=O*m+k;y[Pt*3]=Q,y[Pt*3+1]=Zt,y[Pt*3+2]=q;const Z=KS(d.bounds,W,P);w[Pt*2]=Z.x,w[Pt*2+1]=Z.y,S[Pt*4]=1,S[Pt*4+1]=1,S[Pt*4+2]=1,S[Pt*4+3]=Bt}}const E=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let b=0;for(let O=0;O<g;O++)for(let L=0;L<g;L++){const P=O*m+L,k=P+1,H=P+m,W=H+1;E[b++]=P,E[b++]=H,E[b++]=k,E[b++]=k,E[b++]=H,E[b++]=W}const A=new ye;A.setAttribute("position",new ve(y,3)),A.setAttribute("uv",new ve(w,2)),A.setAttribute("color",new ve(S,4)),A.setIndex(new ve(E,1)),A.computeVertexNormals();const _=new cc(d.source);_.flipY=!1,_.colorSpace=Nn,_.anisotropy=8;const I=new pr({map:_,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||Lh.install(I);const D=new Mt(A,I);return D.receiveShadow=!s,D.castShadow=!s,{mesh:D,attribution:e.imagery.attribution,originElevationM:Number.isFinite(M)?M:void 0,...p?{water:p}:h?{waterLater:h}:{}}}class Np{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<Np.LOWEST_GROUND_M;let n=0;for(let s=0;s<t.length;s++)i(t[s])&&n++;for(let s=0;n>0&&s<Np.MAX_PASSES;s++){const r=[];for(let a=0;a<e;a++)for(let c=0;c<e;c++){const l=a*e+c;if(!i(t[l]))continue;let h=0,u=0;for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){const p=a+d,m=c+f;if(p<0||m<0||p>=e||m>=e)continue;const g=t[p*e+m];i(g)||(h+=g,u++)}u>0&&r.push([l,h/u])}for(const[a,c]of r)t[a]=c;if(n-=r.length,r.length===0)break}if(n>0)for(let s=0;s<t.length;s++)i(t[s])&&(t[s]=0)}}function LN(o,t,e){return Math.max(t,Math.min(e,o))}class Me{static STEP_M=8;stepM=Me.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new tt;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Xe;surveyed=new Xe;stated=new Xe;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(t){this.stepM=Number.isFinite(t)&&t>0?Math.min(Me.STEP_M,Math.max(1.5,t/2)):Me.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=Me.within(t,e,i,r);Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const l=new Map,h=c.map(f=>f.points.map(p=>ae(p.lat,p.lng,e,i))),u=c.map((f,p)=>this.streetOf(f,h[p],a));for(const[f,p]of c.entries()){const m=l.get(p.surface)??Me.batchFor(p.surface);l.set(p.surface,m);const g=u[f];this.appendPath(h[f],p.widthM,n,m,g?{lateralAt:(v,M,x,y)=>g(v,M,x,y).carriageway}:{})}for(const[f,p]of l){const m=this.meshOf(f,p,s);m&&this.surveyed.add(m)}const d=this.sidewalks(c,h,u,n);if(d.indices.length>0){const f=this.meshOf("paved",d,!1,Me.SIDEWALK_ALBEDO,!1);f&&(f.name="roads sidewalks",this.surveyed.add(f))}this.paint(c,e,i,n,s)}paint(t,e,i,n,s){if(!t.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(Me.markingsModule??=Et(()=>import("./RoadMarkings-DDNrriGo.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const c={positions:[],indices:[]};if(a.lay(t,e,i,(u,d,f)=>this.appendPath(u,d,n,c,{offsetM:f.offsetM,liftM:Me.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,Me.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=Me.MARKINGS_RENDER_ORDER,u.material.polygonOffsetFactor=-4,u.material.polygonOffsetUnits=-4,this.surveyed.add(u))}const h=a.barrierGeometry(a.barriers(t,e,i),n);if(h.indices.length>0){const u=this.meshOf("paved",h,s,Me.BARRIER_ALBEDO,!1);u&&(u.name="roads barriers",u.material.polygonOffset=!1,u.castShadow=!0,this.surveyed.add(u))}this.onMarkings?.()})}onMarkings;anchorGrain(t,e){if(this.grainReference){const n=ae(this.grainReference.lat,this.grainReference.lng,t,e);Math.hypot(n.x,n.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:t,lng:e};const i=ae(this.grainReference.lat,this.grainReference.lng,t,e);this.grainOrigin.set(-i.x,-i.z)}static within(t,e,i,n){if(!Number.isFinite(n))return t;const s=n*1.1+100;return t.filter(r=>{let a;for(const c of r.points){const l=ae(c.lat,c.lng,e,i);if(Math.hypot(l.x,l.z)<=s||a&&Math.hypot((l.x+a.x)/2,(l.z+a.z)/2)<=s)return!0;a=l}return!1})}streetOf(t,e,i){if(!t.urban||t.surface!=="paved")return;const n=Me.surveyedAcross(t);if(!i||!i.near(e))return()=>n;const s=new Map,r=(f,p,m,g)=>{const v=`${f.toFixed(2)}:${p.toFixed(2)}`;let M=s.get(v);return M||(M=i.across(f,p,m,g),s.set(v,M)),M},a=this.rungsOf(e),c=a.flatMap(f=>{const p=r(f.x,f.z,f.dirX,f.dirZ);return p.leftM!==void 0&&p.rightM!==void 0?[(p.leftM-p.rightM)/2]:[]}).sort((f,p)=>f-p),l=i.lampsAlong(e);if(c.length===0&&l.length===0)return()=>n;const h=c.length>0?c[Math.floor((c.length-1)/2)]:0,u=Me.clearOf(l,t.widthM/2,Math.max(-2.5,Math.min(Me.STREET_MIDDLE_MOST_M,h))),d={rungs:a,across:(f,p,m,g)=>Me.betweenWalls(t,u,r(f,p,m,g).leftM,r(f,p,m,g).rightM)};return this.laidStreets.push(d),(f,p,m,g)=>{const v=r(f,p,m,g);return Me.betweenWalls(t,u,v.leftM,v.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+Me.LAMP_CLEARANCE_M);if(n(i))return i;const s=Me.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*s;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=s&&n(a))return a;return i}atKerb(t,e){let i;for(const d of this.laidStreets)for(const f of d.rungs){const p=Math.hypot(t-f.x,e-f.z);p<=Me.KERB_REACH_M&&(!i||p<i.distance)&&(i={rung:f,across:d.across(f.x,f.z,f.dirX,f.dirZ),distance:p})}if(!i)return{x:t,z:e};const{rung:n,across:s}=i,r=(t-n.x)*-n.dirZ+(e-n.z)*n.dirX,a=(t-n.x)*n.dirX+(e-n.z)*n.dirZ,l=(r>=s.carriageway.offsetM?s.left:s.right)??s.left??s.right;if(!l)return{x:t,z:e};const h=Math.sign(l.outerM-l.kerbM),u=l.kerbM+h*Math.min(Me.LAMP_FROM_KERB_M,Math.abs(l.outerM-l.kerbM)/2);return{x:n.x+n.dirX*a-n.dirZ*u,z:n.z+n.dirZ*a+n.dirX*u}}rungsOf(t){const e=this.resample(t);return e.map((i,n)=>{const s=e[Math.max(0,n-1)],r=e[Math.min(e.length-1,n+1)],a=r.x-s.x,c=r.z-s.z,l=Math.hypot(a,c);return l<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/l,dirZ:c/l}})}static surveyedAcross(t){const e=t.widthM/2,i={offsetM:0,halfM:e};return t.widthM<Me.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+Me.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-Me.SIDEWALK_WIDTH_M}}}static betweenWalls(t,e,i,n){const s=t.widthM/2,r={offsetM:e,halfM:s},a=e+s,c=e-s,l=i??a+Me.SIDEWALK_WIDTH_M,h=-(n??-c+Me.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=Me.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...c-h>=Me.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:h}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new Wr(t,e);return t.forEach((a,c)=>{const l=i[c];if(!l)return;const h=(u,d)=>r.onAnotherCarriageway(u,d,c);for(const u of["left","right"]){const d=(f,p,m,g)=>{const v=l(f,p,m,g)[u];return v&&{offsetM:(v.kerbM+v.outerM)/2,halfM:Math.abs(v.outerM-v.kerbM)/2}};this.appendPath(e[c],0,n,s,{lateralAt:d,liftM:Me.LIFT_M+Me.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(e[c],n,s,(f,p,m,g)=>l(f,p,m,g)[u]?.kerbM,u==="left",h)}}),s}setStated(t,e){Me.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??Me.batchFor(n.surface);i.set(n.surface,s),this.appendPath(n.path.map(r=>({x:r.eastM,z:-r.northM})),n.widthM,e,s)}for(const[n,s]of i){const r=this.meshOf(n,s,!1);r&&this.stated.add(r)}}clear(){Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(t){for(const e of[...t.children]){t.remove(e);const i=e;i.geometry?.dispose(),i.material?.dispose()}}dispose(){Me.empty(this.surveyed),Me.empty(this.stated)}appendPath(t,e,i,n,s={}){const r=this.resample(t);if(r.length<2)return;const a=Math.max(s.minHalfM??.5,e/2),c=s.liftM??Me.LIFT_M,l=s.offsetM??0,h=n.positions.length/3,u=[],d=[],f=[];for(let m=0;m<r.length;m++){const g=r[Math.max(0,m-1)],v=r[Math.min(r.length-1,m+1)];let M=v.x-g.x,x=v.z-g.z;const y=Math.hypot(M,x);y<1e-6?(M=1,x=0):(M/=y,x/=y);const w=s.lateralAt?s.lateralAt(r[m].x,r[m].z,M,x):{offsetM:l,halfM:a},S=w?Math.max(s.minHalfM??.5,w.halfM):a,E=w?.offsetM??l,b=-x*S,A=M*S,_={x:r[m].x+-x*E,z:r[m].z+M*E};u.push(w!==void 0&&w.halfM>0&&!s.skip?.(_.x,_.z)),d.push([{x:_.x+b,z:_.z+A},_,{x:_.x-b,z:_.z-A}]),f.push(S)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const v=d[m][g],M=d[m+1][g],x=i((v.x+M.x)/2,(v.z+M.z)/2)-(p[m][g]+p[m+1][g])/2;x>0&&(p[m][g]+=x,p[m+1][g]+=x)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=h+m*3;n.indices.push(g,g+3,g+1,g+1,g+3,g+4),n.indices.push(g+1,g+4,g+2,g+2,g+4,g+5)}}appendKerb(t,e,i,n,s,r){const a=this.resample(t);if(a.length<2)return;const c=i.positions.length/3,l=[];for(let h=0;h<a.length;h++){const u=a[Math.max(0,h-1)],d=a[Math.min(a.length-1,h+1)];let f=d.x-u.x,p=d.z-u.z;const m=Math.hypot(f,p);m<1e-6?(f=1,p=0):(f/=m,p/=m);const g=n(a[h].x,a[h].z,f,p),v=a[h].x+-p*(g??0),M=a[h].z+f*(g??0);l.push(g!==void 0&&!r(v,M));const x=e(v,M)+Me.LIFT_M;i.positions.push(v,x,M,v,x+Me.SIDEWALK_KERB_M,M)}for(let h=0;h<a.length-1;h++){if(!l[h]||!l[h+1])continue;const u=c+h*2;s?i.indices.push(u,u+1,u+2,u+1,u+3,u+2):i.indices.push(u,u+2,u+1,u+1,u+2,u+3)}}static batchFor(t){return t==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(t,e,i,n,s=!0){if(e.indices.length===0)return;const r=new ye;r.setAttribute("position",new ve(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new ve(new Float32Array(e.edges),2)),r.setIndex(new ve(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??Me.ALBEDO[t],l=new pr({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?Me.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(l,Me.GRAIN_CONTRAST[t],a);const h=new Mt(r,l);return h.name=`roads ${t}`,h.renderOrder=Me.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(t,e,i=!1){const n=this.grainOrigin;t.onBeforeCompile=s=>{s.uniforms.uRoadOrigin={value:n},s.uniforms.uRoadContrast={value:e},i&&(s.defines={...s.defines,ROAD_VERGE:""}),s.vertexShader=s.vertexShader.replace("#include <common>",`#include <common>
|
|
7598
|
+
}`)},t.customProgramCacheKey=()=>e?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class Vr{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(t,e,i){const n=i&&i.length>=2?Vr.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=Vr.fill(t,r).filter(h=>!n?.[h]);if(a.length===0)continue;const c=a.map(h=>t.heights[h]).filter(Number.isFinite).sort((h,u)=>h-u);if(c.length===0)continue;const l=c[Math.floor((c.length-1)*Vr.LEVEL_QUANTILE)];for(const h of a)t.heights[h]>l&&(t.heights[h]=l,s++)}return s}static fill(t,e){const{width:i,height:n,bounds:s}=t,r=d=>(d-s.west)/(s.east-s.west)*(i-1),a=d=>(s.north-d)/(s.north-s.south)*(n-1),c=[];for(const d of e.rings)for(let f=0;f<d.length;f++){const p=d[f],m=d[(f+1)%d.length],g={r0:a(p.lat),c0:r(p.lng),r1:a(m.lat),c1:r(m.lng)};g.r0!==g.r1&&c.push(g)}const l=[];if(c.length===0)return l;const h=Math.max(0,Math.ceil(Math.min(...c.map(d=>Math.min(d.r0,d.r1))))),u=Math.min(n-1,Math.floor(Math.max(...c.map(d=>Math.max(d.r0,d.r1)))));for(let d=h;d<=u;d++){const f=[];for(const{r0:p,c0:m,r1:g,c1:v}of c)p<=d!=g<=d&&f.push(m+(v-m)*(d-p)/(g-p));f.sort((p,m)=>p-m);for(let p=0;p+1<f.length;p+=2){const m=Math.max(0,Math.ceil(f[p])),g=Math.min(i-1,Math.floor(f[p+1]));for(let v=m;v<=g;v++)l.push(d*i+v)}}return l}static alongRoute(t,e){const{width:i,height:n,bounds:s}=t,r=(s.east-s.west)*Vr.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*Vr.METRES_PER_DEGREE/(n-1),c=Math.ceil(Vr.ROUTE_CLEARANCE_M/r),l=Math.ceil(Vr.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*n),u=f=>(f-s.west)/(s.east-s.west)*(i-1),d=f=>(s.north-f)/(s.north-s.south)*(n-1);for(let f=0;f+1<e.length;f++){const[p,m,g,v]=[u(e[f].lng),d(e[f].lat),u(e[f+1].lng),d(e[f+1].lat)];if(Math.max(p,g)<-c||Math.min(p,g)>i-1+c||Math.max(m,v)<-l||Math.min(m,v)>n-1+l)continue;const M=Math.max(1,Math.ceil(Math.hypot(g-p,v-m)*2));for(let x=0;x<=M;x++){const y=Math.round(p+(g-p)*x/M),w=Math.round(m+(v-m)*x/M);for(let S=-l;S<=l;S++)for(let E=-c;E<=c;E++){const b=w+S,A=y+E;b<0||A<0||b>=n||A>=i||Math.hypot(E*r,S*a)<=Vr.ROUTE_CLEARANCE_M&&(h[b*i+A]=1)}}}return h}}const IN=64,Xw=IN+1,$w=2048,DN=900,CN=700/900,ON=0,PN=.01,NN=1500;function td(o,t,e){return{north:Ps(0,-e,o,t).lat,south:Ps(0,e,o,t).lat,east:Ps(e,0,o,t).lng,west:Ps(-e,0,o,t).lng}}async function Og(o,t,e,i=DN,n,s){const r=i,a=i*CN,c=td(o,t,r),l={width:Xw,height:Xw},h=s||i>Be.ROADS_MAX_RADIUS_M?void 0:e.water?.getWater(c).catch(O=>(console.warn("Water unavailable, drawing none:",O),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,l,n),e.imagery.getImageryTexture(c,{width:$w,height:$w})]);let f;const p=h?await Promise.race([h,new Promise(O=>{f=setTimeout(()=>O(void 0),NN)})]):void 0;if(clearTimeout(f),u.width!==u.height||u.width<3||u.heights.length!==u.width*u.height)throw new Error("The ground came as a grid that is not square");Np.fill(u.heights,u.width),p&&p.length>0&&Vr.flatten(u,p,n?.route);const m=u.width,g=m-1,v=Math.floor(m/2),M=u.heights[v*m+v],x=s?.referenceElevationM??M,y=new Float32Array(m*m*3),w=new Float32Array(m*m*2),S=new Float32Array(m*m*4);for(let O=0;O<m;O++){const L=O/(m-1),P=c.north+(c.south-c.north)*L;for(let k=0;k<m;k++){const H=k/(m-1),W=c.west+(c.east-c.west)*H,{x:Q,z:q}=ae(P,W,o,t),nt=u.heights[O*m+k],at=Math.max(Math.abs(Q),Math.abs(q)),Bt=s&&at<s.innerM?0:1-LN((at-a)/(r-a),0,1),Zt=ON+PN+(nt-x),Pt=O*m+k;y[Pt*3]=Q,y[Pt*3+1]=Zt,y[Pt*3+2]=q;const Z=KS(d.bounds,W,P);w[Pt*2]=Z.x,w[Pt*2+1]=Z.y,S[Pt*4]=1,S[Pt*4+1]=1,S[Pt*4+2]=1,S[Pt*4+3]=Bt}}const E=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let b=0;for(let O=0;O<g;O++)for(let L=0;L<g;L++){const P=O*m+L,k=P+1,H=P+m,W=H+1;E[b++]=P,E[b++]=H,E[b++]=k,E[b++]=k,E[b++]=H,E[b++]=W}const A=new ye;A.setAttribute("position",new ve(y,3)),A.setAttribute("uv",new ve(w,2)),A.setAttribute("color",new ve(S,4)),A.setIndex(new ve(E,1)),A.computeVertexNormals();const _=new cc(d.source);_.flipY=!1,_.colorSpace=Nn,_.anisotropy=8;const I=new pr({map:_,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||Lh.install(I);const D=new Mt(A,I);return D.receiveShadow=!s,D.castShadow=!s,{mesh:D,attribution:e.imagery.attribution,originElevationM:Number.isFinite(M)?M:void 0,...p?{water:p}:h?{waterLater:h}:{}}}class Np{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<Np.LOWEST_GROUND_M;let n=0;for(let s=0;s<t.length;s++)i(t[s])&&n++;for(let s=0;n>0&&s<Np.MAX_PASSES;s++){const r=[];for(let a=0;a<e;a++)for(let c=0;c<e;c++){const l=a*e+c;if(!i(t[l]))continue;let h=0,u=0;for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){const p=a+d,m=c+f;if(p<0||m<0||p>=e||m>=e)continue;const g=t[p*e+m];i(g)||(h+=g,u++)}u>0&&r.push([l,h/u])}for(const[a,c]of r)t[a]=c;if(n-=r.length,r.length===0)break}if(n>0)for(let s=0;s<t.length;s++)i(t[s])&&(t[s]=0)}}function LN(o,t,e){return Math.max(t,Math.min(e,o))}class Me{static STEP_M=8;stepM=Me.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new tt;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Xe;surveyed=new Xe;stated=new Xe;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(t){this.stepM=Number.isFinite(t)&&t>0?Math.min(Me.STEP_M,Math.max(1.5,t/2)):Me.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=Me.within(t,e,i,r);Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const l=new Map,h=c.map(f=>f.points.map(p=>ae(p.lat,p.lng,e,i))),u=c.map((f,p)=>this.streetOf(f,h[p],a));for(const[f,p]of c.entries()){const m=l.get(p.surface)??Me.batchFor(p.surface);l.set(p.surface,m);const g=u[f];this.appendPath(h[f],p.widthM,n,m,g?{lateralAt:(v,M,x,y)=>g(v,M,x,y).carriageway}:{})}for(const[f,p]of l){const m=this.meshOf(f,p,s);m&&this.surveyed.add(m)}const d=this.sidewalks(c,h,u,n);if(d.indices.length>0){const f=this.meshOf("paved",d,!1,Me.SIDEWALK_ALBEDO,!1);f&&(f.name="roads sidewalks",this.surveyed.add(f))}this.paint(c,e,i,n,s)}paint(t,e,i,n,s){if(!t.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(Me.markingsModule??=Et(()=>import("./RoadMarkings-DDNrriGo.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const c={positions:[],indices:[]};if(a.lay(t,e,i,(u,d,f)=>this.appendPath(u,d,n,c,{offsetM:f.offsetM,liftM:Me.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,Me.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=Me.MARKINGS_RENDER_ORDER,u.material.polygonOffsetFactor=-4,u.material.polygonOffsetUnits=-4,this.surveyed.add(u))}const h=a.barrierGeometry(a.barriers(t,e,i),n);if(h.indices.length>0){const u=this.meshOf("paved",h,s,Me.BARRIER_ALBEDO,!1);u&&(u.name="roads barriers",u.material.polygonOffset=!1,u.castShadow=!0,this.surveyed.add(u))}this.onMarkings?.()})}onMarkings;anchorGrain(t,e){if(this.grainReference){const n=ae(this.grainReference.lat,this.grainReference.lng,t,e);Math.hypot(n.x,n.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:t,lng:e};const i=ae(this.grainReference.lat,this.grainReference.lng,t,e);this.grainOrigin.set(-i.x,-i.z)}static within(t,e,i,n){if(!Number.isFinite(n))return t;const s=n*1.1+100;return t.filter(r=>{let a;for(const c of r.points){const l=ae(c.lat,c.lng,e,i);if(Math.hypot(l.x,l.z)<=s||a&&Math.hypot((l.x+a.x)/2,(l.z+a.z)/2)<=s)return!0;a=l}return!1})}streetOf(t,e,i){if(!t.urban||t.surface!=="paved")return;const n=Me.surveyedAcross(t);if(!i||!i.near(e))return()=>n;const s=new Map,r=(f,p,m,g)=>{const v=`${f.toFixed(2)}:${p.toFixed(2)}`;let M=s.get(v);return M||(M=i.across(f,p,m,g),s.set(v,M)),M},a=this.rungsOf(e),c=a.flatMap(f=>{const p=r(f.x,f.z,f.dirX,f.dirZ);return p.leftM!==void 0&&p.rightM!==void 0?[(p.leftM-p.rightM)/2]:[]}).sort((f,p)=>f-p),l=i.lampsAlong(e);if(c.length===0&&l.length===0)return()=>n;const h=c.length>0?c[Math.floor((c.length-1)/2)]:0,u=Me.clearOf(l,t.widthM/2,Math.max(-2.5,Math.min(Me.STREET_MIDDLE_MOST_M,h))),d={rungs:a,across:(f,p,m,g)=>Me.betweenWalls(t,u,r(f,p,m,g).leftM,r(f,p,m,g).rightM)};return this.laidStreets.push(d),(f,p,m,g)=>{const v=r(f,p,m,g);return Me.betweenWalls(t,u,v.leftM,v.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+Me.LAMP_CLEARANCE_M);if(n(i))return i;const s=Me.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*s;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=s&&n(a))return a;return i}atKerb(t,e){let i;for(const d of this.laidStreets)for(const f of d.rungs){const p=Math.hypot(t-f.x,e-f.z);p<=Me.KERB_REACH_M&&(!i||p<i.distance)&&(i={rung:f,across:d.across(f.x,f.z,f.dirX,f.dirZ),distance:p})}if(!i)return{x:t,z:e};const{rung:n,across:s}=i,r=(t-n.x)*-n.dirZ+(e-n.z)*n.dirX,a=(t-n.x)*n.dirX+(e-n.z)*n.dirZ,l=(r>=s.carriageway.offsetM?s.left:s.right)??s.left??s.right;if(!l)return{x:t,z:e};const h=Math.sign(l.outerM-l.kerbM),u=l.kerbM+h*Math.min(Me.LAMP_FROM_KERB_M,Math.abs(l.outerM-l.kerbM)/2);return{x:n.x+n.dirX*a-n.dirZ*u,z:n.z+n.dirZ*a+n.dirX*u}}rungsOf(t){const e=this.resample(t);return e.map((i,n)=>{const s=e[Math.max(0,n-1)],r=e[Math.min(e.length-1,n+1)],a=r.x-s.x,c=r.z-s.z,l=Math.hypot(a,c);return l<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/l,dirZ:c/l}})}static surveyedAcross(t){const e=t.widthM/2,i={offsetM:0,halfM:e};return t.widthM<Me.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+Me.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-Me.SIDEWALK_WIDTH_M}}}static betweenWalls(t,e,i,n){const s=t.widthM/2,r={offsetM:e,halfM:s},a=e+s,c=e-s,l=i??a+Me.SIDEWALK_WIDTH_M,h=-(n??-c+Me.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=Me.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...c-h>=Me.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:h}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new Wr(t,e);return t.forEach((a,c)=>{const l=i[c];if(!l)return;const h=(u,d)=>r.onAnotherCarriageway(u,d,c);for(const u of["left","right"]){const d=(f,p,m,g)=>{const v=l(f,p,m,g)[u];return v&&{offsetM:(v.kerbM+v.outerM)/2,halfM:Math.abs(v.outerM-v.kerbM)/2}};this.appendPath(e[c],0,n,s,{lateralAt:d,liftM:Me.LIFT_M+Me.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(e[c],n,s,(f,p,m,g)=>l(f,p,m,g)[u]?.kerbM,u==="left",h)}}),s}setStated(t,e){Me.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??Me.batchFor(n.surface);i.set(n.surface,s),this.appendPath(n.path.map(r=>({x:r.eastM,z:-r.northM})),n.widthM,e,s)}for(const[n,s]of i){const r=this.meshOf(n,s,!1);r&&this.stated.add(r)}}clear(){Me.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(t){for(const e of[...t.children]){t.remove(e);const i=e;i.geometry?.dispose(),i.material?.dispose()}}dispose(){Me.empty(this.surveyed),Me.empty(this.stated)}appendPath(t,e,i,n,s={}){const r=this.resample(t);if(r.length<2)return;const a=Math.max(s.minHalfM??.5,e/2),c=s.liftM??Me.LIFT_M,l=s.offsetM??0,h=n.positions.length/3,u=[],d=[],f=[];for(let m=0;m<r.length;m++){const g=r[Math.max(0,m-1)],v=r[Math.min(r.length-1,m+1)];let M=v.x-g.x,x=v.z-g.z;const y=Math.hypot(M,x);y<1e-6?(M=1,x=0):(M/=y,x/=y);const w=s.lateralAt?s.lateralAt(r[m].x,r[m].z,M,x):{offsetM:l,halfM:a},S=w?Math.max(s.minHalfM??.5,w.halfM):a,E=w?.offsetM??l,b=-x*S,A=M*S,_={x:r[m].x+-x*E,z:r[m].z+M*E};u.push(w!==void 0&&w.halfM>0&&!s.skip?.(_.x,_.z)),d.push([{x:_.x+b,z:_.z+A},_,{x:_.x-b,z:_.z-A}]),f.push(S)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const v=d[m][g],M=d[m+1][g],x=i((v.x+M.x)/2,(v.z+M.z)/2)-(p[m][g]+p[m+1][g])/2;x>0&&(p[m][g]+=x,p[m+1][g]+=x)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=h+m*3;n.indices.push(g,g+3,g+1,g+1,g+3,g+4),n.indices.push(g+1,g+4,g+2,g+2,g+4,g+5)}}appendKerb(t,e,i,n,s,r){const a=this.resample(t);if(a.length<2)return;const c=i.positions.length/3,l=[];for(let h=0;h<a.length;h++){const u=a[Math.max(0,h-1)],d=a[Math.min(a.length-1,h+1)];let f=d.x-u.x,p=d.z-u.z;const m=Math.hypot(f,p);m<1e-6?(f=1,p=0):(f/=m,p/=m);const g=n(a[h].x,a[h].z,f,p),v=a[h].x+-p*(g??0),M=a[h].z+f*(g??0);l.push(g!==void 0&&!r(v,M));const x=e(v,M)+Me.LIFT_M;i.positions.push(v,x,M,v,x+Me.SIDEWALK_KERB_M,M)}for(let h=0;h<a.length-1;h++){if(!l[h]||!l[h+1])continue;const u=c+h*2;s?i.indices.push(u,u+1,u+2,u+1,u+3,u+2):i.indices.push(u,u+2,u+1,u+1,u+2,u+3)}}static batchFor(t){return t==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(t,e,i,n,s=!0){if(e.indices.length===0)return;const r=new ye;r.setAttribute("position",new ve(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new ve(new Float32Array(e.edges),2)),r.setIndex(new ve(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??Me.ALBEDO[t],l=new pr({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?Me.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(l,Me.GRAIN_CONTRAST[t],a);const h=new Mt(r,l);return h.name=`roads ${t}`,h.renderOrder=Me.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(t,e,i=!1){const n=this.grainOrigin;t.onBeforeCompile=s=>{s.uniforms.uRoadOrigin={value:n},s.uniforms.uRoadContrast={value:e},i&&(s.defines={...s.defines,ROAD_VERGE:""}),s.vertexShader=s.vertexShader.replace("#include <common>",`#include <common>
|
|
7599
7599
|
varying vec2 vRoadXZ;
|
|
7600
7600
|
uniform vec2 uRoadOrigin;
|
|
7601
7601
|
#ifdef ROAD_VERGE
|
|
@@ -7642,7 +7642,7 @@ float roadNoise(vec2 p) {
|
|
|
7642
7642
|
if (fromEdge < reach) discard;
|
|
7643
7643
|
}
|
|
7644
7644
|
#endif
|
|
7645
|
-
}`)},t.customProgramCacheKey=()=>i?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1],a=Math.hypot(r.x-s.x,r.z-s.z),c=Math.max(1,Math.ceil(a/this.stepM));for(let l=0;l<c;l++){const h=l/c;e.push({x:s.x+(r.x-s.x)*h,z:s.z+(r.z-s.z)*h})}}const i=t[t.length-1];return i&&e.push({x:i.x,z:i.z}),e}}class Wr{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((i,n)=>{const s=t[n].widthM/2+.3;for(let r=1;r<i.length;r++){const a=i[r-1].x,c=i[r-1].z,l=i[r].x-a,h=i[r].z-c,u={way:n,ax:a,az:c,dx:l,dz:h,length2:l*l+h*h,reach:s},d=Math.floor((Math.min(a,i[r].x)-s)/Wr.CELL_M),f=Math.floor((Math.max(a,i[r].x)+s)/Wr.CELL_M),p=Math.floor((Math.min(c,i[r].z)-s)/Wr.CELL_M),m=Math.floor((Math.max(c,i[r].z)+s)/Wr.CELL_M);for(let g=d;g<=f;g++)for(let v=p;v<=m;v++){const M=Wr.key(g,v),x=this.cells.get(M);x?x.push(u):this.cells.set(M,[u])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,i){const n=this.cells.get(Wr.key(Math.floor(t/Wr.CELL_M),Math.floor(e/Wr.CELL_M)));if(!n)return!1;for(const s of n){if(s.way===i)continue;const r=s.length2===0?0:Math.max(0,Math.min(1,((t-s.ax)*s.dx+(e-s.az)*s.dz)/s.length2));if(Math.hypot(t-(s.ax+s.dx*r),e-(s.az+s.dz*r))<s.reach)return!0}return!1}}class Si{constructor(t,e=[]){this.lamps=e;for(const i of t){const n=Math.hypot(i.halfAlongM,i.halfAcrossM),s=Math.floor((i.x-n)/Si.CELL_M),r=Math.floor((i.x+n)/Si.CELL_M),a=Math.floor((i.z-n)/Si.CELL_M),c=Math.floor((i.z+n)/Si.CELL_M);for(let l=s;l<=r;l++)for(let h=a;h<=c;h++){const u=Si.key(l,h),d=this.cells.get(u);d?d.push(i):this.cells.set(u,[i])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,i,n){const s=[],r=[];for(const a of Si.SAMPLES_M){const c=t+i*a,l=e+n*a,h=this.wall(c,l,-n,i),u=this.wall(c,l,n,-i);h!==void 0&&s.push(h),u!==void 0&&r.push(u)}return{leftM:Si.agreed(s),rightM:Si.agreed(r)}}lampsAlong(t){const e=[];for(const i of this.lamps){let n;for(let s=1;s<t.length;s++){const r=t[s-1].x,a=t[s-1].z,c=t[s].x-r,l=t[s].z-a,h=c*c+l*l;if(h===0)continue;const u=((i.x-r)*c+(i.z-a)*l)/h;if(u<0||u>1)continue;const d=Math.sqrt(h),f=((i.x-r)*-l+(i.z-a)*c)/d;(!n||Math.abs(f)<n.distance)&&(n={distance:Math.abs(f),lateral:f})}n&&n.distance<=Si.REACH_M&&e.push(n.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=Si.REACH_M+Math.max(...Si.SAMPLES_M.map(Math.abs)),i=t.map(s=>s.x),n=t.map(s=>s.z);for(let s=Math.floor((Math.min(...i)-e)/Si.CELL_M);s<=Math.floor((Math.max(...i)+e)/Si.CELL_M);s++)for(let r=Math.floor((Math.min(...n)-e)/Si.CELL_M);r<=Math.floor((Math.max(...n)+e)/Si.CELL_M);r++)if(this.cells.has(Si.key(s,r)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,i)=>e-i),t[Math.floor((t.length-1)/2)]}wall(t,e,i,n){let s;const r=new Set,a=Si.CELL_M/2;for(let c=0;c<=Si.REACH_M+a;c+=a){const l=this.cells.get(Si.key(Math.floor((t+i*c)/Si.CELL_M),Math.floor((e+n*c)/Si.CELL_M)));for(const h of l??[]){if(r.has(h))continue;r.add(h);const u=Si.hit(h,t,e,i,n);u!==void 0&&u<=Si.REACH_M&&(s===void 0||u<s)&&(s=u)}}return s!==void 0&&s>=Si.NEAREST_M?s:void 0}static hit(t,e,i,n,s){const r=e-t.x,a=i-t.z,c=[r*t.alongX+a*t.alongZ,-r*t.alongZ+a*t.alongX],l=[n*t.alongX+s*t.alongZ,-n*t.alongZ+s*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let u=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(l[f])<1e-9){if(Math.abs(c[f])>h[f])return;continue}const p=(-h[f]-c[f])/l[f],m=(h[f]-c[f])/l[f];u=Math.max(u,Math.min(p,m)),d=Math.min(d,Math.max(p,m))}if(!(d<u||d<0||u<0))return u}static key(t,e){return(t+5e4)*100003+(e+5e4)}}const kN=js.catalog({en:()=>Et(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(o=>o.beamKindMessages_en),fr:()=>Et(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(o=>o.beamKindMessages_fr),es:()=>Et(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(o=>o.beamKindMessages_es),it:()=>Et(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(o=>o.beamKindMessages_it)}),Yw={key:"beams",messages:kN,pickKind:"beam",simulation:()=>Et(async()=>{const{BeamSystem:o}=await import("./BeamSystem-Bm8JAQ9L.js");return{BeamSystem:o}},__vite__mapDeps([6,7]),import.meta.url).then(({BeamSystem:o})=>()=>new o),editor:()=>Et(async()=>{const{BeamEditor:o}=await import("./BeamEditor-C1rw_f3H.js");return{BeamEditor:o}},__vite__mapDeps([8,7,1,9]),import.meta.url).then(({BeamEditor:o})=>(t,e,i)=>new o(t,e,i)),reachM:(o,t)=>
|
|
7645
|
+
}`)},t.customProgramCacheKey=()=>i?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1],a=Math.hypot(r.x-s.x,r.z-s.z),c=Math.max(1,Math.ceil(a/this.stepM));for(let l=0;l<c;l++){const h=l/c;e.push({x:s.x+(r.x-s.x)*h,z:s.z+(r.z-s.z)*h})}}const i=t[t.length-1];return i&&e.push({x:i.x,z:i.z}),e}}class Wr{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((i,n)=>{const s=t[n].widthM/2+.3;for(let r=1;r<i.length;r++){const a=i[r-1].x,c=i[r-1].z,l=i[r].x-a,h=i[r].z-c,u={way:n,ax:a,az:c,dx:l,dz:h,length2:l*l+h*h,reach:s},d=Math.floor((Math.min(a,i[r].x)-s)/Wr.CELL_M),f=Math.floor((Math.max(a,i[r].x)+s)/Wr.CELL_M),p=Math.floor((Math.min(c,i[r].z)-s)/Wr.CELL_M),m=Math.floor((Math.max(c,i[r].z)+s)/Wr.CELL_M);for(let g=d;g<=f;g++)for(let v=p;v<=m;v++){const M=Wr.key(g,v),x=this.cells.get(M);x?x.push(u):this.cells.set(M,[u])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,i){const n=this.cells.get(Wr.key(Math.floor(t/Wr.CELL_M),Math.floor(e/Wr.CELL_M)));if(!n)return!1;for(const s of n){if(s.way===i)continue;const r=s.length2===0?0:Math.max(0,Math.min(1,((t-s.ax)*s.dx+(e-s.az)*s.dz)/s.length2));if(Math.hypot(t-(s.ax+s.dx*r),e-(s.az+s.dz*r))<s.reach)return!0}return!1}}class Si{constructor(t,e=[]){this.lamps=e;for(const i of t){const n=Math.hypot(i.halfAlongM,i.halfAcrossM),s=Math.floor((i.x-n)/Si.CELL_M),r=Math.floor((i.x+n)/Si.CELL_M),a=Math.floor((i.z-n)/Si.CELL_M),c=Math.floor((i.z+n)/Si.CELL_M);for(let l=s;l<=r;l++)for(let h=a;h<=c;h++){const u=Si.key(l,h),d=this.cells.get(u);d?d.push(i):this.cells.set(u,[i])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,i,n){const s=[],r=[];for(const a of Si.SAMPLES_M){const c=t+i*a,l=e+n*a,h=this.wall(c,l,-n,i),u=this.wall(c,l,n,-i);h!==void 0&&s.push(h),u!==void 0&&r.push(u)}return{leftM:Si.agreed(s),rightM:Si.agreed(r)}}lampsAlong(t){const e=[];for(const i of this.lamps){let n;for(let s=1;s<t.length;s++){const r=t[s-1].x,a=t[s-1].z,c=t[s].x-r,l=t[s].z-a,h=c*c+l*l;if(h===0)continue;const u=((i.x-r)*c+(i.z-a)*l)/h;if(u<0||u>1)continue;const d=Math.sqrt(h),f=((i.x-r)*-l+(i.z-a)*c)/d;(!n||Math.abs(f)<n.distance)&&(n={distance:Math.abs(f),lateral:f})}n&&n.distance<=Si.REACH_M&&e.push(n.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=Si.REACH_M+Math.max(...Si.SAMPLES_M.map(Math.abs)),i=t.map(s=>s.x),n=t.map(s=>s.z);for(let s=Math.floor((Math.min(...i)-e)/Si.CELL_M);s<=Math.floor((Math.max(...i)+e)/Si.CELL_M);s++)for(let r=Math.floor((Math.min(...n)-e)/Si.CELL_M);r<=Math.floor((Math.max(...n)+e)/Si.CELL_M);r++)if(this.cells.has(Si.key(s,r)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,i)=>e-i),t[Math.floor((t.length-1)/2)]}wall(t,e,i,n){let s;const r=new Set,a=Si.CELL_M/2;for(let c=0;c<=Si.REACH_M+a;c+=a){const l=this.cells.get(Si.key(Math.floor((t+i*c)/Si.CELL_M),Math.floor((e+n*c)/Si.CELL_M)));for(const h of l??[]){if(r.has(h))continue;r.add(h);const u=Si.hit(h,t,e,i,n);u!==void 0&&u<=Si.REACH_M&&(s===void 0||u<s)&&(s=u)}}return s!==void 0&&s>=Si.NEAREST_M?s:void 0}static hit(t,e,i,n,s){const r=e-t.x,a=i-t.z,c=[r*t.alongX+a*t.alongZ,-r*t.alongZ+a*t.alongX],l=[n*t.alongX+s*t.alongZ,-n*t.alongZ+s*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let u=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(l[f])<1e-9){if(Math.abs(c[f])>h[f])return;continue}const p=(-h[f]-c[f])/l[f],m=(h[f]-c[f])/l[f];u=Math.max(u,Math.min(p,m)),d=Math.min(d,Math.max(p,m))}if(!(d<u||d<0||u<0))return u}static key(t,e){return(t+5e4)*100003+(e+5e4)}}const kN=js.catalog({en:()=>Et(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(o=>o.beamKindMessages_en),fr:()=>Et(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(o=>o.beamKindMessages_fr),es:()=>Et(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(o=>o.beamKindMessages_es),it:()=>Et(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(o=>o.beamKindMessages_it)}),Yw={key:"beams",messages:kN,pickKind:"beam",simulation:()=>Et(async()=>{const{BeamSystem:o}=await import("./BeamSystem-Bm8JAQ9L.js");return{BeamSystem:o}},__vite__mapDeps([6,7]),import.meta.url).then(({BeamSystem:o})=>()=>new o),editor:()=>Et(async()=>{const{BeamEditor:o}=await import("./BeamEditor-C1rw_f3H.js");return{BeamEditor:o}},__vite__mapDeps([8,7,1,9]),import.meta.url).then(({BeamEditor:o})=>(t,e,i)=>new o(t,e,i)),reachM:(o,t)=>Be.beamReachFor(o,t),describe:(o,t,{texts:e,name:i,distance:n})=>({name:i,detail:e.detail.replace("{name}",i).replace("{wavelength}",String(o.wavelengthNm)).replace("{power}",o.powerW.toLocaleString()).replace("{distance}",n(t.distanceM??0))})},UN=js.catalog({en:()=>Et(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(o=>o.launchKindMessages_en),fr:()=>Et(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(o=>o.launchKindMessages_fr),es:()=>Et(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(o=>o.launchKindMessages_es),it:()=>Et(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(o=>o.launchKindMessages_it)}),Kw={key:"launches",messages:UN,pickKind:"plume",simulation:()=>Et(async()=>{const{LaunchSimulation:o}=await import("./LaunchSimulation-3m1LUs2t.js");return{LaunchSimulation:o}},__vite__mapDeps([10,11]),import.meta.url).then(({LaunchSimulation:o})=>()=>new o),editor:()=>Et(async()=>{const{LaunchEditor:o}=await import("./LaunchEditor-BLkzRUDz.js");return{LaunchEditor:o}},__vite__mapDeps([12,1,11,9]),import.meta.url).then(({LaunchEditor:o})=>(t,e,i)=>new o(t,e,i)),describe:(o,t,{said:e,texts:i,distance:n})=>{const s=t.detail,r=e.read(o.title)||o.vehicle?.mission||i.name,a=s.release===void 0||s.release==="burn"?void 0:o.jets?.find((l,h)=>`jet:${l.id??h}`===s.release),c=s.release===void 0||s.release==="burn"?i.ascent:a?.kind==="vent"?i.vent:i.burn;return{name:r,detail:i.detail.replace("{name}",r).replace("{part}",c).replace("{distance}",n(s.centre.distanceKm*1e3)).replace("{height}",Math.round(s.heightKm??0).toLocaleString())}}},FN=js.catalog({en:()=>Et(()=>import("./ReentryKindMessages_en-Cbgk3paQ.js"),[],import.meta.url).then(o=>o.reentryKindMessages_en),fr:()=>Et(()=>import("./ReentryKindMessages_fr-D9r9x2bK.js"),[],import.meta.url).then(o=>o.reentryKindMessages_fr),es:()=>Et(()=>import("./ReentryKindMessages_es-DwgJQanC.js"),[],import.meta.url).then(o=>o.reentryKindMessages_es),it:()=>Et(()=>import("./ReentryKindMessages_it-DQ-J5YpD.js"),[],import.meta.url).then(o=>o.reentryKindMessages_it)}),qw={key:"reentries",messages:FN,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>Et(async()=>{const{ReentrySimulation:o}=await import("./ReentrySimulation-BfkUcIGM.js");return{ReentrySimulation:o}},[],import.meta.url).then(({ReentrySimulation:o})=>()=>new o),editor:()=>Et(async()=>{const{ReentryEditor:o}=await import("./ReentryEditor-C5dzOj_i.js");return{ReentryEditor:o}},__vite__mapDeps([13,1,9]),import.meta.url).then(({ReentryEditor:o})=>(t,e,i)=>new o(t,e,i)),describe:(o,t,{said:e,texts:i})=>{const n=t.detail,s=(o.title?e.read(o.title):"")||o.object?.name||i.name,r=n.view.head,a=6371,c=Math.sqrt(a**2+r.distanceKm**2+2*a*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-a;return{name:(n.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",s).replace("{mag}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(c).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},Kv=Ae.point("skyEvents").provide(Ae.BUILT_IN,[{id:Kw.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Kw},{id:Yw.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Yw},{id:qw.key,name:"Fireballs",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>qw}]);class to{static built=new WeakMap;static of(t){let e=to.built.get(t);return e||(e=t.create(),to.built.set(t,e)),e}static eventsOf(t,e){const i=t?.[e.key];return Array.isArray(i)?i:[]}}const zN=18,BN=.55,HN=.5,GN=.4,VN=2,WN=`
|
|
7646
7646
|
attribute float aSpeed;
|
|
7647
7647
|
uniform float uTime;
|
|
7648
7648
|
uniform float uOverallSpeed;
|
|
@@ -8654,7 +8654,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
8654
8654
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
8655
8655
|
}
|
|
8656
8656
|
`,transparent:!0,depthWrite:!1,side:bn,fog:!1,blending:Zc,blendSrc:Jc,blendDst:Ud})}static wallReflectance(t,e,i){const n=i(t,1,e);return 2*n/(1+n)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return Ft.respond(e*Ft.relativeOfResponse(Math.max(t,1e-5)))}}class As{static SIZE=64;static MOVE_M=.01;holder=new Pi;cameras=[];faces=[];target=new qe(As.SIZE,As.SIZE);white=new Ms({color:new rt(1,1,1),side:bn});scene=new Zs;cabin;meshes=0;eye=new R;scratch=new R;constructor(){const t=[[new R(1,0,0),new R(0,1,0)],[new R(-1,0,0),new R(0,1,0)],[new R(0,1,0),new R(0,0,1)],[new R(0,-1,0),new R(0,0,-1)],[new R(0,0,1),new R(0,1,0)],[new R(0,0,-1),new R(0,1,0)]];for(const[e,i]of t){const n=new Wn(90,1,.02,20);n.up.copy(i),n.lookAt(e),this.holder.add(n),this.cameras.push(n),this.faces.push(new Uint8Array(As.SIZE*As.SIZE*4))}this.scene.background=new rt(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,i){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const n=this.scratch.copy(i);e.worldToLocal(n);let s=0;e.traverse(r=>{r.isMesh&&s++}),!(e===this.cabin&&s===this.meshes&&n.distanceTo(this.eye)<As.MOVE_M)&&(this.cabin=e,this.meshes=s,this.eye.copy(n),this.draw(t,e))}hides(t){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let e=0;e<6;e++){const i=this.cameras[e],n=this.scratch.copy(t).transformDirection(i.matrixWorldInverse);if(n.z>=0)continue;const s=n.x/-n.z,r=n.y/-n.z;if(Math.abs(s)>1||Math.abs(r)>1)continue;const a=Math.min(As.SIZE-1,Math.floor((s+1)/2*As.SIZE)),c=Math.min(As.SIZE-1,Math.floor((r+1)/2*As.SIZE));return this.faces[e][(c*As.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(t,e){e.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];e.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof no))return;const l=new Mt(a.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(a.matrixWorld),l.matrixWorld.copy(a.matrixWorld),i.push(l)});for(const r of i)this.scene.add(r);const n=t.getRenderTarget(),s=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,a),t.readRenderTargetPixels(this.target,0,0,As.SIZE,As.SIZE,this.faces[r])}t.setRenderTarget(n),t.shadowMap.autoUpdate=s;for(const r of i)r.removeFromParent()}}const zg="https://ufoathome.org/models/index.json";class sd{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??I8()}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(`
|
|
8657
|
-
`);let e=sd.shared.get(t);return e||(e=this.fetchFirstAvailable(),sd.shared.set(t,e),e.then(i=>{i.length===0&&sd.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 I8(){const o=`?v=${encodeURIComponent("0.170.
|
|
8657
|
+
`);let e=sd.shared.get(t);return e||(e=this.fetchFirstAvailable(),sd.shared.set(t,e),e.then(i=>{i.length===0&&sd.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 I8(){const o=`?v=${encodeURIComponent("0.170.1")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==zg?[t,zg]:[zg]).map(e=>e+o)}const D8=Ae.point("decorModels").provide(Ae.BUILT_IN,[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new sd}]);class GA{constructor(t,e=D8){this.preferredId=t,this.sources=e}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const t=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(t?[t,...this.sources.filter(i=>i!==t)]:[]).map(i=>{let n=this.built.get(i);return n||(n=i.create(),this.built.set(i,n)),n})}entries(t){const e=this.catalogues()[0];return e?e.entries(t):Promise.resolve([])}async entry(t){for(const e of this.catalogues()){const i=await e.entry(t).catch(()=>{});if(i)return i}}async moduleOf(t){const e=Ae.point("decorModels");for(const i of this.sources){const n=e.ownerOf(i.id);if(!(n===void 0||n===Ae.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return n}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function Bg(o){const{GLTFLoader:t}=await Et(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-C8rVdDv7.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 VA=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class $s{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new Mt(new os(2,2),new Re({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:$s.VERTEX,fragmentShader:$s.FRAGMENT,transparent:!0,depthWrite:!1,blending:_n,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*$s.MIN_ANGLE_RAD),r=$s.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min($s.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/($s.MAX_SHARE*$s.FILL*Math.PI))}static VERTEX=`
|
|
8658
8658
|
uniform float uRadius;
|
|
8659
8659
|
varying vec2 vOffset;
|
|
8660
8660
|
void main() {
|
|
@@ -9263,7 +9263,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
9263
9263
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
9264
9264
|
gl_FragColor = vec4(light, 1.0);
|
|
9265
9265
|
}
|
|
9266
|
-
`,transparent:!0,blending:_n,depthWrite:!1,side:Oi,fog:!1});this.object=new Mt(new an(cy.RADIUS,128,32,0,Math.PI*2,0,Ue.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Ue.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=kn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=kn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class Up{constructor(t){this.generator=t}static SIZE=128;target=new Xd(Up.SIZE,{type:We,generateMipmaps:!0,minFilter:qs,magFilter:ge});camera=new $M(.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 l=c;l.isLight&&l.castShadow&&l.shadow&&!l.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,l)=>{c.visible=a[l]}),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 Qn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Qn.install(),this.generator=new xv(t),this.eye=new Up(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=Qn.REFRESH_MS){for(const g of[...this.probes.keys()])n.some(v=>v.id===g&&v.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const u=[{probe:this.eye}];for(const g of n){if(!g.shiny)continue;let v=this.probes.get(g.id);v||(v=new Up(this.generator),this.probes.set(g.id,v)),u.push({probe:v,reflector:g})}const d=performance.now(),f=()=>u.filter(({probe:g})=>g.capturedVersion!==a),p=f().filter(({probe:g})=>d-g.capturedAtMs>=h);if(p.length>0){const g=p.reduce((v,M)=>M.probe.capturedAtMs<v.probe.capturedAtMs?M:v);if(g.reflector){const v=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,v,[g.reflector.holder,...s]),Qn.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),l?.(g.probe.sharp),Qn.decor=g.probe.filtered;for(const v of r)Qn.reflectOn(v,g.probe);for(const v of n)v.shiny||Qn.reflectOn(v.holder,g.probe)}g.probe.capturedVersion=a}const m=f();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:g})=>h-(d-g.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:Qn.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof no?e.sharp&&s.setSurroundings(e.sharp):s instanceof Fo&&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(Qn.installed)return;Qn.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!he.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}he.lights_fragment_maps=he.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const YA=0,P8=1,N8=2,pb=2,Hg=1.25,mb=1,ns=32,Sn=ns/4,KA=65535,K0=Math.pow(2,-24),ly=Symbol("SKIP_GENERATION"),qA={strategy:YA,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[ly]:!1};function Yi(o,t,e){return e.min.x=t[o],e.min.y=t[o+1],e.min.z=t[o+2],e.max.x=t[o+3],e.max.y=t[o+4],e.max.z=t[o+5],e}function tM(o){let t=-1,e=-1/0;for(let i=0;i<3;i++){const n=o[i+3]-o[i];n>e&&(e=n,t=i)}return t}function gb(o,t){t.set(o)}function vb(o,t,e){let i,n;for(let s=0;s<3;s++){const r=s+3;i=o[s],n=t[s],e[s]=i<n?i:n,i=o[r],n=t[r],e[r]=i>n?i:n}}function n0(o,t,e){for(let i=0;i<3;i++){const n=t[o+2*i],s=t[o+2*i+1],r=n-s,a=n+s;r<e[i]&&(e[i]=r),a>e[i+3]&&(e[i+3]=a)}}function _u(o){const t=o[3]-o[0],e=o[4]-o[1],i=o[5]-o[2];return 2*(t*e+e*i+i*t)}function sn(o,t){return t[o+15]===KA}function Un(o,t){return t[o+6]}function ss(o,t){return t[o+14]}function En(o){return o+Sn}function An(o,t){const e=t[o+6];return o+e*Sn}function hy(o,t){return t[o+7]}function Gg(o,t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,g=-1/0;const v=o.offset||0;for(let M=(t-v)*6,x=(t+e-v)*6;M<x;M+=6){const y=o[M+0],w=o[M+1],S=y-w,E=y+w;S<s&&(s=S),E>c&&(c=E),y<u&&(u=y),y>p&&(p=y);const b=o[M+2],A=o[M+3],_=b-A,I=b+A;_<r&&(r=_),I>l&&(l=I),b<d&&(d=b),b>m&&(m=b);const D=o[M+4],O=o[M+5],L=D-O,P=D+O;L<a&&(a=L),P>h&&(h=P),D<f&&(f=D),D>g&&(g=D)}i[0]=s,i[1]=r,i[2]=a,i[3]=c,i[4]=l,i[5]=h,n[0]=u,n[1]=d,n[2]=f,n[3]=p,n[4]=m,n[5]=g}const Ha=32,L8=(o,t)=>o.candidate-t.candidate,Eo=new Array(Ha).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),s0=new Float32Array(6);function k8(o,t,e,i,n,s){let r=-1,a=0;if(s===YA)r=tM(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(s===P8)r=tM(o),r!==-1&&(a=U8(e,i,n,r));else if(s===N8){const c=_u(o);let l=Hg*n;const h=e.offset||0,u=(i-h)*6,d=(i+n-h)*6;for(let f=0;f<3;f++){const p=t[f],v=(t[f+3]-p)/Ha;if(n<Ha/4){const M=[...Eo];M.length=n;let x=0;for(let w=u;w<d;w+=6,x++){const S=M[x];S.candidate=e[w+2*f],S.count=0;const{bounds:E,leftCacheBounds:b,rightCacheBounds:A}=S;for(let _=0;_<3;_++)A[_]=1/0,A[_+3]=-1/0,b[_]=1/0,b[_+3]=-1/0,E[_]=1/0,E[_+3]=-1/0;n0(w,e,E)}M.sort(L8);let y=n;for(let w=0;w<y;w++){const S=M[w];for(;w+1<y&&M[w+1].candidate===S.candidate;)M.splice(w+1,1),y--}for(let w=u;w<d;w+=6){const S=e[w+2*f];for(let E=0;E<y;E++){const b=M[E];S>=b.candidate?n0(w,e,b.rightCacheBounds):(n0(w,e,b.leftCacheBounds),b.count++)}}for(let w=0;w<y;w++){const S=M[w],E=S.count,b=n-S.count,A=S.leftCacheBounds,_=S.rightCacheBounds;let I=0;E!==0&&(I=_u(A)/c);let D=0;b!==0&&(D=_u(_)/c);const O=mb+Hg*(I*E+D*b);O<l&&(r=f,l=O,a=S.candidate)}}else{for(let y=0;y<Ha;y++){const w=Eo[y];w.count=0,w.candidate=p+v+y*v;const S=w.bounds;for(let E=0;E<3;E++)S[E]=1/0,S[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/v);E>=Ha&&(E=Ha-1);const b=Eo[E];b.count++,n0(y,e,b.bounds)}const M=Eo[Ha-1];gb(M.bounds,M.rightCacheBounds);for(let y=Ha-2;y>=0;y--){const w=Eo[y],S=Eo[y+1];vb(w.bounds,S.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let y=0;y<Ha-1;y++){const w=Eo[y],S=w.count,E=w.bounds,A=Eo[y+1].rightCacheBounds;S!==0&&(x===0?gb(E,s0):vb(E,s0,s0)),x+=S;let _=0,I=0;x!==0&&(_=_u(s0)/c);const D=n-x;D!==0&&(I=_u(A)/c);const O=mb+Hg*(_*x+I*D);O<l&&(r=f,l=O,a=w.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function U8(o,t,e,i){let n=0;const s=o.offset;for(let r=t,a=t+e;r<a;r++)n+=o[(r-s)*6+i*2];return n/e}class Vg{constructor(){this.boundingData=new Float32Array(6)}}function F8(o,t,e,i,n,s){let r=i,a=i+n-1;const c=s.pos,l=s.axis*2,h=e.offset||0;for(;;){for(;r<=a&&e[(r-h)*6+l]<c;)r++;for(;r<=a&&e[(a-h)*6+l]>=c;)a--;if(r<a){for(let u=0;u<t;u++){let d=o[r*t+u];o[r*t+u]=o[a*t+u],o[a*t+u]=d}for(let u=0;u<6;u++){const d=r-h,f=a-h,p=e[d*6+u];e[d*6+u]=e[f*6+u],e[f*6+u]=p}r++,a--}else return r}}let ZA,q0,eM,JA;const z8=Math.pow(2,32);function iM(o){return"count"in o?1:1+iM(o.left)+iM(o.right)}function B8(o,t,e){return ZA=new Float32Array(e),q0=new Uint32Array(e),eM=new Uint16Array(e),JA=new Uint8Array(e),nM(o,t)}function nM(o,t){const e=o/4,i=o/2,n="count"in t,s=t.boundingData;for(let r=0;r<6;r++)ZA[e+r]=s[r];if(n)return t.buffer?(JA.set(new Uint8Array(t.buffer),o),o+t.buffer.byteLength):(q0[e+6]=t.offset,eM[i+14]=t.count,eM[i+15]=KA,o+ns);{const{left:r,right:a,splitAxis:c}=t,l=o+ns;let h=nM(l,r);const u=o/ns,f=h/ns-u;if(f>z8)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return q0[e+6]=f,q0[e+7]=c,nM(h,a)}}function H8(o,t,e,i,n,s){const{maxDepth:r,verbose:a,targetLeafSize:c,_strictLeafSize:l=1/0,strategy:h,onProgress:u}=n,d=o.primitiveBuffer,f=o.primitiveBufferStride,p=new Float32Array(6);let m=!1;const g=new Vg;return Gg(t,e,i,g.boundingData,p),M(g,e,i,p),g;function v(x){u&&u((x-s.offset)/s.count)}function M(x,y,w,S=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const b=w>l;if(w<=c&&!b||E>=r)return v(y+w),x.offset=y,x.count=w,x;const A=k8(x.boundingData,S,t,y,w,h);let _=A.axis===-1?-1:F8(d,f,t,y,w,A);if(A.axis===-1||_===y||_===y+w){if(!b)return v(y+w),x.offset=y,x.count=w,x;A.axis=Math.max(0,tM(x.boundingData)),_=y+Math.max(1,Math.floor(w/2))}x.splitAxis=A.axis;const I=new Vg,D=y,O=_-y;x.left=I,Gg(t,D,O,I.boundingData,p),M(I,D,O,p,E+1);const L=new Vg,P=_,k=w-O;return x.right=L,Gg(t,P,k,L.boundingData,p),M(L,P,k,p,E+1),x}}function G8(o,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=o.getRootRanges(t.range),n=i[0],s=i[i.length-1],r={offset:n.offset,count:s.offset+s.count-n.offset},a=new Float32Array(6*r.count);a.offset=r.offset,o.computePrimitiveBounds(r.offset,r.count,a),o._roots=i.map(c=>{const l=H8(o,a,c.offset,c.count,t,r),h=iM(l),u=new e(ns*h);return B8(0,l,u),u})}class uy{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class V8{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const Ni=new V8;let Jo,mh;const kl=[],r0=new uy(()=>new Ke);function W8(o,t,e,i,n,s){Jo=r0.getPrimitive(),mh=r0.getPrimitive(),kl.push(Jo,mh),Ni.setBuffer(o._roots[t]);const r=sM(0,o.geometry,e,i,n,s);Ni.clearBuffer(),r0.releasePrimitive(Jo),r0.releasePrimitive(mh),kl.pop(),kl.pop();const a=kl.length;return a>0&&(mh=kl[a-1],Jo=kl[a-2]),r}function sM(o,t,e,i,n=null,s=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:l}=Ni;let h=o*2;if(sn(h,c)){const d=Un(o,l),f=ss(h,c);return Yi(o,a,Jo),i(d,f,!1,r,s+o/Sn,Jo)}else{let _=function(D){const{uint16Array:O,uint32Array:L}=Ni;let P=D*2;for(;!sn(P,O);)D=En(D),P=D*2;return Un(D,L)},I=function(D){const{uint16Array:O,uint32Array:L}=Ni;let P=D*2;for(;!sn(P,O);)D=An(D,L),P=D*2;return Un(D,L)+ss(P,O)};const d=En(o),f=An(o,l);let p=d,m=f,g,v,M,x;if(n&&(M=Jo,x=mh,Yi(p,a,M),Yi(m,a,x),g=n(M),v=n(x),v<g)){p=f,m=d;const D=g;g=v,v=D,M=x}M||(M=Jo,Yi(p,a,M));const y=sn(p*2,c),w=e(M,y,g,r+1,s+p/Sn);let S;if(w===pb){const D=_(p),L=I(p)-D;S=i(D,L,!0,r+1,s+p/Sn,M)}else S=w&&sM(p,t,e,i,n,s,r+1);if(S)return!0;x=mh,Yi(m,a,x);const E=sn(m*2,c),b=e(x,E,v,r+1,s+m/Sn);let A;if(b===pb){const D=_(m),L=I(m)-D;A=i(D,L,!0,r+1,s+m/Sn,x)}else A=b&&sM(m,t,e,i,n,s,r+1);return!!A}}const ad=new Ni.constructor,Fp=new Ni.constructor,No=new uy(()=>new Ke),Ul=new Ke,Fl=new Ke,Wg=new Ke,Xg=new Ke;let $g=!1;function X8(o,t,e,i){if($g)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");$g=!0;const n=o._roots,s=t._roots;let r,a=0,c=0;const l=new Wt().copy(e).invert();for(let h=0,u=n.length;h<u;h++){ad.setBuffer(n[h]),c=0;const d=No.getPrimitive();Yi(0,ad.float32Array,d),d.applyMatrix4(l);for(let f=0,p=s.length;f<p&&(Fp.setBuffer(s[f]),r=Mr(0,0,e,l,i,a,c,0,0,d),Fp.clearBuffer(),c+=s[f].byteLength/ns,!r);f++);if(No.releasePrimitive(d),ad.clearBuffer(),a+=n[h].byteLength/ns,r)break}return $g=!1,r}function Mr(o,t,e,i,n,s=0,r=0,a=0,c=0,l=null,h=!1){let u,d;h?(u=Fp,d=ad):(u=ad,d=Fp);const f=u.float32Array,p=u.uint32Array,m=u.uint16Array,g=d.float32Array,v=d.uint32Array,M=d.uint16Array,x=o*2,y=t*2,w=sn(x,m),S=sn(y,M);let E=!1;if(S&&w)h?E=n(Un(t,v),ss(t*2,M),Un(o,p),ss(o*2,m),c,r+t/Sn,a,s+o/Sn):E=n(Un(o,p),ss(o*2,m),Un(t,v),ss(t*2,M),a,s+o/Sn,c,r+t/Sn);else if(S){const b=No.getPrimitive();Yi(t,g,b),b.applyMatrix4(e);const A=En(o),_=An(o,p);Yi(A,f,Ul),Yi(_,f,Fl);const I=b.intersectsBox(Ul),D=b.intersectsBox(Fl);E=I&&Mr(t,A,i,e,n,r,s,c,a+1,b,!h)||D&&Mr(t,_,i,e,n,r,s,c,a+1,b,!h),No.releasePrimitive(b)}else{const b=En(t),A=An(t,v);Yi(b,g,Wg),Yi(A,g,Xg);const _=l.intersectsBox(Wg),I=l.intersectsBox(Xg);if(_&&I)E=Mr(o,b,e,i,n,s,r,a,c+1,l,h)||Mr(o,A,e,i,n,s,r,a,c+1,l,h);else if(_)if(w)E=Mr(o,b,e,i,n,s,r,a,c+1,l,h);else{const D=No.getPrimitive();D.copy(Wg).applyMatrix4(e);const O=En(o),L=An(o,p);Yi(O,f,Ul),Yi(L,f,Fl);const P=D.intersectsBox(Ul),k=D.intersectsBox(Fl);E=P&&Mr(b,O,i,e,n,r,s,c,a+1,D,!h)||k&&Mr(b,L,i,e,n,r,s,c,a+1,D,!h),No.releasePrimitive(D)}else if(I)if(w)E=Mr(o,A,e,i,n,s,r,a,c+1,l,h);else{const D=No.getPrimitive();D.copy(Xg).applyMatrix4(e);const O=En(o),L=An(o,p);Yi(O,f,Ul),Yi(L,f,Fl);const P=D.intersectsBox(Ul),k=D.intersectsBox(Fl);E=P&&Mr(A,O,i,e,n,r,s,c,a+1,D,!h)||k&&Mr(A,L,i,e,n,r,s,c,a+1,D,!h),No.releasePrimitive(D)}}return E}const Yg=new class{constructor(){let o=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(s,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=o=s._roots[r],this.uint16Array=e=new Uint16Array(o),this.uint32Array=t=new Uint32Array(o)},this.reset=()=>{this.root=null,this.buffer=o=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=s=>{let r=s*2;for(;!sn(r,e);)s=En(s),r=s*2;return Un(s,t)},this.getRangeEnd=s=>{let r=s*2;for(;!sn(r,e);)s=An(s,t),r=s*2;return Un(s,t)+ss(r,e)};const n=(s,r,a)=>{const c=r*2,l=sn(c,e);if(!s(a,l,r)&&!l){const u=En(r),d=An(r,t);n(s,u,a+1),n(s,d,a+1)}};this.traverseBuffer=s=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{n(s,0,0)}finally{i=!1}},this.traverse=s=>{this.traverseBuffer((r,a,c)=>{if(a){const l=c*2,h=t[c+6],u=e[l+14];return s(r,a,new Float32Array(o,c*4,6),h,u)}else{const l=hy(c,t);return s(r,a,new Float32Array(o,c*4,6),l)}})}}},Mb=new Ke,zl=new Float32Array(6);class $8{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...qA,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),G8(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0;for(let u=t,d=t+e;u<d;u++){this.writePrimitiveBounds(u,zl,0);const[f,p,m,g,v,M]=zl;f<s&&(s=f),g>c&&(c=g),p<r&&(r=p),v>l&&(l=v),m<a&&(a=m),M>h&&(h=M)}return i[n+0]=s,i[n+1]=r,i[n+2]=a,i[n+3]=c,i[n+4]=l,i[n+5]=h,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,zl,0);const[a,c,l,h,u,d]=zl,f=(a+h)/2,p=(c+u)/2,m=(l+d)/2,g=(h-a)/2,v=(u-c)/2,M=(d-l)/2,x=(s-n)*6;i[x+0]=f,i[x+1]=g+(Math.abs(f)+g)*K0,i[x+2]=p,i[x+3]=v+(Math.abs(p)+v)*K0,i[x+4]=m,i[x+5]=M+(Math.abs(m)+M)*K0}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const i=this._roots;for(let n=0;n<i.length;n++){const s=i[n],r=new Uint32Array(s),a=new Uint16Array(s),c=s.byteLength/ns;for(let l=0;l<c;l++){const h=Sn*l,u=2*h;sn(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){Yg.setBVH(this,e),Yg.traverse(t),Yg.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const n=t[e],s=new Uint32Array(n),r=new Uint16Array(n),a=new Float32Array(n),c=n.byteLength/ns;for(let l=c-1;l>=0;l--){const h=l*Sn,u=h*2;if(sn(u,r)){const f=Un(h,s),p=ss(u,r);this.writePrimitiveRangeBounds(f,p,zl,0),a.set(zl,h)}else{const f=En(h),p=An(h,s);for(let m=0;m<3;m++){const g=a[f+m],v=a[f+m+3],M=a[p+m],x=a[p+m+3];a[h+m]=g<M?g:M,a[h+m+3]=v>x?v:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{Yi(0,new Float32Array(i),Mb),t.union(Mb)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:a}=t;if(n&&s){const u=n;n=(d,f,p,m,g)=>u(d,f,p,m,g)?!0:a(d,f,this,s,p,m,r)}else n||(s?n=(u,d,f,p)=>a(u,d,this,s,f,p,r):n=(u,d,f)=>f);let c=!1,l=0;const h=this._roots;for(let u=0,d=h.length;u<d;u++){const f=h[u];if(c=W8(this,u,i,n,e,l),c)break;l+=f.byteLength/ns}return c}bvhcast(t,e,i){let{intersectsRanges:n}=i;return X8(this,t,e,n)}}function Y8(){return typeof SharedArrayBuffer<"u"}function dy(o){return o.index?o.index.count:o.attributes.position.count}function gm(o){return dy(o)/3}function K8(o,t=ArrayBuffer){return o>65535?new Uint32Array(new t(4*o)):new Uint16Array(new t(2*o))}function q8(o,t){if(!o.index){const e=o.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=K8(e,i);o.setIndex(new ve(n,1));for(let s=0;s<e;s++)n[s]=s}}function Z8(o,t,e){const i=dy(o)/e,n=t||o.drawRange,s=n.start/e,r=(n.start+n.count)/e,a=Math.max(0,s),c=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function J8(o,t){return o.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function yb(o,t,e){const i=Z8(o,t,e),n=J8(o,e);if(!n.length)return[i];const s=[],r=i.offset,a=i.offset+i.count,c=dy(o)/e,l=[];for(const d of n){const{offset:f,count:p}=d,m=f,g=isFinite(p)?p:c-f,v=f+g;m<a&&v>r&&(l.push({pos:Math.max(r,m),isStart:!0}),l.push({pos:Math.min(a,v),isStart:!1}))}l.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,u=null;for(const d of l){const f=d.pos;h!==0&&f!==u&&s.push({offset:u,count:f-u}),h+=d.isStart?1:-1,u=f}return s}function j8(o,t){const e=o[o.length-1],i=e.offset+e.count>2**16,n=o.reduce((l,h)=>l+h.count,0),s=i?4:2,r=t?new SharedArrayBuffer(n*s):new ArrayBuffer(n*s),a=i?new Uint32Array(r):new Uint16Array(r);let c=0;for(let l=0;l<o.length;l++){const{offset:h,count:u}=o[l];for(let d=0;d<u;d++)a[c+d]=h+d;c+=u}return a}class Q8 extends $8{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Y8())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...qA,...e},e[ly]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=yb(e,t.range,i),s=j8(n,t.useSharedArrayBuffer);this._indirectBuffer=s}else q8(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Ke))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:yb(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class oo{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const c=t[s][e];i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const a=e[s],c=t.dot(a);i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}oo.prototype.setFromBox=(function(){const o=new R;return function(e,i){const n=i.min,s=i.max;let r=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let l=0;l<=1;l++)for(let h=0;h<=1;h++){o.x=n.x*c+s.x*(1-c),o.y=n.y*l+s.y*(1-l),o.z=n.z*h+s.z*(1-h);const u=e.dot(o);r=Math.min(u,r),a=Math.max(u,a)}this.min=r,this.max=a}})();const tL=(function(){const o=new R,t=new R,e=new R;return function(n,s,r){const a=n.start,c=o,l=s.start,h=t;e.subVectors(a,l),o.subVectors(n.end,n.start),t.subVectors(s.end,s.start);const u=e.dot(h),d=h.dot(c),f=h.dot(h),p=e.dot(c),g=c.dot(c)*f-d*d;let v,M;g!==0?v=(u*d-p*f)/g:v=0,M=(u+v*d)/f,r.x=v,r.y=M}})(),fy=(function(){const o=new tt,t=new R,e=new R;return function(n,s,r,a){tL(n,s,o);let c=o.x,l=o.y;if(c>=0&&c<=1&&l>=0&&l<=1){n.at(c,r),s.at(l,a);return}else if(c>=0&&c<=1){l<0?s.at(0,a):s.at(1,a),n.closestPointToPoint(a,!0,r);return}else if(l>=0&&l<=1){c<0?n.at(0,r):n.at(1,r),s.closestPointToPoint(r,!0,a);return}else{let h;c<0?h=n.start:h=n.end;let u;l<0?u=s.start:u=s.end;const d=t,f=e;if(n.closestPointToPoint(u,!0,t),s.closestPointToPoint(h,!0,e),d.distanceToSquared(u)<=f.distanceToSquared(h)){r.copy(d),a.copy(u);return}else{r.copy(h),a.copy(f);return}}}})(),eL=(function(){const o=new R,t=new R,e=new _r,i=new ro;return function(s,r){const{radius:a,center:c}=s,{a:l,b:h,c:u}=r;if(i.start=l,i.end=h,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a||(i.start=l,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a))return!0;const m=r.getPlane(e);if(Math.abs(m.distanceToPoint(c))<=a){const v=m.projectPoint(c,t);if(r.containsPoint(v))return!0}return!1}})(),iL=["x","y","z"],Va=1e-15,xb=Va*Va;function ir(o){return Math.abs(o)<Va}class Pr extends Ln{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new R),this.satBounds=new Array(4).fill().map(()=>new oo),this.points=[this.a,this.b,this.c],this.plane=new _r,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new ro,this.needsUpdate=!0}intersectsSphere(t){return eL(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,a=s[0],c=r[0];this.getNormal(a),c.setFromPoints(a,n);const l=s[1],h=r[1];l.subVectors(t,e),h.setFromPoints(l,n);const u=s[2],d=r[2];u.subVectors(e,i),d.setFromPoints(u,n);const f=s[3],p=r[3];f.subVectors(i,t),p.setFromPoints(f,n);const m=l.length(),g=u.length(),v=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Va?g<Va||v<Va?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):g<Va?v<Va?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):v<Va&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}Pr.prototype.closestPointToSegment=(function(){const o=new R,t=new R,e=new ro;return function(n,s=null,r=null){const{start:a,end:c}=n,l=this.points;let h,u=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(l[d]),e.end.copy(l[f]),fy(e,n,o,t),h=o.distanceToSquared(t),h<u&&(u=h,s&&s.copy(o),r&&r.copy(t))}return this.closestPointToPoint(a,o),h=a.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(a)),this.closestPointToPoint(c,o),h=c.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(c)),Math.sqrt(u)}})();Pr.prototype.intersectsTriangle=(function(){const o=new Pr,t=new oo,e=new oo,i=new R,n=new R,s=new R,r=new R,a=new ro,c=new ro,l=new R,h=new tt,u=new tt;function d(x,y,w,S){const E=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?E.copy(x.plane.normal):E.copy(y.plane.normal);const b=x.satBounds,A=x.satAxes;for(let D=1;D<4;D++){const O=b[D],L=A[D];if(t.setFromPoints(L,y.points),O.isSeparated(t)||(r.copy(E).cross(L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}const _=y.satBounds,I=y.satAxes;for(let D=1;D<4;D++){const O=_[D],L=I[D];if(t.setFromPoints(L,x.points),O.isSeparated(t)||(r.crossVectors(E,L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}return w&&(S||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function f(x,y,w,S,E,b,A,_,I,D,O){let L=A/(A-_);D.x=S+(E-S)*L,O.start.subVectors(y,x).multiplyScalar(L).add(x),L=A/(A-I),D.y=S+(b-S)*L,O.end.subVectors(w,x).multiplyScalar(L).add(x)}function p(x,y,w,S,E,b,A,_,I,D,O){if(E>0)f(x.c,x.a,x.b,S,y,w,I,A,_,D,O);else if(b>0)f(x.b,x.a,x.c,w,y,S,_,A,I,D,O);else if(_*I>0||A!=0)f(x.a,x.b,x.c,y,w,S,A,_,I,D,O);else if(_!=0)f(x.b,x.a,x.c,w,y,S,_,A,I,D,O);else if(I!=0)f(x.c,x.a,x.b,S,y,w,I,A,_,D,O);else return!0;return!1}function m(x,y,w,S){const E=y.degenerateSegment,b=x.plane.distanceToPoint(E.start),A=x.plane.distanceToPoint(E.end);return ir(b)?ir(A)?d(x,y,w,S):(w&&(w.start.copy(E.start),w.end.copy(E.start)),x.containsPoint(E.start)):ir(A)?(w&&(w.start.copy(E.end),w.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function g(x,y,w){const S=y.a;return ir(x.plane.distanceToPoint(S))&&x.containsPoint(S)?(w&&(w.start.copy(S),w.end.copy(S)),!0):!1}function v(x,y,w){const S=x.degenerateSegment,E=y.a;return S.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<xb?(w&&(w.start.copy(E),w.end.copy(E)),!0):!1}function M(x,y,w,S){if(x.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=x.degenerateSegment,b=y.degenerateSegment,A=n,_=s;E.delta(A),b.delta(_);const I=i.subVectors(b.start,E.start),D=A.x*_.y-A.y*_.x;if(ir(D))return!1;const O=(I.x*_.y-I.y*_.x)/D,L=-(A.x*I.y-A.y*I.x)/D;if(O<0||O>1||L<0||L>1)return!1;const P=E.start.z+A.z*O,k=b.start.z+_.z*L;return ir(P-k)?(w&&(w.start.copy(E.start).addScaledVector(A,O),w.end.copy(E.start).addScaledVector(A,O)),!0):!1}else return y.isDegenerateIntoPoint?v(x,y,w):m(y,x,w,S);else{if(x.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(x.a)<xb?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:y.isDegenerateIntoSegment?v(y,x,w):g(y,x,w);if(y.isDegenerateIntoPoint)return g(x,y,w);if(y.isDegenerateIntoSegment)return m(x,y,w,S)}}return function(y,w=null,S=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(o.copy(y),o.update(),y=o);const E=M(this,y,w,S);if(E!==void 0)return E;const b=this.plane,A=y.plane;let _=A.distanceToPoint(this.a),I=A.distanceToPoint(this.b),D=A.distanceToPoint(this.c);ir(_)&&(_=0),ir(I)&&(I=0),ir(D)&&(D=0);const O=_*I,L=_*D;if(O>0&&L>0)return!1;let P=b.distanceToPoint(y.a),k=b.distanceToPoint(y.b),H=b.distanceToPoint(y.c);ir(P)&&(P=0),ir(k)&&(k=0),ir(H)&&(H=0);const W=P*k,Q=P*H;if(W>0&&Q>0)return!1;n.copy(b.normal),s.copy(A.normal);const q=n.cross(s);let nt=0,at=Math.abs(q.x);const Bt=Math.abs(q.y);Bt>at&&(at=Bt,nt=1),Math.abs(q.z)>at&&(nt=2);const Pt=iL[nt],Z=this.a[Pt],ct=this.b[Pt],ot=this.c[Pt],V=y.a[Pt],Nt=y.b[Pt],Xt=y.c[Pt];if(p(this,Z,ct,ot,O,L,_,I,D,h,a))return d(this,y,w,S);if(p(y,V,Nt,Xt,W,Q,P,k,H,u,c))return d(this,y,w,S);if(h.y<h.x){const Lt=h.y;h.y=h.x,h.x=Lt,l.copy(a.start),a.start.copy(a.end),a.end.copy(l)}if(u.y<u.x){const Lt=u.y;u.y=u.x,u.x=Lt,l.copy(c.start),c.start.copy(c.end),c.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(c.start):w.start.copy(a.start),u.y<h.y?w.end.copy(c.end):w.end.copy(a.end)),!0)}})();Pr.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Pr.prototype.distanceToTriangle=(function(){const o=new R,t=new R,e=["a","b","c"],i=new ro,n=new ro;return function(r,a=null,c=null){const l=a||c?i:null;if(this.intersectsTriangle(r,l,!0))return(a||c)&&(a&&l.getCenter(a),c&&l.getCenter(c)),0;let h=1/0;for(let u=0;u<3;u++){let d;const f=e[u],p=r[f];this.closestPointToPoint(p,o),d=p.distanceToSquared(o),d<h&&(h=d,a&&a.copy(o),c&&c.copy(p));const m=this[f];r.closestPointToPoint(m,o),d=m.distanceToSquared(o),d<h&&(h=d,a&&a.copy(m),c&&c.copy(o))}for(let u=0;u<3;u++){const d=e[u],f=e[(u+1)%3];i.set(this[d],this[f]);for(let p=0;p<3;p++){const m=e[p],g=e[(p+1)%3];n.set(r[m],r[g]),fy(i,n,o,t);const v=o.distanceToSquared(t);v<h&&(h=v,a&&a.copy(o),c&&c.copy(t))}}return Math.sqrt(h)}})();class xs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new R,this.max=new R,this.matrix=new Wt,this.invMatrix=new Wt,this.points=new Array(8).fill().map(()=>new R),this.satAxes=new Array(3).fill().map(()=>new R),this.satBounds=new Array(3).fill().map(()=>new oo),this.alignedSatBounds=new Array(3).fill().map(()=>new oo),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}xs.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const d=1*l|2*h|4*u,f=n[d];f.x=l?i.x:e.x,f.y=h?i.y:e.y,f.z=u?i.z:e.z,f.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,a=n[0];for(let l=0;l<3;l++){const h=r[l],u=s[l],d=1<<l,f=n[d];h.subVectors(a,f),u.setFromPoints(h,n)}const c=this.alignedSatBounds;c[0].setFromPointsField(n,"x"),c[1].setFromPointsField(n,"y"),c[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();xs.prototype.intersectsBox=(function(){const o=new oo;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(o.min=i.x,o.max=n.x,a[0].isSeparated(o)||(o.min=i.y,o.max=n.y,a[1].isSeparated(o))||(o.min=i.z,o.max=n.z,a[2].isSeparated(o)))return!1;for(let c=0;c<3;c++){const l=r[c],h=s[c];if(o.setFromBox(l,e),h.isSeparated(o))return!1}return!0}})();xs.prototype.intersectsTriangle=(function(){const o=new Pr,t=new Array(3),e=new oo,i=new oo,n=new R;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(o.copy(r),o.update(),r=o);const a=this.satBounds,c=this.satAxes;t[0]=r.a,t[1]=r.b,t[2]=r.c;for(let d=0;d<3;d++){const f=a[d],p=c[d];if(e.setFromPoints(p,t),f.isSeparated(e))return!1}const l=r.satBounds,h=r.satAxes,u=this.points;for(let d=0;d<3;d++){const f=l[d],p=h[d];if(e.setFromPoints(p,u),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=c[d];for(let p=0;p<4;p++){const m=h[p];if(n.crossVectors(f,m),e.setFromPoints(n,t),i.setFromPoints(n,u),e.isSeparated(i))return!1}}return!0}})();xs.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();xs.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();xs.prototype.distanceToBox=(function(){const o=["x","y","z"],t=new Array(12).fill().map(()=>new ro),e=new Array(12).fill().map(()=>new ro),i=new R,n=new R;return function(r,a=0,c=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(c||l)&&(r.getCenter(n),this.closestPointToPoint(n,i),r.closestPointToPoint(i,n),c&&c.copy(i),l&&l.copy(n)),0;const h=a*a,u=r.min,d=r.max,f=this.points;let p=1/0;for(let g=0;g<8;g++){const v=f[g];n.copy(v).clamp(u,d);const M=v.distanceToSquared(n);if(M<p&&(p=M,c&&c.copy(v),l&&l.copy(n),M<h))return Math.sqrt(M)}let m=0;for(let g=0;g<3;g++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){const x=(g+1)%3,y=(g+2)%3,w=v<<x|M<<y,S=1<<g|v<<x|M<<y,E=f[w],b=f[S];t[m].set(E,b);const _=o[g],I=o[x],D=o[y],O=e[m],L=O.start,P=O.end;L[_]=u[_],L[I]=v?u[I]:d[I],L[D]=M?u[D]:d[I],P[_]=d[_],P[I]=v?u[I]:d[I],P[D]=M?u[D]:d[I],m++}for(let g=0;g<=1;g++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){n.x=g?d.x:u.x,n.y=v?d.y:u.y,n.z=M?d.z:u.z,this.closestPointToPoint(n,i);const x=n.distanceToSquared(i);if(x<p&&(p=x,c&&c.copy(i),l&&l.copy(n),x<h))return Math.sqrt(x)}for(let g=0;g<12;g++){const v=t[g];for(let M=0;M<12;M++){const x=e[M];fy(v,x,i,n);const y=i.distanceToSquared(n);if(y<p&&(p=y,c&&c.copy(i),l&&l.copy(n),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class nL extends uy{constructor(){super(()=>new Pr)}}const hr=new nL,Tu=new R,Kg=new R;function sL(o,t,e={},i=0,n=1/0){const s=i*i,r=n*n;let a=1/0,c=null;if(o.shapecast({boundsTraverseOrder:h=>(Tu.copy(t).clamp(h.min,h.max),Tu.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<a&&d<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Tu);const d=t.distanceToSquared(Tu);return d<a&&(Kg.copy(Tu),a=d,c=u),d<s}}),a===1/0)return null;const l=Math.sqrt(a);return e.point?e.point.copy(Kg):e.point=Kg.clone(),e.distance=l,e.faceIndex=c,e}const a0=parseInt(tf)>=169,rL=parseInt(tf)<=161,gc=new R,vc=new R,Mc=new R,o0=new tt,c0=new tt,l0=new tt,wb=new R,bb=new R,Sb=new R,Ru=new R;function aL(o,t,e,i,n,s,r,a){let c;if(s===Oi?c=o.intersectTriangle(i,e,t,!0,n):c=o.intersectTriangle(t,e,i,s!==bn,n),c===null)return null;const l=o.origin.distanceTo(n);return l<r||l>a?null:{distance:l,point:n.clone()}}function Eb(o,t,e,i,n,s,r,a,c,l,h){gc.fromBufferAttribute(t,s),vc.fromBufferAttribute(t,r),Mc.fromBufferAttribute(t,a);const u=aL(o,gc,vc,Mc,Ru,c,l,h);if(u){if(i){o0.fromBufferAttribute(i,s),c0.fromBufferAttribute(i,r),l0.fromBufferAttribute(i,a),u.uv=new tt;const f=Ln.getInterpolation(Ru,gc,vc,Mc,o0,c0,l0,u.uv);a0||(u.uv=f)}if(n){o0.fromBufferAttribute(n,s),c0.fromBufferAttribute(n,r),l0.fromBufferAttribute(n,a),u.uv1=new tt;const f=Ln.getInterpolation(Ru,gc,vc,Mc,o0,c0,l0,u.uv1);a0||(u.uv1=f),rL&&(u.uv2=u.uv1)}if(e){wb.fromBufferAttribute(e,s),bb.fromBufferAttribute(e,r),Sb.fromBufferAttribute(e,a),u.normal=new R;const f=Ln.getInterpolation(Ru,gc,vc,Mc,wb,bb,Sb,u.normal);u.normal.dot(o.direction)>0&&u.normal.multiplyScalar(-1),a0||(u.normal=f)}const d={a:s,b:r,c:a,normal:new R,materialIndex:0};if(Ln.getNormal(gc,vc,Mc,d.normal),u.face=d,u.faceIndex=s,a0){const f=new R;Ln.getBarycoord(Ru,gc,vc,Mc,f),u.barycoord=f}}return u}function Ab(o){return o&&o.isMaterial?o.side:o}function vm(o,t,e,i,n,s,r){const a=i*3;let c=a+0,l=a+1,h=a+2;const{index:u,groups:d}=o;o.index&&(c=u.getX(c),l=u.getX(l),h=u.getX(h));const{position:f,normal:p,uv:m,uv1:g}=o.attributes;if(Array.isArray(t)){const v=i*3;for(let M=0,x=d.length;M<x;M++){const{start:y,count:w,materialIndex:S}=d[M];if(v>=y&&v<y+w){const E=Ab(t[S]),b=Eb(e,f,p,m,g,c,l,h,E,s,r);if(b)if(b.faceIndex=i,b.face.materialIndex=S,n)n.push(b);else return b}}}else{const v=Ab(t),M=Eb(e,f,p,m,g,c,l,h,v,s,r);if(M)if(M.faceIndex=i,M.face.materialIndex=0,n)n.push(M);else return M}return null}function pn(o,t,e,i){const n=o.a,s=o.b,r=o.c;let a=t,c=t+1,l=t+2;e&&(a=e.getX(a),c=e.getX(c),l=e.getX(l)),n.x=i.getX(a),n.y=i.getY(a),n.z=i.getZ(a),s.x=i.getX(c),s.y=i.getY(c),s.z=i.getZ(c),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l)}function oL(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++)vm(c,t,e,h,s,r,a)}function cL(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=vm(a,t,e,u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function lL(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=h,pn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function hL(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(sn(m,a)){const g=Un(d,r),v=ss(m,a);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=3*g,A=3*(g+v);b<A;b++){let _=i[b];const I=n.getX(_),D=n.getY(_),O=n.getZ(_);I<M&&(M=I),I>w&&(w=I),D<x&&(x=D),D>S&&(S=D),O<y&&(y=O),O>E&&(E=O)}return c[d+0]!==M||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==S||c[d+5]!==E?(c[d+0]=M,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=S,c[d+5]=E,!0):!1}else{const g=En(d),v=An(d,r);let M=p,x=!1,y=!1;if(t){if(!M){const _=g/Sn+f/ns,I=v/Sn+f/ns;x=t.has(_),y=t.has(I),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(g,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],L=c[I+3],P=c[D],k=c[D+3];c[d+_]=O<P?O:P,c[d+_+3]=L>k?L:k}return A}}}function rc(o,t,e,i,n){let s,r,a,c,l,h;const u=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,p=e.origin.x,m=e.origin.y,g=e.origin.z;let v=t[o],M=t[o+3],x=t[o+1],y=t[o+3+1],w=t[o+2],S=t[o+3+2];return u>=0?(s=(v-p)*u,r=(M-p)*u):(s=(M-p)*u,r=(v-p)*u),d>=0?(a=(x-m)*d,c=(y-m)*d):(a=(y-m)*d,c=(x-m)*d),s>c||a>r||((a>s||isNaN(s))&&(s=a),(c<r||isNaN(r))&&(r=c),f>=0?(l=(w-g)*f,h=(S-g)*f):(l=(S-g)*f,h=(w-g)*f),s>h||l>r)?!1:((l>s||s!==s)&&(s=l),(h<r||r!==r)&&(r=h),s<=n&&r>=i)}function uL(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++){let d=l?l[h]:h;vm(c,t,e,d,s,r,a)}}function dL(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=vm(a,t,e,c?c[u]:u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function fL(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=e.resolveTriangleIndex(h),pn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function pL(o,t,e,i,n,s,r){Ni.setBuffer(o._roots[t]),rM(0,o,e,i,n,s,r),Ni.clearBuffer()}function rM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Ni,h=o*2;if(sn(h,c)){const d=Un(o,l),f=ss(h,c);oL(t,e,i,d,f,n,s,r)}else{const d=En(o);rc(d,a,i,s,r)&&rM(d,t,e,i,n,s,r);const f=An(o,l);rc(f,a,i,s,r)&&rM(f,t,e,i,n,s,r)}}const mL=["x","y","z"];function gL(o,t,e,i,n,s){Ni.setBuffer(o._roots[t]);const r=aM(0,o,e,i,n,s);return Ni.clearBuffer(),r}function aM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Ni;let l=o*2;if(sn(l,a)){const u=Un(o,c),d=ss(l,a);return cL(t,e,i,u,d,n,s)}else{const u=hy(o,c),d=mL[u],p=i.direction[d]>=0;let m,g;p?(m=En(o),g=An(o,c)):(m=An(o,c),g=En(o));const M=rc(m,r,i,n,s)?aM(m,t,e,i,n,s):null;if(M){const w=M.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return M}const y=rc(g,r,i,n,s)?aM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const h0=new Ke,Bl=new Pr,Hl=new Pr,Iu=new Wt,_b=new xs,u0=new xs;function vL(o,t,e,i){Ni.setBuffer(o._roots[t]);const n=oM(0,o,e,i);return Ni.clearBuffer(),n}function oM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Ni;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),_b.set(e.boundingBox.min,e.boundingBox.max,i),n=_b),sn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Un(o,a),g=ss(c,r);if(Iu.copy(i).invert(),e.boundsTree)return Yi(o,s,u0),u0.matrix.copy(Iu),u0.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>u0.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=m*3,y=(g+m)*3;x<y;x+=3)if(pn(Hl,x,u,d),Hl.needsUpdate=!0,M.intersectsTriangle(Hl))return!0;return!1}});{const v=gm(e);for(let M=m*3,x=(g+m)*3;M<x;M+=3){pn(Bl,M,u,d),Bl.a.applyMatrix4(Iu),Bl.b.applyMatrix4(Iu),Bl.c.applyMatrix4(Iu),Bl.needsUpdate=!0;for(let y=0,w=v*3;y<w;y+=3)if(pn(Hl,y,f,p),Hl.needsUpdate=!0,Bl.intersectsTriangle(Hl))return!0}}}else{const h=En(o),u=An(o,a);return Yi(h,s,h0),!!(n.intersectsBox(h0)&&oM(h,t,e,i,n)||(Yi(u,s,h0),n.intersectsBox(h0)&&oM(u,t,e,i,n)))}}const d0=new Wt,qg=new xs,Du=new xs,ML=new R,yL=new R,xL=new R,wL=new R;function bL(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),qg.set(t.boundingBox.min,t.boundingBox.max,e),qg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=hr.getPrimitive(),f=hr.getPrimitive();let p=ML,m=yL,g=null,v=null;n&&(g=xL,v=wL);let M=1/0,x=null,y=null;return d0.copy(e).invert(),Du.matrix.copy(d0),o.shapecast({boundsTraverseOrder:w=>qg.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<r?(S&&(Du.min.copy(w.min),Du.max.copy(w.max),Du.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:b=>Du.distanceToBox(b),intersectsBounds:(b,A,_)=>_<M&&_<r,intersectsRange:(b,A)=>{for(let _=b,I=b+A;_<I;_++){pn(f,3*_,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let D=w,O=w+S;D<O;D++){pn(d,3*D,l,c),d.needsUpdate=!0;const L=d.distanceToTriangle(f,p,g);if(L<M&&(m.copy(p),v&&v.copy(g),M=L,x=D,y=_),L<s)return!0}}}});{const E=gm(t);for(let b=0,A=E;b<A;b++){pn(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+S;_<I;_++){pn(d,3*_,l,c),d.needsUpdate=!0;const D=d.distanceToTriangle(f,p,g);if(D<M&&(m.copy(p),v&&v.copy(g),M=D,x=_,y=b),D<s)return!0}}}}}),hr.releasePrimitive(d),hr.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=x,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(d0),m.applyMatrix4(d0),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function SL(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(sn(m,a)){const g=Un(d,r),v=ss(m,a);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=g,A=g+v;b<A;b++){const _=3*o.resolveTriangleIndex(b);for(let I=0;I<3;I++){let D=_+I;D=i?i[D]:D;const O=n.getX(D),L=n.getY(D),P=n.getZ(D);O<M&&(M=O),O>w&&(w=O),L<x&&(x=L),L>S&&(S=L),P<y&&(y=P),P>E&&(E=P)}}return c[d+0]!==M||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==S||c[d+5]!==E?(c[d+0]=M,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=S,c[d+5]=E,!0):!1}else{const g=En(d),v=An(d,r);let M=p,x=!1,y=!1;if(t){if(!M){const _=g/Sn+f/ns,I=v/Sn+f/ns;x=t.has(_),y=t.has(I),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(g,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],L=c[I+3],P=c[D],k=c[D+3];c[d+_]=O<P?O:P,c[d+_+3]=L>k?L:k}return A}}}function EL(o,t,e,i,n,s,r){Ni.setBuffer(o._roots[t]),cM(0,o,e,i,n,s,r),Ni.clearBuffer()}function cM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Ni,h=o*2;if(sn(h,c)){const d=Un(o,l),f=ss(h,c);uL(t,e,i,d,f,n,s,r)}else{const d=En(o);rc(d,a,i,s,r)&&cM(d,t,e,i,n,s,r);const f=An(o,l);rc(f,a,i,s,r)&&cM(f,t,e,i,n,s,r)}}const AL=["x","y","z"];function _L(o,t,e,i,n,s){Ni.setBuffer(o._roots[t]);const r=lM(0,o,e,i,n,s);return Ni.clearBuffer(),r}function lM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Ni;let l=o*2;if(sn(l,a)){const u=Un(o,c),d=ss(l,a);return dL(t,e,i,u,d,n,s)}else{const u=hy(o,c),d=AL[u],p=i.direction[d]>=0;let m,g;p?(m=En(o),g=An(o,c)):(m=An(o,c),g=En(o));const M=rc(m,r,i,n,s)?lM(m,t,e,i,n,s):null;if(M){const w=M.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return M}const y=rc(g,r,i,n,s)?lM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const f0=new Ke,Gl=new Pr,Vl=new Pr,Cu=new Wt,Tb=new xs,p0=new xs;function TL(o,t,e,i){Ni.setBuffer(o._roots[t]);const n=hM(0,o,e,i);return Ni.clearBuffer(),n}function hM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Ni;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),Tb.set(e.boundingBox.min,e.boundingBox.max,i),n=Tb),sn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Un(o,a),g=ss(c,r);if(Cu.copy(i).invert(),e.boundsTree)return Yi(o,s,p0),p0.matrix.copy(Cu),p0.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>p0.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=m,y=g+m;x<y;x++)if(pn(Vl,3*t.resolveTriangleIndex(x),u,d),Vl.needsUpdate=!0,M.intersectsTriangle(Vl))return!0;return!1}});{const v=gm(e);for(let M=m,x=g+m;M<x;M++){const y=t.resolveTriangleIndex(M);pn(Gl,3*y,u,d),Gl.a.applyMatrix4(Cu),Gl.b.applyMatrix4(Cu),Gl.c.applyMatrix4(Cu),Gl.needsUpdate=!0;for(let w=0,S=v*3;w<S;w+=3)if(pn(Vl,w,f,p),Vl.needsUpdate=!0,Gl.intersectsTriangle(Vl))return!0}}}else{const h=En(o),u=An(o,a);return Yi(h,s,f0),!!(n.intersectsBox(f0)&&hM(h,t,e,i,n)||(Yi(u,s,f0),n.intersectsBox(f0)&&hM(u,t,e,i,n)))}}const m0=new Wt,Zg=new xs,Ou=new xs,RL=new R,IL=new R,DL=new R,CL=new R;function OL(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),Zg.set(t.boundingBox.min,t.boundingBox.max,e),Zg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=hr.getPrimitive(),f=hr.getPrimitive();let p=RL,m=IL,g=null,v=null;n&&(g=DL,v=CL);let M=1/0,x=null,y=null;return m0.copy(e).invert(),Ou.matrix.copy(m0),o.shapecast({boundsTraverseOrder:w=>Zg.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<r?(S&&(Ou.min.copy(w.min),Ou.max.copy(w.max),Ou.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:b=>Ou.distanceToBox(b),intersectsBounds:(b,A,_)=>_<M&&_<r,intersectsRange:(b,A)=>{for(let _=b,I=b+A;_<I;_++){const D=E.resolveTriangleIndex(_);pn(f,3*D,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let O=w,L=w+S;O<L;O++){const P=o.resolveTriangleIndex(O);pn(d,3*P,l,c),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,g);if(k<M&&(m.copy(p),v&&v.copy(g),M=k,x=O,y=_),k<s)return!0}}}})}else{const E=gm(t);for(let b=0,A=E;b<A;b++){pn(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+S;_<I;_++){const D=o.resolveTriangleIndex(_);pn(d,3*D,l,c),d.needsUpdate=!0;const O=d.distanceToTriangle(f,p,g);if(O<M&&(m.copy(p),v&&v.copy(g),M=O,x=_,y=b),O<s)return!0}}}}}),hr.releasePrimitive(d),hr.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=x,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(m0),m.applyMatrix4(m0),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function Rb(o,t,e){return o===null?null:(o.point.applyMatrix4(t.matrixWorld),o.distance=o.point.distanceTo(e.ray.origin),o.object=t,o)}const g0=new xs,v0=new sl,Ib=new R,Db=new Wt,Cb=new R,Jg=["getX","getY","getZ"];class zp extends Q8{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=n.map(c=>c.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=s?s.slice():null):(a.roots=n,a.index=r?r.array:null,a.indirectBuffer=s),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(s));const a=new zp(e,{...i,[ly]:!0});if(a._roots=s,a._indirectBuffer=r||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new ve(t.index,1,!1);e.setIndex(h)}else l.array!==n&&(l.array.set(n),l.needsUpdate=!0)}return a;function c(l){for(let h=0;h<l.length;h++){const u=l[h],d=new Uint32Array(u),f=new Uint16Array(u);for(let p=0,m=u.byteLength/ns;p<m;p++){const g=Sn*p,v=2*g;sn(v,f)||(d[g+6]=d[g+6]/Sn-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,l=(s?s[t]:t)*3;let h=l+0,u=l+1,d=l+2;a&&(h=a[h],u=a[u],d=a[d]);for(let f=0;f<3;f++){const p=r[Jg[f]](h),m=r[Jg[f]](u),g=r[Jg[f]](d);let v=p;m<v&&(v=m),g<v&&(v=g);let M=p;m>M&&(M=m),g>M&&(M=g),e[i+f]=v,e[i+f+3]=M}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,c=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,h=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const d=["getX","getY","getZ"],f=i.offset;for(let p=t,m=t+e;p<m;p++){const v=(s?s[p]:p)*3,M=(p-f)*6;let x=v+0,y=v+1,w=v+2;a&&(x=a[x],y=a[y],w=a[w]),c||(x=x*u+h,y=y*u+h,w=w*u+h);for(let S=0;S<3;S++){let E,b,A;c?(E=r[d[S]](x),b=r[d[S]](y),A=r[d[S]](w)):(E=l[x+S],b=l[y+S],A=l[w+S]);let _=E;b<_&&(_=b),A<_&&(_=A);let I=E;b>I&&(I=b),A>I&&(I=A);const D=(I-_)/2,O=S*2;i[M+O+0]=_+D,i[M+O+1]=D+(Math.abs(_)+D)*K0}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(n===void 0)return;Db.copy(t.matrixWorld).invert(),v0.copy(e.ray).applyMatrix4(Db),Cb.setFromMatrixScale(t.matrixWorld),Ib.copy(v0.direction).multiply(Cb);const s=Ib.length(),r=e.near/s,a=e.far/s;if(e.firstHitOnly===!0){let c=this.raycastFirst(v0,n,r,a);c=Rb(c,t,e),c&&i.push(c)}else{const c=this.raycast(v0,n,r,a);for(let l=0,h=c.length;l<h;l++){const u=Rb(c[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?SL:hL)(this,t)}raycast(t,e=Sa,i=0,n=1/0){const s=this._roots,r=[],a=this.indirect?EL:pL;for(let c=0,l=s.length;c<l;c++)a(this,c,e,t,r,i,n);return r}raycastFirst(t,e=Sa,i=0,n=1/0){const s=this._roots;let r=null;const a=this.indirect?_L:gL;for(let c=0,l=s.length;c<l;c++){const h=a(this,c,e,t,i,n);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?TL:vL;for(let r=0,a=n.length;r<a&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=hr.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?fL:lL});return hr.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=hr.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,l=this.indirect?p=>{const m=this.resolveTriangleIndex(p);pn(r,m*3,a,c)}:p=>{pn(r,p*3,a,c)},h=hr.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const m=t.resolveTriangleIndex(p);pn(h,m*3,u,d)}:p=>{pn(h,p*3,u,d)};if(s){if(!(t instanceof zp))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(m,g,v,M,x,y,w,S)=>{for(let E=v,b=v+M;E<b;E++){f(E),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let A=m,_=m+g;A<_;A++)if(l(A),r.needsUpdate=!0,s(r,h,A,E,x,y,w,S))return!0}return!1};if(n){const m=n;n=function(g,v,M,x,y,w,S,E){return m(g,v,M,x,y,w,S,E)?!0:p(g,v,M,x,y,w,S,E)}}else n=p}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return g0.set(t.min,t.max,e),g0.needsUpdate=!0,this.shapecast({intersectsBounds:i=>g0.intersectsBox(i),intersectsTriangle:i=>g0.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?OL:bL)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return sL(this,t,e,i,n)}}class Xr{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new fr;static install(){if(Xr.installed)return;Xr.installed=!0;const t=Mt.prototype.raycast;Mt.prototype.raycast=function(e,i){const n=Xr.treeOf(this,e);n!==null&&(n?n.raycastObject3D(this,e,i):t.call(this,e,i))}}static treeOf(t,e){const i=t.geometry,n=i?.attributes.position;if(!(n instanceof ve)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||i.morphAttributes.position)return;const s=i.index;if((s?s.count:n.count)/3<Xr.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=Xr.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(r))return null;const a=Xr.trees.get(i);if(a){if(!a.bvh)return;if(a.position===n&&a.positionVersion===n.version&&a.index===s&&a.indexVersion===(s?.version??0))return a.bvh;Xr.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const c=new zp(i,{indirect:!0});return Xr.trees.set(i,{bvh:c,position:n,positionVersion:n.version,index:s,indexVersion:s?.version??0}),c}}function PL(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 M0=900,jg=1,Ob=4,Qg=5,y0=.5,x0=Ge.GROUND_RADIUS_M;function Pb(o){return Ge.groundRadiusFor(o)}const t1=.5,e1=850,w0=.03,NL=.015,ls=850,Wl=300,La=120,LL=700,i1=.03,kL=3.5,b0=20,n1=.04,UL=.26,Nb=4,s1=1.5,Lb=-1,FL=.01,Z0=-4,zL=2,BL=20,S0=2600,HL=.97,GL=.38,Pu=Z0,VL=8,WL=2,kb=1500,XL=.7,$L=.3,YL=.32,KL=.65,Ub=2.4,qL=.9,ZL=400,JL=[0,45,90,135,180,225,270,315],jL=2,QL=16,Fb=4e3,zb=880,E0=40,Bb=60,t9=10,Hb=1,e9=Ge.REBUILD_DISTANCE_M,Gb=.265,Vb=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*Gb,Math.sin(e)*Gb]})],r1=700,a1=250/dM,i9=12,Wb=5,o1=6,yc=[.92,.92,.95],c1=[.15,.15,.19],l1={snow:{fallSpeedMPerS:2,size:.3,color:new rt(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new rt(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Zl=0,h1=0,n9=150,u1=3e3,Nu=20,s9=15,Xb=Zl,r9=40,$b=1,a9=9;function d1(o){return $b+(a9-$b)*o}const Yb=new rt(.75,.82,.92),o9=10,c9=.5;function Kb(o){return $r(o/o9,c9,1)}const xc=200,qb=.18,Zb=.32,l9=.35,Jb=new rt(.85,.9,.98),jb=5,Qb=.85,tS=.01;function h9(o,t,e=1){return Math.round(o*(tS+(1-tS)*t)*e)}function u9(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 eS=230,iS=.7,nS=.05,d9=.6,f9=.7,p9=.15,sS=.35,m9=3,g9=1/12,v9=.5,Hr=new rt(.82,.86,1),M9=2500,y9=1.6,f1=15,x9={Venus:new rt(1,.96,.85),Mars:new rt(1,.55,.4),Jupiter:new rt(.95,.87,.72),Saturn:new rt(.92,.86,.68)};class lt{renderer;scene=new Zs;phenomena=new Er(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Xe;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()+Fb,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Fb+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new tt;decorModelProvider=new GA;decorModelToken=0;decorModelCredits=new Map;emitterLights=new us(this.scene,()=>this.relativeScale,{halfExtentM:La,depthHalfRangeM:Wl,biasM:i1,normalBiasM:n1,mapSize:1024});bodySystem=new re(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??lt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*lt.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Ep(16777215,0);celestialLightTarget=new Pi;skyLight=new b4(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 V0;weather=Yp;observerElevationM=0;siteElevationM=0;air=new or;groundRadius=x0;terrainRadius=x0;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 tt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Ep(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new V0;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new V0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=pi.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Kd;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=QS()){Qu.install(),Xr.install(),this.renderer=new UO({canvas:t,antialias:!0}),this.resolution=new Qe(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Xu,this.camera=new Wn(60,t.width/Math.max(t.height,1),.1,M0*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=-La,this.celestialLight.shadow.camera.right=La,this.celestialLight.shadow.camera.top=La,this.celestialLight.shadow.camera.bottom=-La,this.celestialLight.shadow.camera.near=ls-Wl,this.celestialLight.shadow.camera.far=ls+Wl,this.celestialLight.shadow.bias=-i1/(2*Wl),this.celestialLight.shadow.normalBias=n1,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Hr),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 de(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*a1,0,t.z*a1);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){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Je,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Je;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Je,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(Pb(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/x0),this.camera.far=Math.max(M0*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.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=lt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Ge.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ae(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}this.lookPatch&&s(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=Hb+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=Ge.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(t.headingDeg??0)*Math.PI/180,n=t.lat+e.distanceM*Math.cos(i)/111320,s=t.lng+e.distanceM*Math.sin(i)/(111320*Math.cos(t.lat*Math.PI/180)),r=this.lookPatchAsked;if(r){const l=ae(n,s,r.lat,r.lng);if(Math.hypot(l.x,l.z)<r.radiusM*lt.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:n,lng:s,radiusM:e.radiusM};const a=++this.lookPatchToken,c=this.terrainProviders;Og(n,s,{elevation:c.elevation,imagery:c.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:l})=>{if(a!==this.lookPatchToken||this.terrainProviders!==c||!this.terrainMesh){this.disposeMesh(l);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),l.renderOrder=lt.LOOK_PATCH_RENDER_ORDER,l.position.y=this.terrainMesh.position.y;const h=l.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:l,origin:{lat:n,lng:s},radiusM:e.radiusM};const u=ae(n,s,t.lat,t.lng);l.position.x=u.x,l.position.z=u.z,this.scene.add(l),this.compileNextFrameOffThread(),this.render()},l=>console.warn("No sharp ground under what is looked at:",l))}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),lt.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(Ge.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=ae(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<e9*(r/x0))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ae(t,e,c.lat,c.lng).x,ae(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 h=++this.terrainBuildToken;this.awaitArrival(Og(t,e,this.terrainProviders,r,{route:this.observerRoute}),lt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const g=this.terrainMesh,v=this.terrainMeshOrigin,M=v?ae(t,e,v.lat,v.lng):void 0;g&&M&&Math.hypot(M.x,M.z)<=a&&(u.position.y=g.position.y+this.groundYOfPatch(g,M.x,M.z)),g&&v&&M&&Math.hypot(M.x,M.z)<=a?this.crossfadeTerrain(u,g,v):this.disposeMesh(this.terrainMesh),u.renderOrder=Hb,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,m),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=this.skyEventReachM({lat:t,lng:e});if(!Ge.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=ae(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*lt.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(t,e);if(l&&!h){this.dropFarRing();return}const u=h?.radiusM??Ge.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(Og(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*lt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),lt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=lt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-lt.FAR_RING_DROP_M;const m=p.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,i){if(this.grassReference){const r=ae(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=ae(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/lt.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Ge.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(td(t,e,i)),lt.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>lt.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),lt.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(ae(t,e,a.lat,a.lng).x,ae(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(td(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),Qn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Et(async()=>{const{WaterSystem:t}=await import("./WaterSystem-D3andNtL.js");return{WaterSystem:t}},[],import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const n=this.terrainProviders.railways;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(td(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),Qn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Et(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-C920HhY6.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??=Et(async()=>{const{TraceSystem:t}=await import("./TraceSystem-BrpqiAAJ.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(Qg);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=ut.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ae(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 Si(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?xn.LENS_K:xn.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(PL(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!u9(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=or.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:Zo.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>=v9,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(lt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ut.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,VL);for(const i of t){const n=ut.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<WL,i.lamp),i.model&&i.id.startsWith(Di.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=lt.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=Et(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-Bgre4cLs.js");return{ContrailSystem:t}},__vite__mapDeps([14,15]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,n=lt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=gs.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Ue.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*l*c[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,i){if(this.skyEventsStart=i,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let n=!1;const s=new Set;for(const r of Kv){const a=to.of(r);s.add(a.key);const c=to.eventsOf(t,a);let l=this.skyEventLayers.get(a.key);if(l?.kind!==a&&l&&(this.disposeSkyEventLayer(a.key,l),l=void 0),!(!l&&c.length===0)){if(!l)l={kind:a,events:c},this.skyEventLayers.set(a.key,l);else if(l.events===c)continue;l.events=c,n||=a.reachM!==void 0,this.loadSkyEventSimulation(l)}}for(const[r,a]of this.skyEventLayers)s.has(r)||(this.disposeSkyEventLayer(r,a),n||=a.kind.reachM!==void 0);n&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const i=e();(i.inSky?this.celestialGroup:this.scene).add(i.object),t.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[])}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const i=`skyEvent:${t}:`,n=new Set;for(const s of e){const r=i+s.key,{x:a,y:c,z:l}=xi(s.position.altitudeDeg,s.position.azimuthDeg,ls),[h,u,d]=this.arrivingIlluminance(s.position,s.magnitude,this.cloudTransmission(s.position));this.setGlare(r,a,c,l,[h*s.fade,u*s.fade,d*s.fade],0,lt.POINT_VEIL_HOLD_DEG),n.add(r)}for(const s of[...this.glareSprites.keys()])s.startsWith(i)&&!n.has(s)&&this.disposeGlare(s)}skyEventReachM(t){let e=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(e=Math.max(e,i.kind.reachM(i.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,i={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},n=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,s=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$0(-90,this.instrumentMagnitudeGain);let r;for(const[a,c]of this.skyEventLayers)c.simulation&&(r??={observer:i,date:n,magnitudeLimit:s,cloudTransmission:l=>this.cloudTransmission(l),arrivingIlluminance:(l,h,u)=>this.arrivingIlluminance(l,h,u),transmittanceFromSpace:l=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,l.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(l,h,u)=>this.transmittanceTo(l,h,u),groundYAt:(l,h)=>this.groundYUnder(l,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Je)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Je)*this.weather.windSpeed}},c.simulation.update(c.events,this.decorTime,{...r,lightFrom:l=>this.skyEventLight(a,l),glareFrom:l=>this.skyEventGlare(a,l)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?xi(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}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*Je)/Math.cos(t.lat*Je)}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,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),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 h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,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,l)=>(a*e+(c+l)/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 Bg(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(np(t))||!ut.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=WA(i.scene);n.traverse(s=>{s instanceof Mt&&(s.userData.sharedModel=!0)}),ut.applyModelParameters(n,t.modelParameters,i.bindings),ut.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new Rs;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?LS[t.kind]:np(t);if(!(!n||!ut.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await Bg(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&(re.glaze(c),Qn.reflectOn(c));const h={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,h),this.applyLoadedDecorModel(t,l,h),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=Bg(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Qn.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?ae(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&Xh(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=Cr(s,i),m=ut.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*Je,v=m.x*Math.cos(g)+m.z*Math.sin(g),M=-m.x*Math.sin(g)+m.z*Math.cos(g),x=p.eastM+n.x,y=-p.northM+n.z;r.x=-(x+v),r.z=-(y+M),this.camera.position.y=this.groundYUnder(x,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Je,-(m.headingDeg+this.indoorLookYawDeg)*Je,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const l=this.findCabin(i,n,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const m=this.decorGroups.get(p.id);if(!m)continue;const g=Cr(p,i),v=this.lampNudges.get(p.id),M=g.eastM+(v?.eastM??0)+n.x+r.x,x=-(g.northM+(v?.northM??0))+n.z+r.z,y=this.terrainMesh,w=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(x-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(m.userData.footprintKey!==w){if(p.kind==="wire"){const O=ut.wireGround(p,M,x,g.headingDeg,(L,P)=>this.groundYUnder(L,P));m.userData.footprintGroundY=O.startY,ut.shearWire(m,ut.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(M,x),L=-(g.headingDeg??0)*Je,P=Math.cos(L),k=Math.sin(L);m.userData.footprintGroundY=O,Ee.drape(ut.bodyOf(m),(H,W)=>this.groundYUnder(M+H*P+W*k,x-H*k+W*P)-O)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,M,x,g.headingDeg,g.altitudeM);m.userData.footprintKey=w}const E=g.altitudeM>lt.AIRBORNE_M&&Math.hypot(M,x)<lt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,b=p.id.startsWith(Di.ID_PREFIX)?lt.trafficHeight(g.altitudeM,m.userData.footprintGroundY):E+g.altitudeM;if(m.position.set(M,b,x),p.kind==="crop"){const O=Math.hypot(M,x);m.visible=O<=n9}const A=this.decorPresence.get(p.id),_=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(m.visible=!_);const I=this.decorSunlight.get(p.id);I&&!_&&this.lightFromAbove(m,I),g.headingDeg!==void 0&&(m.rotation.y=-g.headingDeg*Je);const D=X_(p,i);if(D!==void 0&<.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const O=this.terrainMesh,L=[O?.geometry.uuid,M-(O?.position.x??0),x-(O?.position.z??0),m.position.y-(O?.position.y??0),g.headingDeg,g.altitudeM].map(P=>typeof P=="number"?P.toFixed(4):P).join(":");m.userData.cropGroundKey!==L&&(ut.fitCropToGround(m,(P,k)=>this.groundYUnder(P,k)+g.altitudeM),m.userData.cropGroundKey=L)}if(!_){const O=m.position.distanceTo(this.camera.position);a=Math.max(a,O),O<lt.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateSkyEvents();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(M0*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,l=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(l)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=h*h*(3-2*h);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=Cr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=-(a.headingDeg??0)*Je,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(l-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(c,0,l),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=ut.fitTerrace(r,s,(m,g)=>this.terrainYUnder(c+m*d+g*f,l-m*f+g*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.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):h1}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+lt.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=c;u=Math.max(u+l,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),m=u*u/(2*lt.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(p-m-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return h1;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=$r((e-r)/(a-r)*(s-1),0,s-1),u=$r((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return h1;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,m=u-f,g=(w,S)=>n.getY(w*s+S),v=g(f,d),M=g(f,d+1),x=g(f+1,d),y=g(f+1,d+1);return p+m<=1?v+(M-v)*p+(x-v)*m:y+(x-y)*(1-p)+(M-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return ut.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=Ls.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n,s){const r=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0&&n===void 0,maxIso:t.maxIso,metering:s??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}: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?Ls.NONE:this.perception??Ls.NONE;if(Ci.uColorVision.value.set(...i.colorMatrix),Ci.uContrast.value=i.contrastGain,!t){Ci.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";Ci.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:n?4:3;const s=t.autoExposure?this.frameLight:void 0,r=t.autoExposure||this.skyUnknown?s?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),c=r===void 0?void 0:r+a.mean,l=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let h=c!==void 0&&c>0?1/(e*c):void 0;h!==void 0&&t.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,lt.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),h!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(h=Math.min(h,lt.ZONE_KEPT_AT/(.18*e*s.brightest)));const u=h!==void 0?Math.min(h,t.maxIso!==void 0?l(t.maxIso):1/0):l(t.iso);Ci.uMediumExposure.value=u,Ci.uPhoneStrength.value=n&&c!==void 0&&c>0?br.strengthFor(br.MID_GREY*u*e*c):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new R;let r=0,a=0;for(const{position:c,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())s.copy(c).project(t),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=l*h,a=Math.max(a,l*Math.min(1,h/(lt.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new tt;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&ut.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?kS(n,t):void 0,c=a!==void 0?qc.lamps(a):tm(n,t,this.lastAstronomy?.sun.altitudeDeg);ut.setLit(r,n.kind,c,this.relativeScale,n.lamp);const l=this.streetlightLights.get(n.id);l&&(l.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??=Et(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-CmppP6Mm.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=ut.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-$L);r.y+=XL;const a=ut.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*YL,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?qc.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*Ub,this.camera.position.y-qL,n.z*Ub);this.headlightSystem.aim("observer",e,s,n,KL,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=ut.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=kb*ut.lampShare(n),c=new WE(16764006,a*this.relativeScale,ZL);n?.colorTemperatureK&&c.color.setRGB(...ut.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;ut.setLitWindowShare(t?zn.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=Cs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Ft.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=en.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,Nb,new rt(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<Z0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=Nb/ls*(180/Math.PI),n=i/e.sunRadiusDeg,s=xi(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=xi(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos($r(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?$r(e.separationDeg*n*Je/a,0,2):0,l=Math.sin(a),[h,u]=a>1e-9?[Math.sin((1-c)*a)/l,Math.sin(c*a)/l]:[1,0],d={x:s.x*h+r.x*u,y:s.y*h+r.y*u,z:s.z*h+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*Je,moonRadiusRad:f*Je};const p=.01,m=(M,x)=>xi(t.sun.altitudeDeg+M,t.sun.azimuthDeg+x,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},v={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new ph(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.updateSkyEvents());const e=this.scatteredSky?.ambient??lt.relativeSkyOf(Iv(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),Gt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??kb)*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?qt.DEFAULT_AEROSOL_OPTICAL_DEPTH:Zo.opticalDepth(i))*qt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ue.aureoleScale(n,Ue.airMass(t.altitudeDeg))*s,c=Ue.coronaScale(r),l=Ue.illuminanceOf(t.magnitude),h=[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(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new cy,this.celestialGroup.add(this.lunarDiffraction.object));const u=Ue.profile(Ue.HAZE_COARSE_MODE),d=Ue.profile(Ue.CLOUD_DROPLETS),f=aP(t.altitudeDeg),p=new Float32Array(Ue.STEPS*3);let m=0;for(let x=0;x<Ue.STEPS;x++){const y=x*3,w=[0,1,2].map(E=>l*f[E]*(a*u[y+E]+c*d[y+E])),S=Cs.shown(w,Cs.luminanceOf(w),(E,b)=>e.relativeOfLuminance(E,b));p.set(S,y),m=Math.max(m,Cs.response(S))}const{x:g,y:v,z:M}=xi(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:g,y:v,z:M}:void 0,p)}applyAir(){this.scene.fog instanceof $c||(this.scene.fog=new $c),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))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,lt.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:en.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?en.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:_t.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?QL:jL),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 QN(e1),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$0(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}flightScreenPoint(t){const e=`${Di.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(e))continue;const s=this.screenPointOf(new R().copy(n.position).sub(this.camera.position).normalize());if(s&&Math.abs(s.ndcX)<=1&&Math.abs(s.ndcY)<=1&&!this.groundHides(s.ndcX,s.ndcY))return s}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(w0*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(Di.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,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(w0*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>=Pu,s=!n&&t.moon.altitudeDeg>=Pu,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Je)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?fb.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=Pu&&(h=t.moon,u=fb.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Je)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),m=Math.max(0,1/(1+.1125*p)-f),g=[0,0,0];if(n||s){const S=Ue.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)g[I]=S*E[I]*m*c,this.cloudBeam[I]=S*E[I];const{x:b,y:A,z:_}=xi(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(b,A,_),u>0){const I=Ue.illuminanceOf(h.magnitude)*i,D=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),O=h===r?f:this.cloudTransmission(h);for(let L=0;L<3;L++)a[L]=I*D[L]*O*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,b=[0,1,2].map(_=>E[_]*S+g[_]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const A=ee.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(b[0]+a[0]*d),A*(b[1]+a[1]*d),A*(b[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:M,y:x,z:y}=xi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(M,x,y),this.celestialLight.shadow.normalBias=n1*$r(x/UL,.1,1),this.placeShadowFrustum();const w=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/w,a[1]/w,a[2]/w),this.celestialLight.intensity=w,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=gs.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Ue.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=lt.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)n[l]=Math.max(0,a*r[l]*s*c-this.sceneSunBeam[l])}}t.traverse(s=>{const r=s.material;if(!(r instanceof pr||r instanceof Fo)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=lt.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new 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=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*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=kL;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=b0+5,i.near=this.shadowLightDistanceM-b0,i.far=this.shadowLightDistanceM+b0,i.updateProjectionMatrix(),e.bias=-.004/(2*b0),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==lt.CABIN_SKY_SHARE&&(r.envMapIntensity=lt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(LL,Math.max(La,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(Wl,e*(Wl/La));this.shadowLightDistanceM=Math.max(ls,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-i1/(2*s);const r=e>2*La?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=La;shadowLightDistanceM=ls;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*Je,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/Ft.semiSaturation(Ft.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new Dn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const i=Math.max(this.relativeScale,1e-30),n=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:s,y:r,z:a}=xi(t.altitudeDeg,t.azimuthDeg,1);return{direction:new R(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=zi.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=_t.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:_t.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return $0(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.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+lt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"&&s.kind!=="vehicle"||s.observerSide!==void 0&&Xh(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Cr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(c,l)<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 Qn(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(c=>c.mesh)],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof Xs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object].filter(c=>c!==void 0),...[...this.skyEventLayers.values()].filter(c=>c.simulation?.hiddenFromEye).map(c=>c.simulation.object)],n=this.relativeScale,s=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,c=>this.measureSurroundings(c,n,s,r),t?0:Qn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,lt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new hh,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>xi(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,r,a=>{const c=p=>p.map(m=>m/e),l=this.surroundings,h={up:c(a.up),down:c(a.down)},u=(p,m)=>p.some((g,v)=>Math.abs(g-m[v])>.03*Math.max(Math.abs(g),Math.abs(m[v]),1e-12)),d=!l||u(l.up,h.up)||u(l.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(lt.adaptingLuminance(Math.exp(a.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Pu?t.sun:t.moon.altitudeDeg>=Pu?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new wr;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?xi(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??lt.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,s=>{const r={mean:s.mean/t.scale,brightest:s.brightest/t.scale},a=this.frameLight,c=t.atMs,l=a?c-a.atMs:1/0,h=l<0||l>lt.EXPOSURE_JUMP_MS,u=h||l===0&&a?.jumped?1:1-Math.exp(-l/n),d=(m,g)=>m>0&&g>0?m*(g/m)**u:g,f={mean:d(a?.mean??0,r.mean),brightest:d(a?.brightest??0,r.brightest),atMs:c,jumped:h||l===0&&(a?.jumped??!1)};this.frameLight=f;const p=(m,g)=>Math.abs(m-g)>.01*Math.max(m,g);(!a||p(a.mean,f.mean)||p(a.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Ci.uRetinaOn.value=0,this.medium)return;const t=[];for(const a of this.emitterLights.farEmitters){const c=this.screenPointOf(a.direction);!c||Math.abs(c.ndcX)>1.2||Math.abs(c.ndcY)>1.2||t.push({ndcX:c.ndcX,ndcY:c.ndcY,lux:Cs.luminanceOf(a.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.y,1),n={width:this.camera.fov*i,height:this.camera.fov},s=this.retina?.atMs;if((s===void 0||this.recordingTimeMs<s||this.recordingTimeMs-s>le.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new le,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),n,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new le,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(Ci.uRetina.value=this.retina.texture,Ci.uRetinaOn.value=1,Ci.uRetinaViewport.value.copy(e))}retinaSize=new tt;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const n=i.pose,s=this.historicQuaternion.setFromEuler(this.historicEuler.set((n?.pitchDeg??0)*Je,-(n?.headingDeg??0)*Je,(n?.rollDeg??0)*Je,"YXZ")).invert(),r=n?.fovDeg??this.camera.fov,a=[];for(const c of i.views){const l=this.farEmitterOf(c.head,c.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(s),r,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:Cs.luminanceOf(l.lux)})}return a}historicQuaternion=new rs;historicEuler=new Ea;historicDirection=new R;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<lt.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const i of t)i.traverse(n=>{n.userData.emissive===!0&&e.push(n)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,g9);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ut.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[Qv]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Rs.INTERVAL_MS)),Ci.uRodShare.value=this.scatteredSky?.rodShare??0,Ci.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Ci.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 Xs&&e.userData.pointSource||e instanceof Mt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Qg),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($A),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 Ms({blending:Zc,blendSrc:ua,blendDst:ua,blendSrcAlpha:ua,blendDstAlpha:ua,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??=Et(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-DVbt8GRf.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s,s.onFrame=()=>this.render(),this.referenceClock&&s.setTime(this.referenceClock);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})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new 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;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const s=e?this.narrowTo(t,e):t,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse)),a=this.phenomena.furthestM;let c=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=l.kind!=="crop"&&this.mayHide(h,t,r,a);lt.markDecorDepth(h,u),u&&c++}c>0&&(t.layers.set(jg),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(Qv),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new nm;phenomenaViewProjection=new Wt;occluderSphere=new fr;localBounds=new WeakMap;mayHide(t,e,i,n){let s=0;t.traverse(()=>s++);let r=this.localBounds.get(t);if(!r||r.objects!==s){t.updateMatrixWorld(!0);const c=new Ke().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new fr).applyMatrix4(new Wt().copy(t.matrixWorld).invert()),objects:s},this.localBounds.set(t,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(t.matrixWorld);return a.center.distanceTo(e.position)-a.radius>n?!1:i.intersectsSphere(a)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new tt),n=lt.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),s=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-n)),r=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-n)),a=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+n)),c=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+n)),l=this.narrowCamera.copy(t);return l.setViewOffset(i.x,i.y,s,i.y-c,Math.max(1,a-s),Math.max(1,c-r)),l.updateMatrixWorld(),l}narrowCamera=new Wn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new Ms({colorWrite:!1,side:bn});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(lt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*Je}static isSolidSurface(t){if(!(t instanceof Mt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==_n}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof Mt))return;e&<.isSolidSurface(i)?i.layers.enable(jg):i.layers.disable(jg)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new tt),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new YO(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+lt.EXPOSURE_BUDGET_MS,s=lt.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=a[l]})}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(){Ci.uRodShare.value=this.scatteredSky?.rodShare??0,Ci.uHasOverlay.value=1,Ci.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Zs,n=new Js(-1,1,1,-1,0,2),s=E0/(zb*Math.tan(Bb*Je/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new pu(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(s/this.camera.aspect,s,1),i.add(h)}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 Ke,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)<lt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const g=(m.ndcX+1)/2,v=(1-m.ndcY)/2;c=Math.min(c,g),l=Math.max(l,g),h=Math.min(h,v),u=Math.max(u,v)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&t.push({x:c,y:h,width:l-c,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new tt),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new id(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,Ci.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 tt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Qi(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new tt);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new oy(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new tt);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Ii(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,n=>{const s=lt.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!s||s.distance>=n-.001||this.mirrors.isMirror(s.object)})}aimStraightAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new tt(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);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ii.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*Je);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new R;screenPointQuaternion=new rs;screenPointSize=new tt;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(l=>Math.max(0,l-lt.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=t.uniforms.uLensPosition.value,r=t.uniforms.uTanHalfFov.value,a=this.camera.aspect,c=pi.offFrameShare(Math.atan(Math.hypot(s.x*a,s.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI);if(!(c<=0))return{x:s.x,y:s.y,radius:i,flux:[e[0]*n*c,e[1]*n*c,e[2]*n*c]}}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(Ob),this.camera.layers.set(Ob),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 Vb)this.isSunOccluded(e[0],e[1])||t++;return t/Vb.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const n=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&n.length===0)return!1;const s=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),r=s.length();if(s.normalize(),e!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(s.z,0,-s.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const u=this.sunOcclusionUpScratch.crossVectors(h,s).normalize();s.addScaledVector(h,e*l).addScaledVector(u,i*l).normalize()}if(this.groundBlocks(this.camera.position,s,r)||this.cabinMask.hides(s))return!0;const a=this.cabinMask.any?n.filter(l=>!this.cabinGroups.includes(l)):n;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,s);const c=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(l=>!(l.object.material instanceof no));return c!==void 0&&c.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const i=e.mesh.getWorldPosition(this.veilTargetScratch),n=e.mesh.material.uniforms.uSourceDeg.value,s=n>.05?lt.VEIL_SAMPLES:lt.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,c]of s)this.isOccludedToward(i,a*n,c*n)||r++;e.share=r/s.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new As;veilTargetScratch=new R;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const v=t.x+e.x*g-s.position.x,M=t.z+e.z*g-s.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[g,v,M]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(g<x||g>y)return!1;continue}const w=(x-g)/v,S=(y-g)/v;d=Math.max(d,Math.min(w,S)),f=Math.min(f,Math.max(w,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const v=d+(f-d)*g/m,M=t.x+e.x*v,x=t.y+e.y*v,y=t.z+e.z*v;if(x<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=y0;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(l=>lt.isSolidSurface(l.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=FL*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new R).sub(i);return{key:h,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}]:[],l=lt.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...c],s);if(l)return this.groundHides(t,e)?void 0:l}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 l=Math.acos($r(c.direction.dot(t),-1,1))-c.radiusRad;if(l>i)continue;const h=l<=0,u=s<=0,d=c.inFront===!0;(h!==u?h:h?d!==a?d:c.radiusRad<r:l<s)&&(n=c.key,s=l,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=NL*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?lt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new Ke,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,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const v=Math.acos(Math.min(1,m.normalize().dot(n))),M=Math.atan(p/g);if(M>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(v>r)continue;M<h&&(h=M,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(w0*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,y0)}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),l=this.screenPointOf(c.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),s=Math.max(s,l.ndcX),n=Math.min(n,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new Ke;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 l=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),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.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*Je/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 _r;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<lt.SEE_THROUGH_BELOW||s instanceof no))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=lt.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new sl().copy(n).applyMatrix4(new Wt().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,lt.RAILWAY_PICK_ABOVE_M))return;const c=lt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-lt.RAILWAY_GROUND_MARGIN_M,y0))return;const l=i.group.worldToLocal(c.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const u=i.contactHeightM(h);return{line:h,distanceM:c.distance,...u!==void 0?{contactM:u}:{}}}pickSkyEventAt(t,e,i=()=>!0){const n=[...this.skyEventLayers.values()].filter(l=>l.simulation?.pick&&l.simulation.drawnCount>0&&i(l.kind,l.simulation));if(n.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray,r={toleranceRad:lt.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(w0*this.camera.fov*Math.PI/180),skyLightTowards:l=>this.skyLightTowards(l)};let a;for(const l of n){const h=l.simulation.pick(s.origin,s.direction,r);h&&(!a||(h.distanceM??1/0)<(a.distanceM??1/0))&&(a={kind:l.kind.key,...h})}if(!a)return;if(a.distanceM===void 0)return this.groundHides(t,e)?void 0:a;if(this.terrainMesh&&this.groundBlocks(s.origin,s.direction,a.distanceM-1,y0))return;const c=lt.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(c&&c.distance<a.distanceM))return a}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const t of this.skyEventLayers.values())t.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())ut.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<lt.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new an(M0,32,16),i=e.attributes.position,n=e.getAttribute("color")??new fe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=hA(i.getX(r),i.getY(r),i.getZ(r)),l=nP(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new Ms({vertexColors:!0,side:Oi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Mt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=Pb(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new FM(this.groundRadius,48),i=new pr({color:new rt(t1,t1,t1),fog:!0});$c.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Mt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=xi(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-Ne.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*HL);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Ne.iceAlphaAt(i,S0,r,this.cloudFieldOffset)*GL),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<Z0){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}=xi(e.altitudeDeg,e.azimuthDeg,ls),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,s,l),u=lt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/ls)**2,p=[0,1,2].map(g=>u[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(lt.BRIGHTEST_RELATIVE,g));d instanceof Mt||(this.disposeMesh(d),d=new Mt(new an(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(m[0],m[1],m[2]),d.scale.setScalar(i)}else{if(!(d instanceof Xs)){this.disposeMesh(d);const m=new ye;m.setAttribute("position",new ve(new Float32Array(3),3)),m.setAttribute("color",new ve(new Float32Array(3),3)),d=new Xs(m,Gt.material(Ch[Ch.length-1].size,!1)),Gt.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]*h[0]*p,u[1]*h[1]*p,u[2]*h[2]*p),f.needsUpdate=!0}if(d.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,h,i/ls*(180/Math.PI),lt.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,c*f),this.lensFlare||(this.lensFlare=jN(),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<Z0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=xi(t.altitudeDeg,t.azimuthDeg,ls),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??ra.MEAN_RADIUS_DEG,h=ls*Math.tan(l*Je),u=Math.max($r(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/ls)**2,d=new rt(...c.map(m=>Math.min(lt.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round($r(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof pu?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=aS(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new pu(new G0({map:aS(t.phase),color:d,fog:!1,blending:_n,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(h*2,h*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,c,l)}bentLight(t,e,i=zL){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return lt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new rt;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Gt.CONE_SOLID_ANGLE/e)}pointScratch=new tt;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=Ue.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Cs.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 G0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new pu(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(xn.radiusDeg(xn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new xn(`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=oh(t.magnitude,e),s=Ig(n);this.cometKey=i,this.setBodyMesh(i,t.position,s1*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new Vs(ls),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Xi,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:S0},0);return}const s=this.lowerCloudCover(),r=we.deckLitUntilDeg(we.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?de.SUN_MAGNITUDE:e.magnitude),l=we.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=xi(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},a.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??S0},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??M3,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Uc,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?de.SUN_MAGNITUDE:e.magnitude,BL),c=Gs.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:l,y:h,z:u}=xi(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Oo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=Sr.galactic(i,n),r=lt.directionOf(s.centre),a=lt.directionOf(s.rotation),c=lt.directionOf(s.pole),l=new ue().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=lt.directionOf(Sr.eclipticPole(i,n)),u=lt.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:lt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:_t.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}=xi(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=oh(n.magnitude,e),a=Ig(r);this.setBodyMesh(s,n.position,s1*(.5+.5*r),new rt(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=oh(n.magnitude,e),r=Ig(s),a=x9[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),l=s1*(.5+.5*s);this.setBodyMesh(n.body,n.position,l,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 Tr(n,s),a=p1(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<Lb)continue;const{x:p,y:m,z:g}=xi(d,f,e1);c.push({x:p,y:m,z:g,brightness:oh(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Ue.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of RN){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<Lb)continue;const{x:f,y:p,z:m}=xi(u,d,e1);this.namedStars.push({star:h,direction:new R(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=Ch.map((h,u)=>{const d=c.filter(w=>qM(w.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),m=new Float32Array(d.length*3),g=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((w,S)=>{f[S*3]=w.x,f[S*3+1]=w.y,f[S*3+2]=w.z,p[S]=w.brightness,m.set(w.illuminance,S*3),g[S]=w.phase,v[S]=w.speedFactor});const M=new ye;M.setAttribute("position",new ve(f,3)),M.setAttribute("seed",new ve(g.map(w=>w/(2*Math.PI)),1));const x=new ve(new Float32Array(d.length*3),3);M.setAttribute("color",x);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new Xs(M,Gt.material(h.size)),Gt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:x,brightness:p,illuminance:m,phase:g,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Gt.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 Dh(this.celestialGroup,r1,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new rt(yc[0]+(c1[0]-yc[0])*e,yc[1]+(c1[1]-yc[1])*e,yc[2]+(c1[2]-yc[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}=Ev(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=Av(r1);this.cloudMesh=new Mt(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=Ev(new rt(...yc),t,S0,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Mt(Av(r1*1.04),e),this.cirrusMesh.renderOrder=Wb-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?Dh.deckOrder(!0,0,1):Wb}cloudLayerOffset(){const e=((this.weather.cloudBaseM??dM)-this.observerElevationM)*a1;return Math.sign(e||1)*Math.max(Math.abs(e),i9)}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*f1*this.relativeScale/Math.PI,l=new rt(e[0]+Hr.r*c,e[1]+Hr.g*c,e[2]+Hr.b*c);this.layeredClouds?.setLighting(n.clone(),new rt(s,r,a),l,l);const h=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*h,r*h,a*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return h9(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,u1],[this.rainSplashSystem?.points,xc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:l1[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=Kb(d1(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=l1[t],i=e.poolSize,n=p1(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),l=new Float32Array(i),h=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 y=n()*Math.PI*2,w=n()*e.radiusM;s[x*3]=Math.cos(y)*w,s[x*3+1]=Zl+n()*(e.topYM-Zl),s[x*3+2]=Math.sin(y)*w,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,l[x]=.4+n()*1.2}const m=new ye;m.setAttribute("position",new ve(s,3)),m.setDrawRange(0,this.precipitationCount(i));const g={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new rt(...this.baseFogColor)},uTexture:{value:w9(t)},uNearFocusDistance:{value:jb},uHazeDistance:{value:e.radiusM*Qb}},v=new Re({uniforms:g,vertexShader:T9,fragmentShader:R9,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const M=new Xs(m,v);M.renderOrder=o1,this.scene.add(M),this.precipitationPoints=M,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,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=l1[i];if(this.precipitationUniforms?.uColor.value.copy(lt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*Je,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,m=this.precipitationBounceDuration,g=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,M=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&m&&g&&v;for(let y=0,w=0;y<c.length;y+=3,w++){if(x&&f[w]>0){if(f[w]-=e,f[w]<=0){const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(b)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(b)*A,f[w]=0}else{const b=1-f[w]/m[w];c[y+1]=Zl+Math.sin(Math.PI*b)*p[w],c[y]=A0(c[y]+(r+g[w])*e,n.radiusM),c[y+2]=A0(c[y+2]+(a+v[w])*e,n.radiusM)}continue}let S=0,E=0;if(M){const b=d9*u[w],A=f9*d[w];S=Math.sin(t*b*Math.PI*2+l[w])*A,E=Math.sin(t*b*Math.PI*2+l[w]+Math.PI/2)*A}if(c[y]+=(r+S)*e,c[y+1]-=n.fallSpeedMPerS*h[w]*e,c[y+2]+=(a+E)*e,c[y]=A0(c[y],n.radiusM),c[y+2]=A0(c[y+2],n.radiusM),c[y+1]<Zl){if(x){p[w]=sS*(.2+Math.random()*1.6),m[w]=p9*(.5+Math.random()),f[w]=m[w];const _=Math.random()*Math.PI*2,I=m9*(p[w]/sS);g[w]=Math.cos(_)*I,v[w]=Math.sin(_)*I,c[y+1]=Zl;continue}const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(b)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(b)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=d1(this.weather.precipitationIntensity);this.rainSystem=qN({count:u1,radiusM:Nu,heightM:s9,bottomYM:Xb,overallSpeed:r9,color:Yb.clone(),opacity:.85,visibleCount:this.precipitationCount(u1),speedStreak:Kb(t),pixelSize:eS,seed:9001,nearFocusDistanceM:jb,hazeDistanceM:Nu*Qb,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=o1,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=p1(4242),e=new Float32Array(xc*3),i=new Float32Array(xc),n=new Float32Array(xc),s=new Float32Array(xc);for(let h=0;h<xc;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Nu;e[h*3]=Math.cos(u)*d,e[h*3+1]=Xb,e[h*3+2]=Math.sin(u)*d,n[h]=rS(qb,Zb),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new ye;r.setAttribute("position",new ve(e,3));const a=new ve(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(xc));const c=new Re({uniforms:{uMaxSize:{value:l9},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Jb.clone()},uTexture:{value:E9()}},vertexShader:A9,fragmentShader:_9,transparent:!0,depthWrite:!1}),l=new Xs(r,c);l.renderOrder=o1,this.scene.add(l),this.rainSplashSystem={points:l,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*Je;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-d1(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(lt.litBySky(Yb,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(lt.litBySky(Jb,this.baseFogColor));const n=this.weather.windDirectionDeg*Je,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Nu,c=h=>(h%(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 l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=iS+(1-iS)*(1-l),u=nS+(1-nS)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=eS*h*(.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,l=0;c<i.length;c+=3,l++){if(n[l]+=t,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Nu;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=rS(qb,Zb),n[l]=0}a[l]=n[l]/s[l]}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 l=gn.brightnessAt(c,t);l>i&&(e=c,i=l)}const n=e?Math.min(1,Math.max(.1,(M9/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,l=s*f1*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Hr.r*l,this.airlight[1]+Hr.g*l,this.airlight[2]+Hr.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*y9;r.setRGB(1+c*Hr.r,1+c*Hr.g,1+c*Hr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*f1*this.relativeScale,e){const{x:c,y:l,z:h}=xi(25,e.azimuthDeg,ls);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new Po(ls*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=JL.map(t=>{const e=Xc.point(t,this.compassPoints),i=new G0({map:I9(e),depthTest:!1,fog:!1}),n=new pu(i),{x:s,y:r,z:a}=xi(0,t,zb);return n.position.set(s,r,a),n.scale.set(E0,E0,1),n.renderOrder=t9,n.layers.set(Qg),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=Bb*Math.PI/360,i=E0*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 Je=Math.PI/180;function $r(o,t,e){return Math.max(t,Math.min(e,o))}function rS(o,t){return o+Math.random()*(t-o)}function A0(o,t){return(o%(t*2)+t*3)%(t*2)-t}let _0,T0;function w9(o){switch(o){case"snow":return b9();case"hail":return S9()}}function b9(){if(_0)return _0;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),_0=new cc(t),_0}function S9(){if(T0)return T0;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),T0=new cc(t),T0}let R0;function E9(){if(R0)return R0;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),R0=new cc(t),R0}const A9=`
|
|
9266
|
+
`,transparent:!0,blending:_n,depthWrite:!1,side:Oi,fog:!1});this.object=new Mt(new an(cy.RADIUS,128,32,0,Math.PI*2,0,Ue.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Ue.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=kn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=kn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class Up{constructor(t){this.generator=t}static SIZE=128;target=new Xd(Up.SIZE,{type:We,generateMipmaps:!0,minFilter:qs,magFilter:ge});camera=new $M(.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 l=c;l.isLight&&l.castShadow&&l.shadow&&!l.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,l)=>{c.visible=a[l]}),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 Qn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Qn.install(),this.generator=new xv(t),this.eye=new Up(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=Qn.REFRESH_MS){for(const g of[...this.probes.keys()])n.some(v=>v.id===g&&v.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const u=[{probe:this.eye}];for(const g of n){if(!g.shiny)continue;let v=this.probes.get(g.id);v||(v=new Up(this.generator),this.probes.set(g.id,v)),u.push({probe:v,reflector:g})}const d=performance.now(),f=()=>u.filter(({probe:g})=>g.capturedVersion!==a),p=f().filter(({probe:g})=>d-g.capturedAtMs>=h);if(p.length>0){const g=p.reduce((v,M)=>M.probe.capturedAtMs<v.probe.capturedAtMs?M:v);if(g.reflector){const v=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,v,[g.reflector.holder,...s]),Qn.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),l?.(g.probe.sharp),Qn.decor=g.probe.filtered;for(const v of r)Qn.reflectOn(v,g.probe);for(const v of n)v.shiny||Qn.reflectOn(v.holder,g.probe)}g.probe.capturedVersion=a}const m=f();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:g})=>h-(d-g.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:Qn.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof no?e.sharp&&s.setSurroundings(e.sharp):s instanceof Fo&&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(Qn.installed)return;Qn.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!he.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}he.lights_fragment_maps=he.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const YA=0,P8=1,N8=2,pb=2,Hg=1.25,mb=1,ns=32,Sn=ns/4,KA=65535,K0=Math.pow(2,-24),ly=Symbol("SKIP_GENERATION"),qA={strategy:YA,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[ly]:!1};function Yi(o,t,e){return e.min.x=t[o],e.min.y=t[o+1],e.min.z=t[o+2],e.max.x=t[o+3],e.max.y=t[o+4],e.max.z=t[o+5],e}function tM(o){let t=-1,e=-1/0;for(let i=0;i<3;i++){const n=o[i+3]-o[i];n>e&&(e=n,t=i)}return t}function gb(o,t){t.set(o)}function vb(o,t,e){let i,n;for(let s=0;s<3;s++){const r=s+3;i=o[s],n=t[s],e[s]=i<n?i:n,i=o[r],n=t[r],e[r]=i>n?i:n}}function n0(o,t,e){for(let i=0;i<3;i++){const n=t[o+2*i],s=t[o+2*i+1],r=n-s,a=n+s;r<e[i]&&(e[i]=r),a>e[i+3]&&(e[i+3]=a)}}function _u(o){const t=o[3]-o[0],e=o[4]-o[1],i=o[5]-o[2];return 2*(t*e+e*i+i*t)}function sn(o,t){return t[o+15]===KA}function Un(o,t){return t[o+6]}function ss(o,t){return t[o+14]}function En(o){return o+Sn}function An(o,t){const e=t[o+6];return o+e*Sn}function hy(o,t){return t[o+7]}function Gg(o,t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,g=-1/0;const v=o.offset||0;for(let M=(t-v)*6,x=(t+e-v)*6;M<x;M+=6){const y=o[M+0],w=o[M+1],S=y-w,E=y+w;S<s&&(s=S),E>c&&(c=E),y<u&&(u=y),y>p&&(p=y);const b=o[M+2],A=o[M+3],_=b-A,I=b+A;_<r&&(r=_),I>l&&(l=I),b<d&&(d=b),b>m&&(m=b);const D=o[M+4],O=o[M+5],L=D-O,P=D+O;L<a&&(a=L),P>h&&(h=P),D<f&&(f=D),D>g&&(g=D)}i[0]=s,i[1]=r,i[2]=a,i[3]=c,i[4]=l,i[5]=h,n[0]=u,n[1]=d,n[2]=f,n[3]=p,n[4]=m,n[5]=g}const Ha=32,L8=(o,t)=>o.candidate-t.candidate,Eo=new Array(Ha).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),s0=new Float32Array(6);function k8(o,t,e,i,n,s){let r=-1,a=0;if(s===YA)r=tM(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(s===P8)r=tM(o),r!==-1&&(a=U8(e,i,n,r));else if(s===N8){const c=_u(o);let l=Hg*n;const h=e.offset||0,u=(i-h)*6,d=(i+n-h)*6;for(let f=0;f<3;f++){const p=t[f],v=(t[f+3]-p)/Ha;if(n<Ha/4){const M=[...Eo];M.length=n;let x=0;for(let w=u;w<d;w+=6,x++){const S=M[x];S.candidate=e[w+2*f],S.count=0;const{bounds:E,leftCacheBounds:b,rightCacheBounds:A}=S;for(let _=0;_<3;_++)A[_]=1/0,A[_+3]=-1/0,b[_]=1/0,b[_+3]=-1/0,E[_]=1/0,E[_+3]=-1/0;n0(w,e,E)}M.sort(L8);let y=n;for(let w=0;w<y;w++){const S=M[w];for(;w+1<y&&M[w+1].candidate===S.candidate;)M.splice(w+1,1),y--}for(let w=u;w<d;w+=6){const S=e[w+2*f];for(let E=0;E<y;E++){const b=M[E];S>=b.candidate?n0(w,e,b.rightCacheBounds):(n0(w,e,b.leftCacheBounds),b.count++)}}for(let w=0;w<y;w++){const S=M[w],E=S.count,b=n-S.count,A=S.leftCacheBounds,_=S.rightCacheBounds;let I=0;E!==0&&(I=_u(A)/c);let D=0;b!==0&&(D=_u(_)/c);const O=mb+Hg*(I*E+D*b);O<l&&(r=f,l=O,a=S.candidate)}}else{for(let y=0;y<Ha;y++){const w=Eo[y];w.count=0,w.candidate=p+v+y*v;const S=w.bounds;for(let E=0;E<3;E++)S[E]=1/0,S[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/v);E>=Ha&&(E=Ha-1);const b=Eo[E];b.count++,n0(y,e,b.bounds)}const M=Eo[Ha-1];gb(M.bounds,M.rightCacheBounds);for(let y=Ha-2;y>=0;y--){const w=Eo[y],S=Eo[y+1];vb(w.bounds,S.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let y=0;y<Ha-1;y++){const w=Eo[y],S=w.count,E=w.bounds,A=Eo[y+1].rightCacheBounds;S!==0&&(x===0?gb(E,s0):vb(E,s0,s0)),x+=S;let _=0,I=0;x!==0&&(_=_u(s0)/c);const D=n-x;D!==0&&(I=_u(A)/c);const O=mb+Hg*(_*x+I*D);O<l&&(r=f,l=O,a=w.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function U8(o,t,e,i){let n=0;const s=o.offset;for(let r=t,a=t+e;r<a;r++)n+=o[(r-s)*6+i*2];return n/e}class Vg{constructor(){this.boundingData=new Float32Array(6)}}function F8(o,t,e,i,n,s){let r=i,a=i+n-1;const c=s.pos,l=s.axis*2,h=e.offset||0;for(;;){for(;r<=a&&e[(r-h)*6+l]<c;)r++;for(;r<=a&&e[(a-h)*6+l]>=c;)a--;if(r<a){for(let u=0;u<t;u++){let d=o[r*t+u];o[r*t+u]=o[a*t+u],o[a*t+u]=d}for(let u=0;u<6;u++){const d=r-h,f=a-h,p=e[d*6+u];e[d*6+u]=e[f*6+u],e[f*6+u]=p}r++,a--}else return r}}let ZA,q0,eM,JA;const z8=Math.pow(2,32);function iM(o){return"count"in o?1:1+iM(o.left)+iM(o.right)}function B8(o,t,e){return ZA=new Float32Array(e),q0=new Uint32Array(e),eM=new Uint16Array(e),JA=new Uint8Array(e),nM(o,t)}function nM(o,t){const e=o/4,i=o/2,n="count"in t,s=t.boundingData;for(let r=0;r<6;r++)ZA[e+r]=s[r];if(n)return t.buffer?(JA.set(new Uint8Array(t.buffer),o),o+t.buffer.byteLength):(q0[e+6]=t.offset,eM[i+14]=t.count,eM[i+15]=KA,o+ns);{const{left:r,right:a,splitAxis:c}=t,l=o+ns;let h=nM(l,r);const u=o/ns,f=h/ns-u;if(f>z8)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return q0[e+6]=f,q0[e+7]=c,nM(h,a)}}function H8(o,t,e,i,n,s){const{maxDepth:r,verbose:a,targetLeafSize:c,_strictLeafSize:l=1/0,strategy:h,onProgress:u}=n,d=o.primitiveBuffer,f=o.primitiveBufferStride,p=new Float32Array(6);let m=!1;const g=new Vg;return Gg(t,e,i,g.boundingData,p),M(g,e,i,p),g;function v(x){u&&u((x-s.offset)/s.count)}function M(x,y,w,S=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const b=w>l;if(w<=c&&!b||E>=r)return v(y+w),x.offset=y,x.count=w,x;const A=k8(x.boundingData,S,t,y,w,h);let _=A.axis===-1?-1:F8(d,f,t,y,w,A);if(A.axis===-1||_===y||_===y+w){if(!b)return v(y+w),x.offset=y,x.count=w,x;A.axis=Math.max(0,tM(x.boundingData)),_=y+Math.max(1,Math.floor(w/2))}x.splitAxis=A.axis;const I=new Vg,D=y,O=_-y;x.left=I,Gg(t,D,O,I.boundingData,p),M(I,D,O,p,E+1);const L=new Vg,P=_,k=w-O;return x.right=L,Gg(t,P,k,L.boundingData,p),M(L,P,k,p,E+1),x}}function G8(o,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=o.getRootRanges(t.range),n=i[0],s=i[i.length-1],r={offset:n.offset,count:s.offset+s.count-n.offset},a=new Float32Array(6*r.count);a.offset=r.offset,o.computePrimitiveBounds(r.offset,r.count,a),o._roots=i.map(c=>{const l=H8(o,a,c.offset,c.count,t,r),h=iM(l),u=new e(ns*h);return B8(0,l,u),u})}class uy{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class V8{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const Ni=new V8;let Jo,mh;const kl=[],r0=new uy(()=>new Ke);function W8(o,t,e,i,n,s){Jo=r0.getPrimitive(),mh=r0.getPrimitive(),kl.push(Jo,mh),Ni.setBuffer(o._roots[t]);const r=sM(0,o.geometry,e,i,n,s);Ni.clearBuffer(),r0.releasePrimitive(Jo),r0.releasePrimitive(mh),kl.pop(),kl.pop();const a=kl.length;return a>0&&(mh=kl[a-1],Jo=kl[a-2]),r}function sM(o,t,e,i,n=null,s=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:l}=Ni;let h=o*2;if(sn(h,c)){const d=Un(o,l),f=ss(h,c);return Yi(o,a,Jo),i(d,f,!1,r,s+o/Sn,Jo)}else{let _=function(D){const{uint16Array:O,uint32Array:L}=Ni;let P=D*2;for(;!sn(P,O);)D=En(D),P=D*2;return Un(D,L)},I=function(D){const{uint16Array:O,uint32Array:L}=Ni;let P=D*2;for(;!sn(P,O);)D=An(D,L),P=D*2;return Un(D,L)+ss(P,O)};const d=En(o),f=An(o,l);let p=d,m=f,g,v,M,x;if(n&&(M=Jo,x=mh,Yi(p,a,M),Yi(m,a,x),g=n(M),v=n(x),v<g)){p=f,m=d;const D=g;g=v,v=D,M=x}M||(M=Jo,Yi(p,a,M));const y=sn(p*2,c),w=e(M,y,g,r+1,s+p/Sn);let S;if(w===pb){const D=_(p),L=I(p)-D;S=i(D,L,!0,r+1,s+p/Sn,M)}else S=w&&sM(p,t,e,i,n,s,r+1);if(S)return!0;x=mh,Yi(m,a,x);const E=sn(m*2,c),b=e(x,E,v,r+1,s+m/Sn);let A;if(b===pb){const D=_(m),L=I(m)-D;A=i(D,L,!0,r+1,s+m/Sn,x)}else A=b&&sM(m,t,e,i,n,s,r+1);return!!A}}const ad=new Ni.constructor,Fp=new Ni.constructor,No=new uy(()=>new Ke),Ul=new Ke,Fl=new Ke,Wg=new Ke,Xg=new Ke;let $g=!1;function X8(o,t,e,i){if($g)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");$g=!0;const n=o._roots,s=t._roots;let r,a=0,c=0;const l=new Wt().copy(e).invert();for(let h=0,u=n.length;h<u;h++){ad.setBuffer(n[h]),c=0;const d=No.getPrimitive();Yi(0,ad.float32Array,d),d.applyMatrix4(l);for(let f=0,p=s.length;f<p&&(Fp.setBuffer(s[f]),r=Mr(0,0,e,l,i,a,c,0,0,d),Fp.clearBuffer(),c+=s[f].byteLength/ns,!r);f++);if(No.releasePrimitive(d),ad.clearBuffer(),a+=n[h].byteLength/ns,r)break}return $g=!1,r}function Mr(o,t,e,i,n,s=0,r=0,a=0,c=0,l=null,h=!1){let u,d;h?(u=Fp,d=ad):(u=ad,d=Fp);const f=u.float32Array,p=u.uint32Array,m=u.uint16Array,g=d.float32Array,v=d.uint32Array,M=d.uint16Array,x=o*2,y=t*2,w=sn(x,m),S=sn(y,M);let E=!1;if(S&&w)h?E=n(Un(t,v),ss(t*2,M),Un(o,p),ss(o*2,m),c,r+t/Sn,a,s+o/Sn):E=n(Un(o,p),ss(o*2,m),Un(t,v),ss(t*2,M),a,s+o/Sn,c,r+t/Sn);else if(S){const b=No.getPrimitive();Yi(t,g,b),b.applyMatrix4(e);const A=En(o),_=An(o,p);Yi(A,f,Ul),Yi(_,f,Fl);const I=b.intersectsBox(Ul),D=b.intersectsBox(Fl);E=I&&Mr(t,A,i,e,n,r,s,c,a+1,b,!h)||D&&Mr(t,_,i,e,n,r,s,c,a+1,b,!h),No.releasePrimitive(b)}else{const b=En(t),A=An(t,v);Yi(b,g,Wg),Yi(A,g,Xg);const _=l.intersectsBox(Wg),I=l.intersectsBox(Xg);if(_&&I)E=Mr(o,b,e,i,n,s,r,a,c+1,l,h)||Mr(o,A,e,i,n,s,r,a,c+1,l,h);else if(_)if(w)E=Mr(o,b,e,i,n,s,r,a,c+1,l,h);else{const D=No.getPrimitive();D.copy(Wg).applyMatrix4(e);const O=En(o),L=An(o,p);Yi(O,f,Ul),Yi(L,f,Fl);const P=D.intersectsBox(Ul),k=D.intersectsBox(Fl);E=P&&Mr(b,O,i,e,n,r,s,c,a+1,D,!h)||k&&Mr(b,L,i,e,n,r,s,c,a+1,D,!h),No.releasePrimitive(D)}else if(I)if(w)E=Mr(o,A,e,i,n,s,r,a,c+1,l,h);else{const D=No.getPrimitive();D.copy(Xg).applyMatrix4(e);const O=En(o),L=An(o,p);Yi(O,f,Ul),Yi(L,f,Fl);const P=D.intersectsBox(Ul),k=D.intersectsBox(Fl);E=P&&Mr(A,O,i,e,n,r,s,c,a+1,D,!h)||k&&Mr(A,L,i,e,n,r,s,c,a+1,D,!h),No.releasePrimitive(D)}}return E}const Yg=new class{constructor(){let o=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(s,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=o=s._roots[r],this.uint16Array=e=new Uint16Array(o),this.uint32Array=t=new Uint32Array(o)},this.reset=()=>{this.root=null,this.buffer=o=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=s=>{let r=s*2;for(;!sn(r,e);)s=En(s),r=s*2;return Un(s,t)},this.getRangeEnd=s=>{let r=s*2;for(;!sn(r,e);)s=An(s,t),r=s*2;return Un(s,t)+ss(r,e)};const n=(s,r,a)=>{const c=r*2,l=sn(c,e);if(!s(a,l,r)&&!l){const u=En(r),d=An(r,t);n(s,u,a+1),n(s,d,a+1)}};this.traverseBuffer=s=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{n(s,0,0)}finally{i=!1}},this.traverse=s=>{this.traverseBuffer((r,a,c)=>{if(a){const l=c*2,h=t[c+6],u=e[l+14];return s(r,a,new Float32Array(o,c*4,6),h,u)}else{const l=hy(c,t);return s(r,a,new Float32Array(o,c*4,6),l)}})}}},Mb=new Ke,zl=new Float32Array(6);class $8{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...qA,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),G8(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0;for(let u=t,d=t+e;u<d;u++){this.writePrimitiveBounds(u,zl,0);const[f,p,m,g,v,M]=zl;f<s&&(s=f),g>c&&(c=g),p<r&&(r=p),v>l&&(l=v),m<a&&(a=m),M>h&&(h=M)}return i[n+0]=s,i[n+1]=r,i[n+2]=a,i[n+3]=c,i[n+4]=l,i[n+5]=h,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,zl,0);const[a,c,l,h,u,d]=zl,f=(a+h)/2,p=(c+u)/2,m=(l+d)/2,g=(h-a)/2,v=(u-c)/2,M=(d-l)/2,x=(s-n)*6;i[x+0]=f,i[x+1]=g+(Math.abs(f)+g)*K0,i[x+2]=p,i[x+3]=v+(Math.abs(p)+v)*K0,i[x+4]=m,i[x+5]=M+(Math.abs(m)+M)*K0}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const i=this._roots;for(let n=0;n<i.length;n++){const s=i[n],r=new Uint32Array(s),a=new Uint16Array(s),c=s.byteLength/ns;for(let l=0;l<c;l++){const h=Sn*l,u=2*h;sn(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){Yg.setBVH(this,e),Yg.traverse(t),Yg.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const n=t[e],s=new Uint32Array(n),r=new Uint16Array(n),a=new Float32Array(n),c=n.byteLength/ns;for(let l=c-1;l>=0;l--){const h=l*Sn,u=h*2;if(sn(u,r)){const f=Un(h,s),p=ss(u,r);this.writePrimitiveRangeBounds(f,p,zl,0),a.set(zl,h)}else{const f=En(h),p=An(h,s);for(let m=0;m<3;m++){const g=a[f+m],v=a[f+m+3],M=a[p+m],x=a[p+m+3];a[h+m]=g<M?g:M,a[h+m+3]=v>x?v:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{Yi(0,new Float32Array(i),Mb),t.union(Mb)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:a}=t;if(n&&s){const u=n;n=(d,f,p,m,g)=>u(d,f,p,m,g)?!0:a(d,f,this,s,p,m,r)}else n||(s?n=(u,d,f,p)=>a(u,d,this,s,f,p,r):n=(u,d,f)=>f);let c=!1,l=0;const h=this._roots;for(let u=0,d=h.length;u<d;u++){const f=h[u];if(c=W8(this,u,i,n,e,l),c)break;l+=f.byteLength/ns}return c}bvhcast(t,e,i){let{intersectsRanges:n}=i;return X8(this,t,e,n)}}function Y8(){return typeof SharedArrayBuffer<"u"}function dy(o){return o.index?o.index.count:o.attributes.position.count}function gm(o){return dy(o)/3}function K8(o,t=ArrayBuffer){return o>65535?new Uint32Array(new t(4*o)):new Uint16Array(new t(2*o))}function q8(o,t){if(!o.index){const e=o.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=K8(e,i);o.setIndex(new ve(n,1));for(let s=0;s<e;s++)n[s]=s}}function Z8(o,t,e){const i=dy(o)/e,n=t||o.drawRange,s=n.start/e,r=(n.start+n.count)/e,a=Math.max(0,s),c=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function J8(o,t){return o.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function yb(o,t,e){const i=Z8(o,t,e),n=J8(o,e);if(!n.length)return[i];const s=[],r=i.offset,a=i.offset+i.count,c=dy(o)/e,l=[];for(const d of n){const{offset:f,count:p}=d,m=f,g=isFinite(p)?p:c-f,v=f+g;m<a&&v>r&&(l.push({pos:Math.max(r,m),isStart:!0}),l.push({pos:Math.min(a,v),isStart:!1}))}l.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,u=null;for(const d of l){const f=d.pos;h!==0&&f!==u&&s.push({offset:u,count:f-u}),h+=d.isStart?1:-1,u=f}return s}function j8(o,t){const e=o[o.length-1],i=e.offset+e.count>2**16,n=o.reduce((l,h)=>l+h.count,0),s=i?4:2,r=t?new SharedArrayBuffer(n*s):new ArrayBuffer(n*s),a=i?new Uint32Array(r):new Uint16Array(r);let c=0;for(let l=0;l<o.length;l++){const{offset:h,count:u}=o[l];for(let d=0;d<u;d++)a[c+d]=h+d;c+=u}return a}class Q8 extends $8{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Y8())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...qA,...e},e[ly]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=yb(e,t.range,i),s=j8(n,t.useSharedArrayBuffer);this._indirectBuffer=s}else q8(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Ke))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:yb(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class oo{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const c=t[s][e];i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const a=e[s],c=t.dot(a);i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}oo.prototype.setFromBox=(function(){const o=new R;return function(e,i){const n=i.min,s=i.max;let r=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let l=0;l<=1;l++)for(let h=0;h<=1;h++){o.x=n.x*c+s.x*(1-c),o.y=n.y*l+s.y*(1-l),o.z=n.z*h+s.z*(1-h);const u=e.dot(o);r=Math.min(u,r),a=Math.max(u,a)}this.min=r,this.max=a}})();const tL=(function(){const o=new R,t=new R,e=new R;return function(n,s,r){const a=n.start,c=o,l=s.start,h=t;e.subVectors(a,l),o.subVectors(n.end,n.start),t.subVectors(s.end,s.start);const u=e.dot(h),d=h.dot(c),f=h.dot(h),p=e.dot(c),g=c.dot(c)*f-d*d;let v,M;g!==0?v=(u*d-p*f)/g:v=0,M=(u+v*d)/f,r.x=v,r.y=M}})(),fy=(function(){const o=new tt,t=new R,e=new R;return function(n,s,r,a){tL(n,s,o);let c=o.x,l=o.y;if(c>=0&&c<=1&&l>=0&&l<=1){n.at(c,r),s.at(l,a);return}else if(c>=0&&c<=1){l<0?s.at(0,a):s.at(1,a),n.closestPointToPoint(a,!0,r);return}else if(l>=0&&l<=1){c<0?n.at(0,r):n.at(1,r),s.closestPointToPoint(r,!0,a);return}else{let h;c<0?h=n.start:h=n.end;let u;l<0?u=s.start:u=s.end;const d=t,f=e;if(n.closestPointToPoint(u,!0,t),s.closestPointToPoint(h,!0,e),d.distanceToSquared(u)<=f.distanceToSquared(h)){r.copy(d),a.copy(u);return}else{r.copy(h),a.copy(f);return}}}})(),eL=(function(){const o=new R,t=new R,e=new _r,i=new ro;return function(s,r){const{radius:a,center:c}=s,{a:l,b:h,c:u}=r;if(i.start=l,i.end=h,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a||(i.start=l,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a))return!0;const m=r.getPlane(e);if(Math.abs(m.distanceToPoint(c))<=a){const v=m.projectPoint(c,t);if(r.containsPoint(v))return!0}return!1}})(),iL=["x","y","z"],Va=1e-15,xb=Va*Va;function ir(o){return Math.abs(o)<Va}class Pr extends Ln{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new R),this.satBounds=new Array(4).fill().map(()=>new oo),this.points=[this.a,this.b,this.c],this.plane=new _r,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new ro,this.needsUpdate=!0}intersectsSphere(t){return eL(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,a=s[0],c=r[0];this.getNormal(a),c.setFromPoints(a,n);const l=s[1],h=r[1];l.subVectors(t,e),h.setFromPoints(l,n);const u=s[2],d=r[2];u.subVectors(e,i),d.setFromPoints(u,n);const f=s[3],p=r[3];f.subVectors(i,t),p.setFromPoints(f,n);const m=l.length(),g=u.length(),v=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Va?g<Va||v<Va?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):g<Va?v<Va?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):v<Va&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}Pr.prototype.closestPointToSegment=(function(){const o=new R,t=new R,e=new ro;return function(n,s=null,r=null){const{start:a,end:c}=n,l=this.points;let h,u=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(l[d]),e.end.copy(l[f]),fy(e,n,o,t),h=o.distanceToSquared(t),h<u&&(u=h,s&&s.copy(o),r&&r.copy(t))}return this.closestPointToPoint(a,o),h=a.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(a)),this.closestPointToPoint(c,o),h=c.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(c)),Math.sqrt(u)}})();Pr.prototype.intersectsTriangle=(function(){const o=new Pr,t=new oo,e=new oo,i=new R,n=new R,s=new R,r=new R,a=new ro,c=new ro,l=new R,h=new tt,u=new tt;function d(x,y,w,S){const E=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?E.copy(x.plane.normal):E.copy(y.plane.normal);const b=x.satBounds,A=x.satAxes;for(let D=1;D<4;D++){const O=b[D],L=A[D];if(t.setFromPoints(L,y.points),O.isSeparated(t)||(r.copy(E).cross(L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}const _=y.satBounds,I=y.satAxes;for(let D=1;D<4;D++){const O=_[D],L=I[D];if(t.setFromPoints(L,x.points),O.isSeparated(t)||(r.crossVectors(E,L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}return w&&(S||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function f(x,y,w,S,E,b,A,_,I,D,O){let L=A/(A-_);D.x=S+(E-S)*L,O.start.subVectors(y,x).multiplyScalar(L).add(x),L=A/(A-I),D.y=S+(b-S)*L,O.end.subVectors(w,x).multiplyScalar(L).add(x)}function p(x,y,w,S,E,b,A,_,I,D,O){if(E>0)f(x.c,x.a,x.b,S,y,w,I,A,_,D,O);else if(b>0)f(x.b,x.a,x.c,w,y,S,_,A,I,D,O);else if(_*I>0||A!=0)f(x.a,x.b,x.c,y,w,S,A,_,I,D,O);else if(_!=0)f(x.b,x.a,x.c,w,y,S,_,A,I,D,O);else if(I!=0)f(x.c,x.a,x.b,S,y,w,I,A,_,D,O);else return!0;return!1}function m(x,y,w,S){const E=y.degenerateSegment,b=x.plane.distanceToPoint(E.start),A=x.plane.distanceToPoint(E.end);return ir(b)?ir(A)?d(x,y,w,S):(w&&(w.start.copy(E.start),w.end.copy(E.start)),x.containsPoint(E.start)):ir(A)?(w&&(w.start.copy(E.end),w.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function g(x,y,w){const S=y.a;return ir(x.plane.distanceToPoint(S))&&x.containsPoint(S)?(w&&(w.start.copy(S),w.end.copy(S)),!0):!1}function v(x,y,w){const S=x.degenerateSegment,E=y.a;return S.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<xb?(w&&(w.start.copy(E),w.end.copy(E)),!0):!1}function M(x,y,w,S){if(x.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=x.degenerateSegment,b=y.degenerateSegment,A=n,_=s;E.delta(A),b.delta(_);const I=i.subVectors(b.start,E.start),D=A.x*_.y-A.y*_.x;if(ir(D))return!1;const O=(I.x*_.y-I.y*_.x)/D,L=-(A.x*I.y-A.y*I.x)/D;if(O<0||O>1||L<0||L>1)return!1;const P=E.start.z+A.z*O,k=b.start.z+_.z*L;return ir(P-k)?(w&&(w.start.copy(E.start).addScaledVector(A,O),w.end.copy(E.start).addScaledVector(A,O)),!0):!1}else return y.isDegenerateIntoPoint?v(x,y,w):m(y,x,w,S);else{if(x.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(x.a)<xb?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:y.isDegenerateIntoSegment?v(y,x,w):g(y,x,w);if(y.isDegenerateIntoPoint)return g(x,y,w);if(y.isDegenerateIntoSegment)return m(x,y,w,S)}}return function(y,w=null,S=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(o.copy(y),o.update(),y=o);const E=M(this,y,w,S);if(E!==void 0)return E;const b=this.plane,A=y.plane;let _=A.distanceToPoint(this.a),I=A.distanceToPoint(this.b),D=A.distanceToPoint(this.c);ir(_)&&(_=0),ir(I)&&(I=0),ir(D)&&(D=0);const O=_*I,L=_*D;if(O>0&&L>0)return!1;let P=b.distanceToPoint(y.a),k=b.distanceToPoint(y.b),H=b.distanceToPoint(y.c);ir(P)&&(P=0),ir(k)&&(k=0),ir(H)&&(H=0);const W=P*k,Q=P*H;if(W>0&&Q>0)return!1;n.copy(b.normal),s.copy(A.normal);const q=n.cross(s);let nt=0,at=Math.abs(q.x);const Bt=Math.abs(q.y);Bt>at&&(at=Bt,nt=1),Math.abs(q.z)>at&&(nt=2);const Pt=iL[nt],Z=this.a[Pt],ct=this.b[Pt],ot=this.c[Pt],V=y.a[Pt],Nt=y.b[Pt],Xt=y.c[Pt];if(p(this,Z,ct,ot,O,L,_,I,D,h,a))return d(this,y,w,S);if(p(y,V,Nt,Xt,W,Q,P,k,H,u,c))return d(this,y,w,S);if(h.y<h.x){const Lt=h.y;h.y=h.x,h.x=Lt,l.copy(a.start),a.start.copy(a.end),a.end.copy(l)}if(u.y<u.x){const Lt=u.y;u.y=u.x,u.x=Lt,l.copy(c.start),c.start.copy(c.end),c.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(c.start):w.start.copy(a.start),u.y<h.y?w.end.copy(c.end):w.end.copy(a.end)),!0)}})();Pr.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Pr.prototype.distanceToTriangle=(function(){const o=new R,t=new R,e=["a","b","c"],i=new ro,n=new ro;return function(r,a=null,c=null){const l=a||c?i:null;if(this.intersectsTriangle(r,l,!0))return(a||c)&&(a&&l.getCenter(a),c&&l.getCenter(c)),0;let h=1/0;for(let u=0;u<3;u++){let d;const f=e[u],p=r[f];this.closestPointToPoint(p,o),d=p.distanceToSquared(o),d<h&&(h=d,a&&a.copy(o),c&&c.copy(p));const m=this[f];r.closestPointToPoint(m,o),d=m.distanceToSquared(o),d<h&&(h=d,a&&a.copy(m),c&&c.copy(o))}for(let u=0;u<3;u++){const d=e[u],f=e[(u+1)%3];i.set(this[d],this[f]);for(let p=0;p<3;p++){const m=e[p],g=e[(p+1)%3];n.set(r[m],r[g]),fy(i,n,o,t);const v=o.distanceToSquared(t);v<h&&(h=v,a&&a.copy(o),c&&c.copy(t))}}return Math.sqrt(h)}})();class xs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new R,this.max=new R,this.matrix=new Wt,this.invMatrix=new Wt,this.points=new Array(8).fill().map(()=>new R),this.satAxes=new Array(3).fill().map(()=>new R),this.satBounds=new Array(3).fill().map(()=>new oo),this.alignedSatBounds=new Array(3).fill().map(()=>new oo),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}xs.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const d=1*l|2*h|4*u,f=n[d];f.x=l?i.x:e.x,f.y=h?i.y:e.y,f.z=u?i.z:e.z,f.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,a=n[0];for(let l=0;l<3;l++){const h=r[l],u=s[l],d=1<<l,f=n[d];h.subVectors(a,f),u.setFromPoints(h,n)}const c=this.alignedSatBounds;c[0].setFromPointsField(n,"x"),c[1].setFromPointsField(n,"y"),c[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();xs.prototype.intersectsBox=(function(){const o=new oo;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(o.min=i.x,o.max=n.x,a[0].isSeparated(o)||(o.min=i.y,o.max=n.y,a[1].isSeparated(o))||(o.min=i.z,o.max=n.z,a[2].isSeparated(o)))return!1;for(let c=0;c<3;c++){const l=r[c],h=s[c];if(o.setFromBox(l,e),h.isSeparated(o))return!1}return!0}})();xs.prototype.intersectsTriangle=(function(){const o=new Pr,t=new Array(3),e=new oo,i=new oo,n=new R;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(o.copy(r),o.update(),r=o);const a=this.satBounds,c=this.satAxes;t[0]=r.a,t[1]=r.b,t[2]=r.c;for(let d=0;d<3;d++){const f=a[d],p=c[d];if(e.setFromPoints(p,t),f.isSeparated(e))return!1}const l=r.satBounds,h=r.satAxes,u=this.points;for(let d=0;d<3;d++){const f=l[d],p=h[d];if(e.setFromPoints(p,u),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=c[d];for(let p=0;p<4;p++){const m=h[p];if(n.crossVectors(f,m),e.setFromPoints(n,t),i.setFromPoints(n,u),e.isSeparated(i))return!1}}return!0}})();xs.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();xs.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();xs.prototype.distanceToBox=(function(){const o=["x","y","z"],t=new Array(12).fill().map(()=>new ro),e=new Array(12).fill().map(()=>new ro),i=new R,n=new R;return function(r,a=0,c=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(c||l)&&(r.getCenter(n),this.closestPointToPoint(n,i),r.closestPointToPoint(i,n),c&&c.copy(i),l&&l.copy(n)),0;const h=a*a,u=r.min,d=r.max,f=this.points;let p=1/0;for(let g=0;g<8;g++){const v=f[g];n.copy(v).clamp(u,d);const M=v.distanceToSquared(n);if(M<p&&(p=M,c&&c.copy(v),l&&l.copy(n),M<h))return Math.sqrt(M)}let m=0;for(let g=0;g<3;g++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){const x=(g+1)%3,y=(g+2)%3,w=v<<x|M<<y,S=1<<g|v<<x|M<<y,E=f[w],b=f[S];t[m].set(E,b);const _=o[g],I=o[x],D=o[y],O=e[m],L=O.start,P=O.end;L[_]=u[_],L[I]=v?u[I]:d[I],L[D]=M?u[D]:d[I],P[_]=d[_],P[I]=v?u[I]:d[I],P[D]=M?u[D]:d[I],m++}for(let g=0;g<=1;g++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){n.x=g?d.x:u.x,n.y=v?d.y:u.y,n.z=M?d.z:u.z,this.closestPointToPoint(n,i);const x=n.distanceToSquared(i);if(x<p&&(p=x,c&&c.copy(i),l&&l.copy(n),x<h))return Math.sqrt(x)}for(let g=0;g<12;g++){const v=t[g];for(let M=0;M<12;M++){const x=e[M];fy(v,x,i,n);const y=i.distanceToSquared(n);if(y<p&&(p=y,c&&c.copy(i),l&&l.copy(n),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class nL extends uy{constructor(){super(()=>new Pr)}}const hr=new nL,Tu=new R,Kg=new R;function sL(o,t,e={},i=0,n=1/0){const s=i*i,r=n*n;let a=1/0,c=null;if(o.shapecast({boundsTraverseOrder:h=>(Tu.copy(t).clamp(h.min,h.max),Tu.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<a&&d<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Tu);const d=t.distanceToSquared(Tu);return d<a&&(Kg.copy(Tu),a=d,c=u),d<s}}),a===1/0)return null;const l=Math.sqrt(a);return e.point?e.point.copy(Kg):e.point=Kg.clone(),e.distance=l,e.faceIndex=c,e}const a0=parseInt(tf)>=169,rL=parseInt(tf)<=161,gc=new R,vc=new R,Mc=new R,o0=new tt,c0=new tt,l0=new tt,wb=new R,bb=new R,Sb=new R,Ru=new R;function aL(o,t,e,i,n,s,r,a){let c;if(s===Oi?c=o.intersectTriangle(i,e,t,!0,n):c=o.intersectTriangle(t,e,i,s!==bn,n),c===null)return null;const l=o.origin.distanceTo(n);return l<r||l>a?null:{distance:l,point:n.clone()}}function Eb(o,t,e,i,n,s,r,a,c,l,h){gc.fromBufferAttribute(t,s),vc.fromBufferAttribute(t,r),Mc.fromBufferAttribute(t,a);const u=aL(o,gc,vc,Mc,Ru,c,l,h);if(u){if(i){o0.fromBufferAttribute(i,s),c0.fromBufferAttribute(i,r),l0.fromBufferAttribute(i,a),u.uv=new tt;const f=Ln.getInterpolation(Ru,gc,vc,Mc,o0,c0,l0,u.uv);a0||(u.uv=f)}if(n){o0.fromBufferAttribute(n,s),c0.fromBufferAttribute(n,r),l0.fromBufferAttribute(n,a),u.uv1=new tt;const f=Ln.getInterpolation(Ru,gc,vc,Mc,o0,c0,l0,u.uv1);a0||(u.uv1=f),rL&&(u.uv2=u.uv1)}if(e){wb.fromBufferAttribute(e,s),bb.fromBufferAttribute(e,r),Sb.fromBufferAttribute(e,a),u.normal=new R;const f=Ln.getInterpolation(Ru,gc,vc,Mc,wb,bb,Sb,u.normal);u.normal.dot(o.direction)>0&&u.normal.multiplyScalar(-1),a0||(u.normal=f)}const d={a:s,b:r,c:a,normal:new R,materialIndex:0};if(Ln.getNormal(gc,vc,Mc,d.normal),u.face=d,u.faceIndex=s,a0){const f=new R;Ln.getBarycoord(Ru,gc,vc,Mc,f),u.barycoord=f}}return u}function Ab(o){return o&&o.isMaterial?o.side:o}function vm(o,t,e,i,n,s,r){const a=i*3;let c=a+0,l=a+1,h=a+2;const{index:u,groups:d}=o;o.index&&(c=u.getX(c),l=u.getX(l),h=u.getX(h));const{position:f,normal:p,uv:m,uv1:g}=o.attributes;if(Array.isArray(t)){const v=i*3;for(let M=0,x=d.length;M<x;M++){const{start:y,count:w,materialIndex:S}=d[M];if(v>=y&&v<y+w){const E=Ab(t[S]),b=Eb(e,f,p,m,g,c,l,h,E,s,r);if(b)if(b.faceIndex=i,b.face.materialIndex=S,n)n.push(b);else return b}}}else{const v=Ab(t),M=Eb(e,f,p,m,g,c,l,h,v,s,r);if(M)if(M.faceIndex=i,M.face.materialIndex=0,n)n.push(M);else return M}return null}function pn(o,t,e,i){const n=o.a,s=o.b,r=o.c;let a=t,c=t+1,l=t+2;e&&(a=e.getX(a),c=e.getX(c),l=e.getX(l)),n.x=i.getX(a),n.y=i.getY(a),n.z=i.getZ(a),s.x=i.getX(c),s.y=i.getY(c),s.z=i.getZ(c),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l)}function oL(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++)vm(c,t,e,h,s,r,a)}function cL(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=vm(a,t,e,u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function lL(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=h,pn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function hL(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(sn(m,a)){const g=Un(d,r),v=ss(m,a);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=3*g,A=3*(g+v);b<A;b++){let _=i[b];const I=n.getX(_),D=n.getY(_),O=n.getZ(_);I<M&&(M=I),I>w&&(w=I),D<x&&(x=D),D>S&&(S=D),O<y&&(y=O),O>E&&(E=O)}return c[d+0]!==M||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==S||c[d+5]!==E?(c[d+0]=M,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=S,c[d+5]=E,!0):!1}else{const g=En(d),v=An(d,r);let M=p,x=!1,y=!1;if(t){if(!M){const _=g/Sn+f/ns,I=v/Sn+f/ns;x=t.has(_),y=t.has(I),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(g,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],L=c[I+3],P=c[D],k=c[D+3];c[d+_]=O<P?O:P,c[d+_+3]=L>k?L:k}return A}}}function rc(o,t,e,i,n){let s,r,a,c,l,h;const u=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,p=e.origin.x,m=e.origin.y,g=e.origin.z;let v=t[o],M=t[o+3],x=t[o+1],y=t[o+3+1],w=t[o+2],S=t[o+3+2];return u>=0?(s=(v-p)*u,r=(M-p)*u):(s=(M-p)*u,r=(v-p)*u),d>=0?(a=(x-m)*d,c=(y-m)*d):(a=(y-m)*d,c=(x-m)*d),s>c||a>r||((a>s||isNaN(s))&&(s=a),(c<r||isNaN(r))&&(r=c),f>=0?(l=(w-g)*f,h=(S-g)*f):(l=(S-g)*f,h=(w-g)*f),s>h||l>r)?!1:((l>s||s!==s)&&(s=l),(h<r||r!==r)&&(r=h),s<=n&&r>=i)}function uL(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++){let d=l?l[h]:h;vm(c,t,e,d,s,r,a)}}function dL(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=vm(a,t,e,c?c[u]:u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function fL(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=e.resolveTriangleIndex(h),pn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function pL(o,t,e,i,n,s,r){Ni.setBuffer(o._roots[t]),rM(0,o,e,i,n,s,r),Ni.clearBuffer()}function rM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Ni,h=o*2;if(sn(h,c)){const d=Un(o,l),f=ss(h,c);oL(t,e,i,d,f,n,s,r)}else{const d=En(o);rc(d,a,i,s,r)&&rM(d,t,e,i,n,s,r);const f=An(o,l);rc(f,a,i,s,r)&&rM(f,t,e,i,n,s,r)}}const mL=["x","y","z"];function gL(o,t,e,i,n,s){Ni.setBuffer(o._roots[t]);const r=aM(0,o,e,i,n,s);return Ni.clearBuffer(),r}function aM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Ni;let l=o*2;if(sn(l,a)){const u=Un(o,c),d=ss(l,a);return cL(t,e,i,u,d,n,s)}else{const u=hy(o,c),d=mL[u],p=i.direction[d]>=0;let m,g;p?(m=En(o),g=An(o,c)):(m=An(o,c),g=En(o));const M=rc(m,r,i,n,s)?aM(m,t,e,i,n,s):null;if(M){const w=M.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return M}const y=rc(g,r,i,n,s)?aM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const h0=new Ke,Bl=new Pr,Hl=new Pr,Iu=new Wt,_b=new xs,u0=new xs;function vL(o,t,e,i){Ni.setBuffer(o._roots[t]);const n=oM(0,o,e,i);return Ni.clearBuffer(),n}function oM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Ni;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),_b.set(e.boundingBox.min,e.boundingBox.max,i),n=_b),sn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Un(o,a),g=ss(c,r);if(Iu.copy(i).invert(),e.boundsTree)return Yi(o,s,u0),u0.matrix.copy(Iu),u0.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>u0.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=m*3,y=(g+m)*3;x<y;x+=3)if(pn(Hl,x,u,d),Hl.needsUpdate=!0,M.intersectsTriangle(Hl))return!0;return!1}});{const v=gm(e);for(let M=m*3,x=(g+m)*3;M<x;M+=3){pn(Bl,M,u,d),Bl.a.applyMatrix4(Iu),Bl.b.applyMatrix4(Iu),Bl.c.applyMatrix4(Iu),Bl.needsUpdate=!0;for(let y=0,w=v*3;y<w;y+=3)if(pn(Hl,y,f,p),Hl.needsUpdate=!0,Bl.intersectsTriangle(Hl))return!0}}}else{const h=En(o),u=An(o,a);return Yi(h,s,h0),!!(n.intersectsBox(h0)&&oM(h,t,e,i,n)||(Yi(u,s,h0),n.intersectsBox(h0)&&oM(u,t,e,i,n)))}}const d0=new Wt,qg=new xs,Du=new xs,ML=new R,yL=new R,xL=new R,wL=new R;function bL(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),qg.set(t.boundingBox.min,t.boundingBox.max,e),qg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=hr.getPrimitive(),f=hr.getPrimitive();let p=ML,m=yL,g=null,v=null;n&&(g=xL,v=wL);let M=1/0,x=null,y=null;return d0.copy(e).invert(),Du.matrix.copy(d0),o.shapecast({boundsTraverseOrder:w=>qg.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<r?(S&&(Du.min.copy(w.min),Du.max.copy(w.max),Du.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:b=>Du.distanceToBox(b),intersectsBounds:(b,A,_)=>_<M&&_<r,intersectsRange:(b,A)=>{for(let _=b,I=b+A;_<I;_++){pn(f,3*_,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let D=w,O=w+S;D<O;D++){pn(d,3*D,l,c),d.needsUpdate=!0;const L=d.distanceToTriangle(f,p,g);if(L<M&&(m.copy(p),v&&v.copy(g),M=L,x=D,y=_),L<s)return!0}}}});{const E=gm(t);for(let b=0,A=E;b<A;b++){pn(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+S;_<I;_++){pn(d,3*_,l,c),d.needsUpdate=!0;const D=d.distanceToTriangle(f,p,g);if(D<M&&(m.copy(p),v&&v.copy(g),M=D,x=_,y=b),D<s)return!0}}}}}),hr.releasePrimitive(d),hr.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=x,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(d0),m.applyMatrix4(d0),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function SL(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(sn(m,a)){const g=Un(d,r),v=ss(m,a);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=g,A=g+v;b<A;b++){const _=3*o.resolveTriangleIndex(b);for(let I=0;I<3;I++){let D=_+I;D=i?i[D]:D;const O=n.getX(D),L=n.getY(D),P=n.getZ(D);O<M&&(M=O),O>w&&(w=O),L<x&&(x=L),L>S&&(S=L),P<y&&(y=P),P>E&&(E=P)}}return c[d+0]!==M||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==S||c[d+5]!==E?(c[d+0]=M,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=S,c[d+5]=E,!0):!1}else{const g=En(d),v=An(d,r);let M=p,x=!1,y=!1;if(t){if(!M){const _=g/Sn+f/ns,I=v/Sn+f/ns;x=t.has(_),y=t.has(I),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(g,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],L=c[I+3],P=c[D],k=c[D+3];c[d+_]=O<P?O:P,c[d+_+3]=L>k?L:k}return A}}}function EL(o,t,e,i,n,s,r){Ni.setBuffer(o._roots[t]),cM(0,o,e,i,n,s,r),Ni.clearBuffer()}function cM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Ni,h=o*2;if(sn(h,c)){const d=Un(o,l),f=ss(h,c);uL(t,e,i,d,f,n,s,r)}else{const d=En(o);rc(d,a,i,s,r)&&cM(d,t,e,i,n,s,r);const f=An(o,l);rc(f,a,i,s,r)&&cM(f,t,e,i,n,s,r)}}const AL=["x","y","z"];function _L(o,t,e,i,n,s){Ni.setBuffer(o._roots[t]);const r=lM(0,o,e,i,n,s);return Ni.clearBuffer(),r}function lM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Ni;let l=o*2;if(sn(l,a)){const u=Un(o,c),d=ss(l,a);return dL(t,e,i,u,d,n,s)}else{const u=hy(o,c),d=AL[u],p=i.direction[d]>=0;let m,g;p?(m=En(o),g=An(o,c)):(m=An(o,c),g=En(o));const M=rc(m,r,i,n,s)?lM(m,t,e,i,n,s):null;if(M){const w=M.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return M}const y=rc(g,r,i,n,s)?lM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const f0=new Ke,Gl=new Pr,Vl=new Pr,Cu=new Wt,Tb=new xs,p0=new xs;function TL(o,t,e,i){Ni.setBuffer(o._roots[t]);const n=hM(0,o,e,i);return Ni.clearBuffer(),n}function hM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Ni;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),Tb.set(e.boundingBox.min,e.boundingBox.max,i),n=Tb),sn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Un(o,a),g=ss(c,r);if(Cu.copy(i).invert(),e.boundsTree)return Yi(o,s,p0),p0.matrix.copy(Cu),p0.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>p0.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=m,y=g+m;x<y;x++)if(pn(Vl,3*t.resolveTriangleIndex(x),u,d),Vl.needsUpdate=!0,M.intersectsTriangle(Vl))return!0;return!1}});{const v=gm(e);for(let M=m,x=g+m;M<x;M++){const y=t.resolveTriangleIndex(M);pn(Gl,3*y,u,d),Gl.a.applyMatrix4(Cu),Gl.b.applyMatrix4(Cu),Gl.c.applyMatrix4(Cu),Gl.needsUpdate=!0;for(let w=0,S=v*3;w<S;w+=3)if(pn(Vl,w,f,p),Vl.needsUpdate=!0,Gl.intersectsTriangle(Vl))return!0}}}else{const h=En(o),u=An(o,a);return Yi(h,s,f0),!!(n.intersectsBox(f0)&&hM(h,t,e,i,n)||(Yi(u,s,f0),n.intersectsBox(f0)&&hM(u,t,e,i,n)))}}const m0=new Wt,Zg=new xs,Ou=new xs,RL=new R,IL=new R,DL=new R,CL=new R;function OL(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),Zg.set(t.boundingBox.min,t.boundingBox.max,e),Zg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=hr.getPrimitive(),f=hr.getPrimitive();let p=RL,m=IL,g=null,v=null;n&&(g=DL,v=CL);let M=1/0,x=null,y=null;return m0.copy(e).invert(),Ou.matrix.copy(m0),o.shapecast({boundsTraverseOrder:w=>Zg.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<r?(S&&(Ou.min.copy(w.min),Ou.max.copy(w.max),Ou.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:b=>Ou.distanceToBox(b),intersectsBounds:(b,A,_)=>_<M&&_<r,intersectsRange:(b,A)=>{for(let _=b,I=b+A;_<I;_++){const D=E.resolveTriangleIndex(_);pn(f,3*D,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let O=w,L=w+S;O<L;O++){const P=o.resolveTriangleIndex(O);pn(d,3*P,l,c),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,g);if(k<M&&(m.copy(p),v&&v.copy(g),M=k,x=O,y=_),k<s)return!0}}}})}else{const E=gm(t);for(let b=0,A=E;b<A;b++){pn(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+S;_<I;_++){const D=o.resolveTriangleIndex(_);pn(d,3*D,l,c),d.needsUpdate=!0;const O=d.distanceToTriangle(f,p,g);if(O<M&&(m.copy(p),v&&v.copy(g),M=O,x=_,y=b),O<s)return!0}}}}}),hr.releasePrimitive(d),hr.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=x,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(m0),m.applyMatrix4(m0),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function Rb(o,t,e){return o===null?null:(o.point.applyMatrix4(t.matrixWorld),o.distance=o.point.distanceTo(e.ray.origin),o.object=t,o)}const g0=new xs,v0=new sl,Ib=new R,Db=new Wt,Cb=new R,Jg=["getX","getY","getZ"];class zp extends Q8{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=n.map(c=>c.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=s?s.slice():null):(a.roots=n,a.index=r?r.array:null,a.indirectBuffer=s),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(s));const a=new zp(e,{...i,[ly]:!0});if(a._roots=s,a._indirectBuffer=r||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new ve(t.index,1,!1);e.setIndex(h)}else l.array!==n&&(l.array.set(n),l.needsUpdate=!0)}return a;function c(l){for(let h=0;h<l.length;h++){const u=l[h],d=new Uint32Array(u),f=new Uint16Array(u);for(let p=0,m=u.byteLength/ns;p<m;p++){const g=Sn*p,v=2*g;sn(v,f)||(d[g+6]=d[g+6]/Sn-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,l=(s?s[t]:t)*3;let h=l+0,u=l+1,d=l+2;a&&(h=a[h],u=a[u],d=a[d]);for(let f=0;f<3;f++){const p=r[Jg[f]](h),m=r[Jg[f]](u),g=r[Jg[f]](d);let v=p;m<v&&(v=m),g<v&&(v=g);let M=p;m>M&&(M=m),g>M&&(M=g),e[i+f]=v,e[i+f+3]=M}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,c=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,h=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const d=["getX","getY","getZ"],f=i.offset;for(let p=t,m=t+e;p<m;p++){const v=(s?s[p]:p)*3,M=(p-f)*6;let x=v+0,y=v+1,w=v+2;a&&(x=a[x],y=a[y],w=a[w]),c||(x=x*u+h,y=y*u+h,w=w*u+h);for(let S=0;S<3;S++){let E,b,A;c?(E=r[d[S]](x),b=r[d[S]](y),A=r[d[S]](w)):(E=l[x+S],b=l[y+S],A=l[w+S]);let _=E;b<_&&(_=b),A<_&&(_=A);let I=E;b>I&&(I=b),A>I&&(I=A);const D=(I-_)/2,O=S*2;i[M+O+0]=_+D,i[M+O+1]=D+(Math.abs(_)+D)*K0}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(n===void 0)return;Db.copy(t.matrixWorld).invert(),v0.copy(e.ray).applyMatrix4(Db),Cb.setFromMatrixScale(t.matrixWorld),Ib.copy(v0.direction).multiply(Cb);const s=Ib.length(),r=e.near/s,a=e.far/s;if(e.firstHitOnly===!0){let c=this.raycastFirst(v0,n,r,a);c=Rb(c,t,e),c&&i.push(c)}else{const c=this.raycast(v0,n,r,a);for(let l=0,h=c.length;l<h;l++){const u=Rb(c[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?SL:hL)(this,t)}raycast(t,e=Sa,i=0,n=1/0){const s=this._roots,r=[],a=this.indirect?EL:pL;for(let c=0,l=s.length;c<l;c++)a(this,c,e,t,r,i,n);return r}raycastFirst(t,e=Sa,i=0,n=1/0){const s=this._roots;let r=null;const a=this.indirect?_L:gL;for(let c=0,l=s.length;c<l;c++){const h=a(this,c,e,t,i,n);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?TL:vL;for(let r=0,a=n.length;r<a&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=hr.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?fL:lL});return hr.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=hr.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,l=this.indirect?p=>{const m=this.resolveTriangleIndex(p);pn(r,m*3,a,c)}:p=>{pn(r,p*3,a,c)},h=hr.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const m=t.resolveTriangleIndex(p);pn(h,m*3,u,d)}:p=>{pn(h,p*3,u,d)};if(s){if(!(t instanceof zp))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(m,g,v,M,x,y,w,S)=>{for(let E=v,b=v+M;E<b;E++){f(E),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let A=m,_=m+g;A<_;A++)if(l(A),r.needsUpdate=!0,s(r,h,A,E,x,y,w,S))return!0}return!1};if(n){const m=n;n=function(g,v,M,x,y,w,S,E){return m(g,v,M,x,y,w,S,E)?!0:p(g,v,M,x,y,w,S,E)}}else n=p}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return g0.set(t.min,t.max,e),g0.needsUpdate=!0,this.shapecast({intersectsBounds:i=>g0.intersectsBox(i),intersectsTriangle:i=>g0.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?OL:bL)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return sL(this,t,e,i,n)}}class Xr{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new fr;static install(){if(Xr.installed)return;Xr.installed=!0;const t=Mt.prototype.raycast;Mt.prototype.raycast=function(e,i){const n=Xr.treeOf(this,e);n!==null&&(n?n.raycastObject3D(this,e,i):t.call(this,e,i))}}static treeOf(t,e){const i=t.geometry,n=i?.attributes.position;if(!(n instanceof ve)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||i.morphAttributes.position)return;const s=i.index;if((s?s.count:n.count)/3<Xr.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=Xr.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(r))return null;const a=Xr.trees.get(i);if(a){if(!a.bvh)return;if(a.position===n&&a.positionVersion===n.version&&a.index===s&&a.indexVersion===(s?.version??0))return a.bvh;Xr.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const c=new zp(i,{indirect:!0});return Xr.trees.set(i,{bvh:c,position:n,positionVersion:n.version,index:s,indexVersion:s?.version??0}),c}}function PL(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 M0=900,jg=1,Ob=4,Qg=5,y0=.5,x0=Be.GROUND_RADIUS_M;function Pb(o){return Be.groundRadiusFor(o)}const t1=.5,e1=850,w0=.03,NL=.015,ls=850,Wl=300,La=120,LL=700,i1=.03,kL=3.5,b0=20,n1=.04,UL=.26,Nb=4,s1=1.5,Lb=-1,FL=.01,Z0=-4,zL=2,BL=20,S0=2600,HL=.97,GL=.38,Pu=Z0,VL=8,WL=2,kb=1500,XL=.7,$L=.3,YL=.32,KL=.65,Ub=2.4,qL=.9,ZL=400,JL=[0,45,90,135,180,225,270,315],jL=2,QL=16,Fb=4e3,zb=880,E0=40,Bb=60,t9=10,Hb=1,e9=Be.REBUILD_DISTANCE_M,Gb=.265,Vb=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*Gb,Math.sin(e)*Gb]})],r1=700,a1=250/dM,i9=12,Wb=5,o1=6,yc=[.92,.92,.95],c1=[.15,.15,.19],l1={snow:{fallSpeedMPerS:2,size:.3,color:new rt(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new rt(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Zl=0,h1=0,n9=150,u1=3e3,Nu=20,s9=15,Xb=Zl,r9=40,$b=1,a9=9;function d1(o){return $b+(a9-$b)*o}const Yb=new rt(.75,.82,.92),o9=10,c9=.5;function Kb(o){return $r(o/o9,c9,1)}const xc=200,qb=.18,Zb=.32,l9=.35,Jb=new rt(.85,.9,.98),jb=5,Qb=.85,tS=.01;function h9(o,t,e=1){return Math.round(o*(tS+(1-tS)*t)*e)}function u9(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 eS=230,iS=.7,nS=.05,d9=.6,f9=.7,p9=.15,sS=.35,m9=3,g9=1/12,v9=.5,Hr=new rt(.82,.86,1),M9=2500,y9=1.6,f1=15,x9={Venus:new rt(1,.96,.85),Mars:new rt(1,.55,.4),Jupiter:new rt(.95,.87,.72),Saturn:new rt(.92,.86,.68)};class lt{renderer;scene=new Zs;phenomena=new Er(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Xe;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()+Fb,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Fb+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new tt;decorModelProvider=new GA;decorModelToken=0;decorModelCredits=new Map;emitterLights=new us(this.scene,()=>this.relativeScale,{halfExtentM:La,depthHalfRangeM:Wl,biasM:i1,normalBiasM:n1,mapSize:1024});bodySystem=new re(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??lt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*lt.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Ep(16777215,0);celestialLightTarget=new Pi;skyLight=new b4(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 V0;weather=Yp;observerElevationM=0;siteElevationM=0;air=new or;groundRadius=x0;terrainRadius=x0;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 tt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Ep(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new V0;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new V0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=pi.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Kd;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=QS()){Qu.install(),Xr.install(),this.renderer=new UO({canvas:t,antialias:!0}),this.resolution=new Qe(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Xu,this.camera=new Wn(60,t.width/Math.max(t.height,1),.1,M0*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=-La,this.celestialLight.shadow.camera.right=La,this.celestialLight.shadow.camera.top=La,this.celestialLight.shadow.camera.bottom=-La,this.celestialLight.shadow.camera.near=ls-Wl,this.celestialLight.shadow.camera.far=ls+Wl,this.celestialLight.shadow.bias=-i1/(2*Wl),this.celestialLight.shadow.normalBias=n1,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Hr),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 de(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*a1,0,t.z*a1);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){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Je,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Je;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Je,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(Pb(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/x0),this.camera.far=Math.max(M0*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.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=lt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Be.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ae(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}this.lookPatch&&s(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=Hb+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=Be.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(t.headingDeg??0)*Math.PI/180,n=t.lat+e.distanceM*Math.cos(i)/111320,s=t.lng+e.distanceM*Math.sin(i)/(111320*Math.cos(t.lat*Math.PI/180)),r=this.lookPatchAsked;if(r){const l=ae(n,s,r.lat,r.lng);if(Math.hypot(l.x,l.z)<r.radiusM*lt.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:n,lng:s,radiusM:e.radiusM};const a=++this.lookPatchToken,c=this.terrainProviders;Og(n,s,{elevation:c.elevation,imagery:c.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:l})=>{if(a!==this.lookPatchToken||this.terrainProviders!==c||!this.terrainMesh){this.disposeMesh(l);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),l.renderOrder=lt.LOOK_PATCH_RENDER_ORDER,l.position.y=this.terrainMesh.position.y;const h=l.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:l,origin:{lat:n,lng:s},radiusM:e.radiusM};const u=ae(n,s,t.lat,t.lng);l.position.x=u.x,l.position.z=u.z,this.scene.add(l),this.compileNextFrameOffThread(),this.render()},l=>console.warn("No sharp ground under what is looked at:",l))}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),lt.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(Be.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=ae(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<e9*(r/x0))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ae(t,e,c.lat,c.lng).x,ae(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 h=++this.terrainBuildToken;this.awaitArrival(Og(t,e,this.terrainProviders,r,{route:this.observerRoute}),lt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const g=this.terrainMesh,v=this.terrainMeshOrigin,M=v?ae(t,e,v.lat,v.lng):void 0;g&&M&&Math.hypot(M.x,M.z)<=a&&(u.position.y=g.position.y+this.groundYOfPatch(g,M.x,M.z)),g&&v&&M&&Math.hypot(M.x,M.z)<=a?this.crossfadeTerrain(u,g,v):this.disposeMesh(this.terrainMesh),u.renderOrder=Hb,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,m),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=this.skyEventReachM({lat:t,lng:e});if(!Be.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=ae(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*lt.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(t,e);if(l&&!h){this.dropFarRing();return}const u=h?.radiusM??Be.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(Og(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*lt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),lt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=lt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-lt.FAR_RING_DROP_M;const m=p.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,i){if(this.grassReference){const r=ae(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=ae(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/lt.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Be.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(td(t,e,i)),lt.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>lt.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),lt.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(ae(t,e,a.lat,a.lng).x,ae(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(td(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),Qn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Et(async()=>{const{WaterSystem:t}=await import("./WaterSystem-D3andNtL.js");return{WaterSystem:t}},[],import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const n=this.terrainProviders.railways;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(td(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),Qn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Et(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-C920HhY6.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??=Et(async()=>{const{TraceSystem:t}=await import("./TraceSystem-BrpqiAAJ.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(Qg);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=ut.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ae(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 Si(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?xn.LENS_K:xn.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(PL(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!u9(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=or.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:Zo.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>=v9,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(lt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ut.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,VL);for(const i of t){const n=ut.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<WL,i.lamp),i.model&&i.id.startsWith(Di.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=lt.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=Et(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-Bgre4cLs.js");return{ContrailSystem:t}},__vite__mapDeps([14,15]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,n=lt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=gs.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Ue.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*l*c[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,i){if(this.skyEventsStart=i,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let n=!1;const s=new Set;for(const r of Kv){const a=to.of(r);s.add(a.key);const c=to.eventsOf(t,a);let l=this.skyEventLayers.get(a.key);if(l?.kind!==a&&l&&(this.disposeSkyEventLayer(a.key,l),l=void 0),!(!l&&c.length===0)){if(!l)l={kind:a,events:c},this.skyEventLayers.set(a.key,l);else if(l.events===c)continue;l.events=c,n||=a.reachM!==void 0,this.loadSkyEventSimulation(l)}}for(const[r,a]of this.skyEventLayers)s.has(r)||(this.disposeSkyEventLayer(r,a),n||=a.kind.reachM!==void 0);n&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const i=e();(i.inSky?this.celestialGroup:this.scene).add(i.object),t.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[])}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const i=`skyEvent:${t}:`,n=new Set;for(const s of e){const r=i+s.key,{x:a,y:c,z:l}=xi(s.position.altitudeDeg,s.position.azimuthDeg,ls),[h,u,d]=this.arrivingIlluminance(s.position,s.magnitude,this.cloudTransmission(s.position));this.setGlare(r,a,c,l,[h*s.fade,u*s.fade,d*s.fade],0,lt.POINT_VEIL_HOLD_DEG),n.add(r)}for(const s of[...this.glareSprites.keys()])s.startsWith(i)&&!n.has(s)&&this.disposeGlare(s)}skyEventReachM(t){let e=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(e=Math.max(e,i.kind.reachM(i.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,i={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},n=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,s=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$0(-90,this.instrumentMagnitudeGain);let r;for(const[a,c]of this.skyEventLayers)c.simulation&&(r??={observer:i,date:n,magnitudeLimit:s,cloudTransmission:l=>this.cloudTransmission(l),arrivingIlluminance:(l,h,u)=>this.arrivingIlluminance(l,h,u),transmittanceFromSpace:l=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,l.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(l,h,u)=>this.transmittanceTo(l,h,u),groundYAt:(l,h)=>this.groundYUnder(l,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Je)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Je)*this.weather.windSpeed}},c.simulation.update(c.events,this.decorTime,{...r,lightFrom:l=>this.skyEventLight(a,l),glareFrom:l=>this.skyEventGlare(a,l)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?xi(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}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*Je)/Math.cos(t.lat*Je)}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,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),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 h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,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,l)=>(a*e+(c+l)/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 Bg(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(np(t))||!ut.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=WA(i.scene);n.traverse(s=>{s instanceof Mt&&(s.userData.sharedModel=!0)}),ut.applyModelParameters(n,t.modelParameters,i.bindings),ut.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new Rs;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?LS[t.kind]:np(t);if(!(!n||!ut.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await Bg(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&(re.glaze(c),Qn.reflectOn(c));const h={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,h),this.applyLoadedDecorModel(t,l,h),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=Bg(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Qn.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?ae(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&Xh(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=Cr(s,i),m=ut.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*Je,v=m.x*Math.cos(g)+m.z*Math.sin(g),M=-m.x*Math.sin(g)+m.z*Math.cos(g),x=p.eastM+n.x,y=-p.northM+n.z;r.x=-(x+v),r.z=-(y+M),this.camera.position.y=this.groundYUnder(x,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Je,-(m.headingDeg+this.indoorLookYawDeg)*Je,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const l=this.findCabin(i,n,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const m=this.decorGroups.get(p.id);if(!m)continue;const g=Cr(p,i),v=this.lampNudges.get(p.id),M=g.eastM+(v?.eastM??0)+n.x+r.x,x=-(g.northM+(v?.northM??0))+n.z+r.z,y=this.terrainMesh,w=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(x-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(m.userData.footprintKey!==w){if(p.kind==="wire"){const O=ut.wireGround(p,M,x,g.headingDeg,(L,P)=>this.groundYUnder(L,P));m.userData.footprintGroundY=O.startY,ut.shearWire(m,ut.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(M,x),L=-(g.headingDeg??0)*Je,P=Math.cos(L),k=Math.sin(L);m.userData.footprintGroundY=O,Ee.drape(ut.bodyOf(m),(H,W)=>this.groundYUnder(M+H*P+W*k,x-H*k+W*P)-O)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,M,x,g.headingDeg,g.altitudeM);m.userData.footprintKey=w}const E=g.altitudeM>lt.AIRBORNE_M&&Math.hypot(M,x)<lt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,b=p.id.startsWith(Di.ID_PREFIX)?lt.trafficHeight(g.altitudeM,m.userData.footprintGroundY):E+g.altitudeM;if(m.position.set(M,b,x),p.kind==="crop"){const O=Math.hypot(M,x);m.visible=O<=n9}const A=this.decorPresence.get(p.id),_=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(m.visible=!_);const I=this.decorSunlight.get(p.id);I&&!_&&this.lightFromAbove(m,I),g.headingDeg!==void 0&&(m.rotation.y=-g.headingDeg*Je);const D=X_(p,i);if(D!==void 0&<.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const O=this.terrainMesh,L=[O?.geometry.uuid,M-(O?.position.x??0),x-(O?.position.z??0),m.position.y-(O?.position.y??0),g.headingDeg,g.altitudeM].map(P=>typeof P=="number"?P.toFixed(4):P).join(":");m.userData.cropGroundKey!==L&&(ut.fitCropToGround(m,(P,k)=>this.groundYUnder(P,k)+g.altitudeM),m.userData.cropGroundKey=L)}if(!_){const O=m.position.distanceTo(this.camera.position);a=Math.max(a,O),O<lt.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateSkyEvents();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(M0*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,l=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(l)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=h*h*(3-2*h);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=Cr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=-(a.headingDeg??0)*Je,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(l-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(c,0,l),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=ut.fitTerrace(r,s,(m,g)=>this.terrainYUnder(c+m*d+g*f,l-m*f+g*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.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):h1}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+lt.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=c;u=Math.max(u+l,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),m=u*u/(2*lt.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(p-m-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return h1;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=$r((e-r)/(a-r)*(s-1),0,s-1),u=$r((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return h1;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,m=u-f,g=(w,S)=>n.getY(w*s+S),v=g(f,d),M=g(f,d+1),x=g(f+1,d),y=g(f+1,d+1);return p+m<=1?v+(M-v)*p+(x-v)*m:y+(x-y)*(1-p)+(M-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return ut.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=Ls.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n,s){const r=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0&&n===void 0,maxIso:t.maxIso,metering:s??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}: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?Ls.NONE:this.perception??Ls.NONE;if(Ci.uColorVision.value.set(...i.colorMatrix),Ci.uContrast.value=i.contrastGain,!t){Ci.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";Ci.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:n?4:3;const s=t.autoExposure?this.frameLight:void 0,r=t.autoExposure||this.skyUnknown?s?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),c=r===void 0?void 0:r+a.mean,l=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let h=c!==void 0&&c>0?1/(e*c):void 0;h!==void 0&&t.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,lt.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),h!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(h=Math.min(h,lt.ZONE_KEPT_AT/(.18*e*s.brightest)));const u=h!==void 0?Math.min(h,t.maxIso!==void 0?l(t.maxIso):1/0):l(t.iso);Ci.uMediumExposure.value=u,Ci.uPhoneStrength.value=n&&c!==void 0&&c>0?br.strengthFor(br.MID_GREY*u*e*c):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new R;let r=0,a=0;for(const{position:c,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())s.copy(c).project(t),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=l*h,a=Math.max(a,l*Math.min(1,h/(lt.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new tt;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&ut.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?kS(n,t):void 0,c=a!==void 0?qc.lamps(a):tm(n,t,this.lastAstronomy?.sun.altitudeDeg);ut.setLit(r,n.kind,c,this.relativeScale,n.lamp);const l=this.streetlightLights.get(n.id);l&&(l.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??=Et(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-CmppP6Mm.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=ut.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-$L);r.y+=XL;const a=ut.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*YL,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?qc.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*Ub,this.camera.position.y-qL,n.z*Ub);this.headlightSystem.aim("observer",e,s,n,KL,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=ut.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=kb*ut.lampShare(n),c=new WE(16764006,a*this.relativeScale,ZL);n?.colorTemperatureK&&c.color.setRGB(...ut.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;ut.setLitWindowShare(t?zn.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=Cs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Ft.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=en.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,Nb,new rt(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<Z0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=Nb/ls*(180/Math.PI),n=i/e.sunRadiusDeg,s=xi(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=xi(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos($r(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?$r(e.separationDeg*n*Je/a,0,2):0,l=Math.sin(a),[h,u]=a>1e-9?[Math.sin((1-c)*a)/l,Math.sin(c*a)/l]:[1,0],d={x:s.x*h+r.x*u,y:s.y*h+r.y*u,z:s.z*h+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*Je,moonRadiusRad:f*Je};const p=.01,m=(M,x)=>xi(t.sun.altitudeDeg+M,t.sun.azimuthDeg+x,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},v={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new ph(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.updateSkyEvents());const e=this.scatteredSky?.ambient??lt.relativeSkyOf(Iv(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),Gt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??kb)*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?qt.DEFAULT_AEROSOL_OPTICAL_DEPTH:Zo.opticalDepth(i))*qt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ue.aureoleScale(n,Ue.airMass(t.altitudeDeg))*s,c=Ue.coronaScale(r),l=Ue.illuminanceOf(t.magnitude),h=[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(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new cy,this.celestialGroup.add(this.lunarDiffraction.object));const u=Ue.profile(Ue.HAZE_COARSE_MODE),d=Ue.profile(Ue.CLOUD_DROPLETS),f=aP(t.altitudeDeg),p=new Float32Array(Ue.STEPS*3);let m=0;for(let x=0;x<Ue.STEPS;x++){const y=x*3,w=[0,1,2].map(E=>l*f[E]*(a*u[y+E]+c*d[y+E])),S=Cs.shown(w,Cs.luminanceOf(w),(E,b)=>e.relativeOfLuminance(E,b));p.set(S,y),m=Math.max(m,Cs.response(S))}const{x:g,y:v,z:M}=xi(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:g,y:v,z:M}:void 0,p)}applyAir(){this.scene.fog instanceof $c||(this.scene.fog=new $c),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))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,lt.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:en.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?en.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:_t.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?QL:jL),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 QN(e1),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$0(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}flightScreenPoint(t){const e=`${Di.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(e))continue;const s=this.screenPointOf(new R().copy(n.position).sub(this.camera.position).normalize());if(s&&Math.abs(s.ndcX)<=1&&Math.abs(s.ndcY)<=1&&!this.groundHides(s.ndcX,s.ndcY))return s}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(w0*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(Di.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,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(w0*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>=Pu,s=!n&&t.moon.altitudeDeg>=Pu,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Je)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?fb.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=Pu&&(h=t.moon,u=fb.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Je)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),m=Math.max(0,1/(1+.1125*p)-f),g=[0,0,0];if(n||s){const S=Ue.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)g[I]=S*E[I]*m*c,this.cloudBeam[I]=S*E[I];const{x:b,y:A,z:_}=xi(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(b,A,_),u>0){const I=Ue.illuminanceOf(h.magnitude)*i,D=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),O=h===r?f:this.cloudTransmission(h);for(let L=0;L<3;L++)a[L]=I*D[L]*O*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,b=[0,1,2].map(_=>E[_]*S+g[_]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const A=ee.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(b[0]+a[0]*d),A*(b[1]+a[1]*d),A*(b[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:M,y:x,z:y}=xi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(M,x,y),this.celestialLight.shadow.normalBias=n1*$r(x/UL,.1,1),this.placeShadowFrustum();const w=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/w,a[1]/w,a[2]/w),this.celestialLight.intensity=w,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=gs.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Ue.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=lt.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)n[l]=Math.max(0,a*r[l]*s*c-this.sceneSunBeam[l])}}t.traverse(s=>{const r=s.material;if(!(r instanceof pr||r instanceof Fo)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=lt.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new 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=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*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=kL;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=b0+5,i.near=this.shadowLightDistanceM-b0,i.far=this.shadowLightDistanceM+b0,i.updateProjectionMatrix(),e.bias=-.004/(2*b0),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==lt.CABIN_SKY_SHARE&&(r.envMapIntensity=lt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(LL,Math.max(La,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(Wl,e*(Wl/La));this.shadowLightDistanceM=Math.max(ls,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-i1/(2*s);const r=e>2*La?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=La;shadowLightDistanceM=ls;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*Je,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/Ft.semiSaturation(Ft.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new Dn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const i=Math.max(this.relativeScale,1e-30),n=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:s,y:r,z:a}=xi(t.altitudeDeg,t.azimuthDeg,1);return{direction:new R(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=zi.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=_t.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:_t.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return $0(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.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+lt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"&&s.kind!=="vehicle"||s.observerSide!==void 0&&Xh(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Cr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(c,l)<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 Qn(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(c=>c.mesh)],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof Xs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object].filter(c=>c!==void 0),...[...this.skyEventLayers.values()].filter(c=>c.simulation?.hiddenFromEye).map(c=>c.simulation.object)],n=this.relativeScale,s=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,c=>this.measureSurroundings(c,n,s,r),t?0:Qn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,lt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new hh,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>xi(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,r,a=>{const c=p=>p.map(m=>m/e),l=this.surroundings,h={up:c(a.up),down:c(a.down)},u=(p,m)=>p.some((g,v)=>Math.abs(g-m[v])>.03*Math.max(Math.abs(g),Math.abs(m[v]),1e-12)),d=!l||u(l.up,h.up)||u(l.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(lt.adaptingLuminance(Math.exp(a.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Pu?t.sun:t.moon.altitudeDeg>=Pu?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new wr;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?xi(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??lt.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,s=>{const r={mean:s.mean/t.scale,brightest:s.brightest/t.scale},a=this.frameLight,c=t.atMs,l=a?c-a.atMs:1/0,h=l<0||l>lt.EXPOSURE_JUMP_MS,u=h||l===0&&a?.jumped?1:1-Math.exp(-l/n),d=(m,g)=>m>0&&g>0?m*(g/m)**u:g,f={mean:d(a?.mean??0,r.mean),brightest:d(a?.brightest??0,r.brightest),atMs:c,jumped:h||l===0&&(a?.jumped??!1)};this.frameLight=f;const p=(m,g)=>Math.abs(m-g)>.01*Math.max(m,g);(!a||p(a.mean,f.mean)||p(a.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Ci.uRetinaOn.value=0,this.medium)return;const t=[];for(const a of this.emitterLights.farEmitters){const c=this.screenPointOf(a.direction);!c||Math.abs(c.ndcX)>1.2||Math.abs(c.ndcY)>1.2||t.push({ndcX:c.ndcX,ndcY:c.ndcY,lux:Cs.luminanceOf(a.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.y,1),n={width:this.camera.fov*i,height:this.camera.fov},s=this.retina?.atMs;if((s===void 0||this.recordingTimeMs<s||this.recordingTimeMs-s>le.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new le,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),n,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new le,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(Ci.uRetina.value=this.retina.texture,Ci.uRetinaOn.value=1,Ci.uRetinaViewport.value.copy(e))}retinaSize=new tt;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const n=i.pose,s=this.historicQuaternion.setFromEuler(this.historicEuler.set((n?.pitchDeg??0)*Je,-(n?.headingDeg??0)*Je,(n?.rollDeg??0)*Je,"YXZ")).invert(),r=n?.fovDeg??this.camera.fov,a=[];for(const c of i.views){const l=this.farEmitterOf(c.head,c.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(s),r,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:Cs.luminanceOf(l.lux)})}return a}historicQuaternion=new rs;historicEuler=new Ea;historicDirection=new R;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<lt.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const i of t)i.traverse(n=>{n.userData.emissive===!0&&e.push(n)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,g9);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ut.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[Qv]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Rs.INTERVAL_MS)),Ci.uRodShare.value=this.scatteredSky?.rodShare??0,Ci.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Ci.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 Xs&&e.userData.pointSource||e instanceof Mt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Qg),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($A),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 Ms({blending:Zc,blendSrc:ua,blendDst:ua,blendSrcAlpha:ua,blendDstAlpha:ua,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??=Et(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-DVbt8GRf.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s,s.onFrame=()=>this.render(),this.referenceClock&&s.setTime(this.referenceClock);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})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new 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;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const s=e?this.narrowTo(t,e):t,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse)),a=this.phenomena.furthestM;let c=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=l.kind!=="crop"&&this.mayHide(h,t,r,a);lt.markDecorDepth(h,u),u&&c++}c>0&&(t.layers.set(jg),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(Qv),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new nm;phenomenaViewProjection=new Wt;occluderSphere=new fr;localBounds=new WeakMap;mayHide(t,e,i,n){let s=0;t.traverse(()=>s++);let r=this.localBounds.get(t);if(!r||r.objects!==s){t.updateMatrixWorld(!0);const c=new Ke().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new fr).applyMatrix4(new Wt().copy(t.matrixWorld).invert()),objects:s},this.localBounds.set(t,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(t.matrixWorld);return a.center.distanceTo(e.position)-a.radius>n?!1:i.intersectsSphere(a)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new tt),n=lt.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),s=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-n)),r=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-n)),a=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+n)),c=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+n)),l=this.narrowCamera.copy(t);return l.setViewOffset(i.x,i.y,s,i.y-c,Math.max(1,a-s),Math.max(1,c-r)),l.updateMatrixWorld(),l}narrowCamera=new Wn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new Ms({colorWrite:!1,side:bn});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(lt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*Je}static isSolidSurface(t){if(!(t instanceof Mt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==_n}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof Mt))return;e&<.isSolidSurface(i)?i.layers.enable(jg):i.layers.disable(jg)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new tt),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new YO(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+lt.EXPOSURE_BUDGET_MS,s=lt.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=a[l]})}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(){Ci.uRodShare.value=this.scatteredSky?.rodShare??0,Ci.uHasOverlay.value=1,Ci.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Zs,n=new Js(-1,1,1,-1,0,2),s=E0/(zb*Math.tan(Bb*Je/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new pu(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(s/this.camera.aspect,s,1),i.add(h)}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 Ke,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)<lt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const g=(m.ndcX+1)/2,v=(1-m.ndcY)/2;c=Math.min(c,g),l=Math.max(l,g),h=Math.min(h,v),u=Math.max(u,v)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&t.push({x:c,y:h,width:l-c,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new tt),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new id(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,Ci.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 tt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Qi(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new tt);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new oy(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new tt);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Ii(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,n=>{const s=lt.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!s||s.distance>=n-.001||this.mirrors.isMirror(s.object)})}aimStraightAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new tt(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);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ii.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*Je);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new R;screenPointQuaternion=new rs;screenPointSize=new tt;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(l=>Math.max(0,l-lt.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=t.uniforms.uLensPosition.value,r=t.uniforms.uTanHalfFov.value,a=this.camera.aspect,c=pi.offFrameShare(Math.atan(Math.hypot(s.x*a,s.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI);if(!(c<=0))return{x:s.x,y:s.y,radius:i,flux:[e[0]*n*c,e[1]*n*c,e[2]*n*c]}}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(Ob),this.camera.layers.set(Ob),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 Vb)this.isSunOccluded(e[0],e[1])||t++;return t/Vb.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const n=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&n.length===0)return!1;const s=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),r=s.length();if(s.normalize(),e!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(s.z,0,-s.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const u=this.sunOcclusionUpScratch.crossVectors(h,s).normalize();s.addScaledVector(h,e*l).addScaledVector(u,i*l).normalize()}if(this.groundBlocks(this.camera.position,s,r)||this.cabinMask.hides(s))return!0;const a=this.cabinMask.any?n.filter(l=>!this.cabinGroups.includes(l)):n;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,s);const c=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(l=>!(l.object.material instanceof no));return c!==void 0&&c.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const i=e.mesh.getWorldPosition(this.veilTargetScratch),n=e.mesh.material.uniforms.uSourceDeg.value,s=n>.05?lt.VEIL_SAMPLES:lt.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,c]of s)this.isOccludedToward(i,a*n,c*n)||r++;e.share=r/s.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new As;veilTargetScratch=new R;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const v=t.x+e.x*g-s.position.x,M=t.z+e.z*g-s.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[g,v,M]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(g<x||g>y)return!1;continue}const w=(x-g)/v,S=(y-g)/v;d=Math.max(d,Math.min(w,S)),f=Math.min(f,Math.max(w,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const v=d+(f-d)*g/m,M=t.x+e.x*v,x=t.y+e.y*v,y=t.z+e.z*v;if(x<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=y0;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(l=>lt.isSolidSurface(l.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=FL*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new R).sub(i);return{key:h,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}]:[],l=lt.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...c],s);if(l)return this.groundHides(t,e)?void 0:l}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 l=Math.acos($r(c.direction.dot(t),-1,1))-c.radiusRad;if(l>i)continue;const h=l<=0,u=s<=0,d=c.inFront===!0;(h!==u?h:h?d!==a?d:c.radiusRad<r:l<s)&&(n=c.key,s=l,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=NL*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?lt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new Ke,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,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const v=Math.acos(Math.min(1,m.normalize().dot(n))),M=Math.atan(p/g);if(M>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(v>r)continue;M<h&&(h=M,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(w0*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,y0)}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),l=this.screenPointOf(c.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),s=Math.max(s,l.ndcX),n=Math.min(n,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new Ke;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 l=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),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.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*Je/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 _r;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<lt.SEE_THROUGH_BELOW||s instanceof no))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=lt.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new sl().copy(n).applyMatrix4(new Wt().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,lt.RAILWAY_PICK_ABOVE_M))return;const c=lt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-lt.RAILWAY_GROUND_MARGIN_M,y0))return;const l=i.group.worldToLocal(c.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const u=i.contactHeightM(h);return{line:h,distanceM:c.distance,...u!==void 0?{contactM:u}:{}}}pickSkyEventAt(t,e,i=()=>!0){const n=[...this.skyEventLayers.values()].filter(l=>l.simulation?.pick&&l.simulation.drawnCount>0&&i(l.kind,l.simulation));if(n.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray,r={toleranceRad:lt.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(w0*this.camera.fov*Math.PI/180),skyLightTowards:l=>this.skyLightTowards(l)};let a;for(const l of n){const h=l.simulation.pick(s.origin,s.direction,r);h&&(!a||(h.distanceM??1/0)<(a.distanceM??1/0))&&(a={kind:l.kind.key,...h})}if(!a)return;if(a.distanceM===void 0)return this.groundHides(t,e)?void 0:a;if(this.terrainMesh&&this.groundBlocks(s.origin,s.direction,a.distanceM-1,y0))return;const c=lt.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(c&&c.distance<a.distanceM))return a}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const t of this.skyEventLayers.values())t.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())ut.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<lt.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new an(M0,32,16),i=e.attributes.position,n=e.getAttribute("color")??new fe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=hA(i.getX(r),i.getY(r),i.getZ(r)),l=nP(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new Ms({vertexColors:!0,side:Oi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Mt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=Pb(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new FM(this.groundRadius,48),i=new pr({color:new rt(t1,t1,t1),fog:!0});$c.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Mt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=xi(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-Ne.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*HL);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Ne.iceAlphaAt(i,S0,r,this.cloudFieldOffset)*GL),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<Z0){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}=xi(e.altitudeDeg,e.azimuthDeg,ls),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,s,l),u=lt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/ls)**2,p=[0,1,2].map(g=>u[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(lt.BRIGHTEST_RELATIVE,g));d instanceof Mt||(this.disposeMesh(d),d=new Mt(new an(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(m[0],m[1],m[2]),d.scale.setScalar(i)}else{if(!(d instanceof Xs)){this.disposeMesh(d);const m=new ye;m.setAttribute("position",new ve(new Float32Array(3),3)),m.setAttribute("color",new ve(new Float32Array(3),3)),d=new Xs(m,Gt.material(Ch[Ch.length-1].size,!1)),Gt.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]*h[0]*p,u[1]*h[1]*p,u[2]*h[2]*p),f.needsUpdate=!0}if(d.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,h,i/ls*(180/Math.PI),lt.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,c*f),this.lensFlare||(this.lensFlare=jN(),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<Z0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=xi(t.altitudeDeg,t.azimuthDeg,ls),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??ra.MEAN_RADIUS_DEG,h=ls*Math.tan(l*Je),u=Math.max($r(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/ls)**2,d=new rt(...c.map(m=>Math.min(lt.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round($r(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof pu?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=aS(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new pu(new G0({map:aS(t.phase),color:d,fog:!1,blending:_n,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(h*2,h*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,c,l)}bentLight(t,e,i=zL){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return lt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new rt;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Gt.CONE_SOLID_ANGLE/e)}pointScratch=new tt;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=Ue.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Cs.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 G0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new pu(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(xn.radiusDeg(xn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new xn(`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=oh(t.magnitude,e),s=Ig(n);this.cometKey=i,this.setBodyMesh(i,t.position,s1*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new Vs(ls),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Xi,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:S0},0);return}const s=this.lowerCloudCover(),r=we.deckLitUntilDeg(we.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?de.SUN_MAGNITUDE:e.magnitude),l=we.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=xi(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},a.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??S0},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??M3,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Uc,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?de.SUN_MAGNITUDE:e.magnitude,BL),c=Gs.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:l,y:h,z:u}=xi(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Oo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=Sr.galactic(i,n),r=lt.directionOf(s.centre),a=lt.directionOf(s.rotation),c=lt.directionOf(s.pole),l=new ue().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=lt.directionOf(Sr.eclipticPole(i,n)),u=lt.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:lt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:_t.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}=xi(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=oh(n.magnitude,e),a=Ig(r);this.setBodyMesh(s,n.position,s1*(.5+.5*r),new rt(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=oh(n.magnitude,e),r=Ig(s),a=x9[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),l=s1*(.5+.5*s);this.setBodyMesh(n.body,n.position,l,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 Tr(n,s),a=p1(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<Lb)continue;const{x:p,y:m,z:g}=xi(d,f,e1);c.push({x:p,y:m,z:g,brightness:oh(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Ue.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of RN){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<Lb)continue;const{x:f,y:p,z:m}=xi(u,d,e1);this.namedStars.push({star:h,direction:new R(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=Ch.map((h,u)=>{const d=c.filter(w=>qM(w.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),m=new Float32Array(d.length*3),g=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((w,S)=>{f[S*3]=w.x,f[S*3+1]=w.y,f[S*3+2]=w.z,p[S]=w.brightness,m.set(w.illuminance,S*3),g[S]=w.phase,v[S]=w.speedFactor});const M=new ye;M.setAttribute("position",new ve(f,3)),M.setAttribute("seed",new ve(g.map(w=>w/(2*Math.PI)),1));const x=new ve(new Float32Array(d.length*3),3);M.setAttribute("color",x);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new Xs(M,Gt.material(h.size)),Gt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:x,brightness:p,illuminance:m,phase:g,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Gt.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 Dh(this.celestialGroup,r1,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new rt(yc[0]+(c1[0]-yc[0])*e,yc[1]+(c1[1]-yc[1])*e,yc[2]+(c1[2]-yc[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}=Ev(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=Av(r1);this.cloudMesh=new Mt(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=Ev(new rt(...yc),t,S0,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Mt(Av(r1*1.04),e),this.cirrusMesh.renderOrder=Wb-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?Dh.deckOrder(!0,0,1):Wb}cloudLayerOffset(){const e=((this.weather.cloudBaseM??dM)-this.observerElevationM)*a1;return Math.sign(e||1)*Math.max(Math.abs(e),i9)}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*f1*this.relativeScale/Math.PI,l=new rt(e[0]+Hr.r*c,e[1]+Hr.g*c,e[2]+Hr.b*c);this.layeredClouds?.setLighting(n.clone(),new rt(s,r,a),l,l);const h=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*h,r*h,a*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return h9(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,u1],[this.rainSplashSystem?.points,xc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:l1[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=Kb(d1(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=l1[t],i=e.poolSize,n=p1(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),l=new Float32Array(i),h=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 y=n()*Math.PI*2,w=n()*e.radiusM;s[x*3]=Math.cos(y)*w,s[x*3+1]=Zl+n()*(e.topYM-Zl),s[x*3+2]=Math.sin(y)*w,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,l[x]=.4+n()*1.2}const m=new ye;m.setAttribute("position",new ve(s,3)),m.setDrawRange(0,this.precipitationCount(i));const g={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new rt(...this.baseFogColor)},uTexture:{value:w9(t)},uNearFocusDistance:{value:jb},uHazeDistance:{value:e.radiusM*Qb}},v=new Re({uniforms:g,vertexShader:T9,fragmentShader:R9,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const M=new Xs(m,v);M.renderOrder=o1,this.scene.add(M),this.precipitationPoints=M,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,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=l1[i];if(this.precipitationUniforms?.uColor.value.copy(lt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*Je,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,m=this.precipitationBounceDuration,g=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,M=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&m&&g&&v;for(let y=0,w=0;y<c.length;y+=3,w++){if(x&&f[w]>0){if(f[w]-=e,f[w]<=0){const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(b)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(b)*A,f[w]=0}else{const b=1-f[w]/m[w];c[y+1]=Zl+Math.sin(Math.PI*b)*p[w],c[y]=A0(c[y]+(r+g[w])*e,n.radiusM),c[y+2]=A0(c[y+2]+(a+v[w])*e,n.radiusM)}continue}let S=0,E=0;if(M){const b=d9*u[w],A=f9*d[w];S=Math.sin(t*b*Math.PI*2+l[w])*A,E=Math.sin(t*b*Math.PI*2+l[w]+Math.PI/2)*A}if(c[y]+=(r+S)*e,c[y+1]-=n.fallSpeedMPerS*h[w]*e,c[y+2]+=(a+E)*e,c[y]=A0(c[y],n.radiusM),c[y+2]=A0(c[y+2],n.radiusM),c[y+1]<Zl){if(x){p[w]=sS*(.2+Math.random()*1.6),m[w]=p9*(.5+Math.random()),f[w]=m[w];const _=Math.random()*Math.PI*2,I=m9*(p[w]/sS);g[w]=Math.cos(_)*I,v[w]=Math.sin(_)*I,c[y+1]=Zl;continue}const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(b)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(b)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=d1(this.weather.precipitationIntensity);this.rainSystem=qN({count:u1,radiusM:Nu,heightM:s9,bottomYM:Xb,overallSpeed:r9,color:Yb.clone(),opacity:.85,visibleCount:this.precipitationCount(u1),speedStreak:Kb(t),pixelSize:eS,seed:9001,nearFocusDistanceM:jb,hazeDistanceM:Nu*Qb,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=o1,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=p1(4242),e=new Float32Array(xc*3),i=new Float32Array(xc),n=new Float32Array(xc),s=new Float32Array(xc);for(let h=0;h<xc;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Nu;e[h*3]=Math.cos(u)*d,e[h*3+1]=Xb,e[h*3+2]=Math.sin(u)*d,n[h]=rS(qb,Zb),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new ye;r.setAttribute("position",new ve(e,3));const a=new ve(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(xc));const c=new Re({uniforms:{uMaxSize:{value:l9},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Jb.clone()},uTexture:{value:E9()}},vertexShader:A9,fragmentShader:_9,transparent:!0,depthWrite:!1}),l=new Xs(r,c);l.renderOrder=o1,this.scene.add(l),this.rainSplashSystem={points:l,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*Je;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-d1(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(lt.litBySky(Yb,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(lt.litBySky(Jb,this.baseFogColor));const n=this.weather.windDirectionDeg*Je,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Nu,c=h=>(h%(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 l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=iS+(1-iS)*(1-l),u=nS+(1-nS)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=eS*h*(.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,l=0;c<i.length;c+=3,l++){if(n[l]+=t,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Nu;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=rS(qb,Zb),n[l]=0}a[l]=n[l]/s[l]}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 l=gn.brightnessAt(c,t);l>i&&(e=c,i=l)}const n=e?Math.min(1,Math.max(.1,(M9/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,l=s*f1*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Hr.r*l,this.airlight[1]+Hr.g*l,this.airlight[2]+Hr.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*y9;r.setRGB(1+c*Hr.r,1+c*Hr.g,1+c*Hr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*f1*this.relativeScale,e){const{x:c,y:l,z:h}=xi(25,e.azimuthDeg,ls);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new Po(ls*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=JL.map(t=>{const e=Xc.point(t,this.compassPoints),i=new G0({map:I9(e),depthTest:!1,fog:!1}),n=new pu(i),{x:s,y:r,z:a}=xi(0,t,zb);return n.position.set(s,r,a),n.scale.set(E0,E0,1),n.renderOrder=t9,n.layers.set(Qg),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=Bb*Math.PI/360,i=E0*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 Je=Math.PI/180;function $r(o,t,e){return Math.max(t,Math.min(e,o))}function rS(o,t){return o+Math.random()*(t-o)}function A0(o,t){return(o%(t*2)+t*3)%(t*2)-t}let _0,T0;function w9(o){switch(o){case"snow":return b9();case"hail":return S9()}}function b9(){if(_0)return _0;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),_0=new cc(t),_0}function S9(){if(T0)return T0;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),T0=new cc(t),T0}let R0;function E9(){if(R0)return R0;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),R0=new cc(t),R0}const A9=`
|
|
9267
9267
|
uniform float uMaxSize;
|
|
9268
9268
|
uniform float uScale;
|
|
9269
9269
|
attribute float aLife;
|
|
@@ -9558,6 +9558,6 @@ ${mi.generation}`;return this.snapshotMap?.key!==i&&(this.snapshotMap={key:i,ima
|
|
|
9558
9558
|
<button id="copy" class="share-copy" type="button"></button>
|
|
9559
9559
|
</div>
|
|
9560
9560
|
</dialog>
|
|
9561
|
-
`;class Uh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Uh.TAG)||customElements.define(Uh.TAG,Uh)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=r7;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.pin=t("pin"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,i=await _T.load(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.pin.checked;this.linkField.value=e?oa.pinnedLink(t.link(),"0.170.
|
|
9562
|
-
${t.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const t=this.messages;if(!t)return;const 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("pin-label",t.pin.replace("{version}","0.170.0")),this.pin.parentElement.title=t.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",t.close),this.linkField.setAttribute("aria-label",t.link)}show(t){this.linkBox.hidden=t!=="link",this.embedBox.hidden=t!=="embed",this.linkOption.setAttribute("aria-pressed",String(t==="link")),this.embedOption.setAttribute("aria-pressed",String(t==="embed")),t==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Et(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 Vn{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(Vn.PLAIN.test(e))return Vn.num(e);const i=Vn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||Vn.num(a)>=60?void 0:Vn.num(s)*3600+Number(r)*60+Vn.num(a)}const n=Vn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?Vn.num(n[1])*3600+Vn.num(n[2])*60+Vn.num(n[3]):/^P/i.test(e)?yh.seconds(e.toUpperCase()):void 0}static isClock(t){return Vn.clock(t)!==void 0}static clock(t){const e=Vn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,l={hour:Number(r),minute:Number(a),second:Vn.num(c)};if(!(l.hour>=24||l.minute>=60||l.second>=60)){if(i!==void 0){const h={year:Number(i),month:Number(n),day:Number(s)};if(h.month<1||h.month>12||h.day<1||h.day>31)return;l.date=h}return l}}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)}}i3();Uh.register();const J0=Zd.home(),D0="compare-account",y1="start-time",MS="start-clock",Uu="observer",C0="case",O0="account",P0="variant-",x1=`${J0}/edit/`;class $p extends HTMLElement{static get observedAttributes(){return["src","show-labels",y1,MS,Uu,ma,ga,D0]}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;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;ready=Promise.resolve();constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${R_}</style>${T_}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(Xp),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.accountElement=this.shadow.getElementById("account"),this.accountPrefix=this.shadow.getElementById("account-prefix"),this.observerText=this.shadow.getElementById("observer-text"),this.observerSelect=this.shadow.getElementById("observer"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.editLink=this.shadow.getElementById("edit-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.labelsToggle=this.shadow.getElementById("info-labels-toggle"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=jt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=i=>({input:this.shadow.getElementById(`share-opt-${i}`),label:this.shadow.getElementById(`share-opt-${i}-label`)});this.shareOptions={labels:e("labels"),map:e("map"),milestones:e("milestones"),compare:e("compare")},this.interpretationChoice=this.shadow.getElementById("interpretation-choice"),this.interpretationLabel=this.shadow.getElementById("interpretation-label"),this.interpretationSelect=this.shadow.getElementById("interpretation"),this.confrontationElement=this.shadow.getElementById("confrontation"),this.confrontationHeading=this.shadow.getElementById("confrontation-heading"),this.confrontationList=this.shadow.getElementById("confrontation-list"),this.compareButton=this.shadow.getElementById("compare-account"),this.variantChips=this.shadow.getElementById("variant-chips"),this.variantMoved=this.shadow.getElementById("variant-moved"),this.compareButton.addEventListener("click",()=>this.setComparing(!this.sceneElement.compareAccount)),this.observerSelect.addEventListener("change",()=>this.selectObserver(this.observerSelect.value)),this.interpretationSelect.addEventListener("change",()=>void this.chooseInterpretation(this.interpretationSelect.value)),this.sceneElement.addEventListener(e3,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.ready=this.loadLocaleMessages())}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=ja.preferencesFor(this);this.preferences=e;const i=rp(e,hp),[n,s,r]=await Promise.all([ET.load(i),TT(i),HS(i)]);if(t!==this.localeToken)return;const a=i!==this.language||this.messages===void 0;this.language=i,this.messages=n,this.tags=new A1(s),this.said=new Ks(e),this.summaryBuilder=new Ec(this.messages,new uM(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(l=>l.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 Ks(["en"]);tags=new A1({});connectedCallback(){ja.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=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===ma||t===ga)&&this.forwardPlayerAttributes(),t===Uu&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===D0&&this.setComparing(this.hasAttribute(D0))}forwardPlayerAttributes(){for(const t of[ma,ga]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=jo.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(yn.isCase(i)){yn.check(i);const n=yn.sightingUrls(i,new URL(t,location.href).href);if(n.length===0)throw new Error(`${t} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(n,{json:i,url:new URL(t,location.href).href})}else this.setEntries([{src:t,sighting:i}],void 0)}get sightingData(){return this.entries.find(t=>t.src===this.currentSrc)?.sighting}set sightingData(t){const e=Fi.toCurrent(t);this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:e}],void 0)}seekTo(t,e){const i=this.caseSource,n=e===void 0?void 0:this.entries.find(s=>{const r=this.plain(s).id;return(i?yn.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 jo.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=yn.problems(t,e.map(s=>this.plain(s).id).filter(s=>s!==void 0));for(const s of i)console.warn(`The case ${t.id??""} gives the id "${s}" to more than one event: a reference to it is ambiguous.`);for(const{reading:s,reference:r}of n)console.warn(`The reading ${s} of the case ${t.id??""} is "interpretationOf" "${r}", which no event of the case has as its id, nor any recording it lists.`)}setEntries(t,e){this.entries=t.map(r=>({...r,sighting:Fi.toCurrent(r.sighting)})),this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";const n=t.map((r,a)=>this.observerDisplayName(this.plain(r).observer)??this.caseTitleOf(r)??(this.messages?.unnamedObserver??"").replace("{n}",String(a+1)));for(const[r,a]of t.entries()){const c=document.createElement("option");c.value=a.src;const l=n.filter(h=>h===n[r]).length>1;c.textContent=(l?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(Uu)?.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===C0))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===C0}editorUrl(){if(!this.currentSrc)return x1;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${x1}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${x1}?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=yn.interpretationEvents(t.json,yn.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?[[Uu,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?[`${Uu}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${J0}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${J0}/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([y1,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([ma,""]),t.milestones.input.checked||e.push([ga,""]),t.compare.input.checked&&e.push([D0,""]),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,C0,this.messages?.shareScopeCase??"");for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??this.caseTitleOf(i)??(this.messages?.unnamedObserver??"").replace("{n}",String(this.entries.indexOf(i)+1));e(this.shareScope,i.src,n),e(this.shareOpens,i.src,n)}this.shareScope.value=C0,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(O0,this.messages?.account??"",()=>Promise.resolve(r));const a=this.caseSource;a&&yn.interpretationEvents(a.json,yn.accountIds(a.json,a.url,t.src,this.plain(t).id)).forEach((u,d)=>{const f=this.said.read(u.title)??`#${d+1}`,p=(u.by??[]).map(m=>this.agentName(m)).filter(Boolean).join(", ");n(`case-${d}`,p?(this.messages?.interpretationBy??"").replace("{title}",f).replace("{by}",p):f,()=>yn.interpretationOf(u,a.url,m=>jo.recording(m)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${P0}${u}`,`${this.variantLabel(d)} (${this.messages?.verdicts[d.variant.verdict]??""})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const h=e&&[...this.interpretationSelect.options].some(u=>u.value===i)?i:O0;this.interpretationSelect.value=h,h===O0?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(h),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.messages)return;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(O0,this.messages?.account??"");for(const{index:i,kept:n}of t)e(`${P0}${i}`,n.variant.label??n.variant.candidate,n.variant.verdict);this.showVariantMoved()}showVariantMoved(){if(!this.messages)return;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(P0)?Number(t.slice(P0.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)}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],l)=>{l>0&&s.append(" · ");const h=document.createElement("span");h.textContent=a,c&&(h.className="disagrees"),s.append(h)}),this.confrontationList.appendChild(s)}}startPending=!1;startSeconds(t){const e=Vn.clock(this.getAttribute(MS)),i=this.plain(t).time;return(e?Vn.elapsedSince(i===void 0?void 0:bh(i),e):void 0)??Vn.delta(this.getAttribute(y1))}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(a7,{detail:{src:t}}))}async runAssessments(){if(!this.messages)return;const t=++this.assessmentToken,e=await new bM(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=ms.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(l=>c===l||c.startsWith(`${l}.`))).map(c=>i.at(c)),r=s.reduce((c,l)=>n[l.basis]>n[c]?l.basis:c,"stated"),a=s.filter(c=>c.basis===r&&c.rationale).map(c=>c.rationale);return{basis:r,rationales:a}}formatDate(t){const e=t.place?.locations?.[0],i=Sc((t.time?bh(t.time):void 0)??{},e?.lng??0,t.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(t,e?.lng??0)*36e5;if(Number.isFinite(n))return new Intl.DateTimeFormat(this.language,{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(t,e){return t.utcOffsetHours??Math.round(e/15)}formatLocation(t){const e=t.place?.locations?.[0];if(e)return`${e.lat.toFixed(4)}, ${e.lng.toFixed(4)}`}toggleInfoPanel(){const t=!this.infoOpen;if(this.supportsPopover){const e=this.infoPanel.matches(":popover-open");t&&!e?this.infoPanel.showPopover():!t&&e&&this.infoPanel.hidePopover();return}t&&this.bringInfoButtonIntoView(),this.syncInfoOpen(t),this.infoPanel.hidden=!t,t?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const t=this.infoButton.getBoundingClientRect(),e=window.innerHeight||document.documentElement.clientHeight;t.top>=0&&t.bottom<=e||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(t){t!==this.infoOpen&&(this.infoOpen=t,this.infoButton.setAttribute("aria-expanded",String(t)),t?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=t=>{const e=t.composedPath();!e.includes(this.infoPanel)&&!e.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}revealInPanel(t){t.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(t){this.toggleAttribute("show-labels",t)}applyLabels(t){this.labelsShown=t,this.syncLabelsToggle(),this.refreshParamSummary(),this.populateInfoPanel()}syncLabelsToggle(){this.labelsToggle.textContent=this.labelsShown?this.messages?.hideLabels??"":this.messages?.showLabels??"",this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,!this.labelsShown){this.paramSummary.replaceChildren(),this.summarySignature="";return}const t=this.sceneElement.ufoElement.sighting,e=[...this.summaryBuilder?.entriesFor(t,this.sceneElement.ufoElement.currentTime,{roadGradeDeg:this.sceneElement.roadGradeDeg})??[],...this.assessmentEntries],i=e.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.full??""}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of e){s&&s.group!==r.group&&(s=void 0);const a=r.group==="summary"?this.messages?.summaryGroup??"":r.group==="observer"?this.messages?.observerGroup??"":this.messages&&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 l=document.createElement("span");l.className="param-nest";const h=document.createElement("span");h.className="param-nest-label",h.textContent=a,l.append(h),s={group:r.group,element:l},n.push(l)}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),OS.sync(this.paramSummary,this.openDescription,this.messages?.summaryDescription??"",this.messages?.closeDescription??"",()=>{this.openDescription=void 0,this.syncDescription(t)})}paramItem(t){const e=document.createElement("span");if(e.className=t.fromSource?"param-label from-source":"param-label",t.detail&&(e.title=t.detail),t.full!==void 0){e.classList.add("describable"),e.tabIndex=0,e.setAttribute("role","button");const s=()=>{this.openDescription=t.full,this.syncDescription([t])};e.addEventListener("click",s),e.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),s())})}const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${t.label} `,e.append(i),t.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=t.color,e.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=t.unit===""?t.value:`${t.value} ${t.unit}`,e.append(n),e}populateInfoPanel(){const t=this.entries.find(e=>e.src===this.currentSrc);if(this.infoObservationList.innerHTML="",t){const e=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(e&&this.appendInfoRow(this.infoObservationList,this.messages?.case??"",e),!this.labelsShown){const s=this.formatDate(this.plain(t));s&&this.appendInfoRow(this.infoObservationList,this.messages?.date??"",s,this.basisOf(t,$p.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages?.location??"",r,this.basisOf(t,$p.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=J0,this.infoAppLink.textContent="UFO@home v0.170.0",Bn.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=this.said.read(i.title)??i.url??"";if(i.url&&/^https?:\/\//i.test(i.url)){const c=document.createElement("a");c.href=i.url,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,s.appendChild(c)}else s.append(r);const a=[i.authors?.join(", "),i.publication?.publisher,i.publication?.time,i.index].filter(Boolean);a.length>0&&s.append(`, ${a.join(", ")}`),t.append(n,s)}static DATE_PATHS=["time","utcOffsetHours","timeZone"];static PLACE_PATHS=["place"];appendInfoRow(t,e,i,n){if(!this.messages)return;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(`
|
|
9561
|
+
`;class Uh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Uh.TAG)||customElements.define(Uh.TAG,Uh)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=r7;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.pin=t("pin"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,i=await _T.load(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.pin.checked;this.linkField.value=e?oa.pinnedLink(t.link(),"0.170.1"):t.link(),this.fitLink();const n=`<script type="module" src="${e?oa.pinned(t.module,"0.170.1"):oa.current(t.module,import.meta.url,Zd.home())}"><\/script>
|
|
9562
|
+
${t.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const t=this.messages;if(!t)return;const 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("pin-label",t.pin.replace("{version}","0.170.1")),this.pin.parentElement.title=t.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",t.close),this.linkField.setAttribute("aria-label",t.link)}show(t){this.linkBox.hidden=t!=="link",this.embedBox.hidden=t!=="embed",this.linkOption.setAttribute("aria-pressed",String(t==="link")),this.embedOption.setAttribute("aria-pressed",String(t==="embed")),t==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Et(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 Vn{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(Vn.PLAIN.test(e))return Vn.num(e);const i=Vn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||Vn.num(a)>=60?void 0:Vn.num(s)*3600+Number(r)*60+Vn.num(a)}const n=Vn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?Vn.num(n[1])*3600+Vn.num(n[2])*60+Vn.num(n[3]):/^P/i.test(e)?yh.seconds(e.toUpperCase()):void 0}static isClock(t){return Vn.clock(t)!==void 0}static clock(t){const e=Vn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,l={hour:Number(r),minute:Number(a),second:Vn.num(c)};if(!(l.hour>=24||l.minute>=60||l.second>=60)){if(i!==void 0){const h={year:Number(i),month:Number(n),day:Number(s)};if(h.month<1||h.month>12||h.day<1||h.day>31)return;l.date=h}return l}}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)}}i3();Uh.register();const J0=Zd.home(),D0="compare-account",y1="start-time",MS="start-clock",Uu="observer",C0="case",O0="account",P0="variant-",x1=`${J0}/edit/`;class $p extends HTMLElement{static get observedAttributes(){return["src","show-labels",y1,MS,Uu,ma,ga,D0]}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;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;ready=Promise.resolve();constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${R_}</style>${T_}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(Xp),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.accountElement=this.shadow.getElementById("account"),this.accountPrefix=this.shadow.getElementById("account-prefix"),this.observerText=this.shadow.getElementById("observer-text"),this.observerSelect=this.shadow.getElementById("observer"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.editLink=this.shadow.getElementById("edit-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.labelsToggle=this.shadow.getElementById("info-labels-toggle"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=jt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=i=>({input:this.shadow.getElementById(`share-opt-${i}`),label:this.shadow.getElementById(`share-opt-${i}-label`)});this.shareOptions={labels:e("labels"),map:e("map"),milestones:e("milestones"),compare:e("compare")},this.interpretationChoice=this.shadow.getElementById("interpretation-choice"),this.interpretationLabel=this.shadow.getElementById("interpretation-label"),this.interpretationSelect=this.shadow.getElementById("interpretation"),this.confrontationElement=this.shadow.getElementById("confrontation"),this.confrontationHeading=this.shadow.getElementById("confrontation-heading"),this.confrontationList=this.shadow.getElementById("confrontation-list"),this.compareButton=this.shadow.getElementById("compare-account"),this.variantChips=this.shadow.getElementById("variant-chips"),this.variantMoved=this.shadow.getElementById("variant-moved"),this.compareButton.addEventListener("click",()=>this.setComparing(!this.sceneElement.compareAccount)),this.observerSelect.addEventListener("change",()=>this.selectObserver(this.observerSelect.value)),this.interpretationSelect.addEventListener("change",()=>void this.chooseInterpretation(this.interpretationSelect.value)),this.sceneElement.addEventListener(e3,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.ready=this.loadLocaleMessages())}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=ja.preferencesFor(this);this.preferences=e;const i=rp(e,hp),[n,s,r]=await Promise.all([ET.load(i),TT(i),HS(i)]);if(t!==this.localeToken)return;const a=i!==this.language||this.messages===void 0;this.language=i,this.messages=n,this.tags=new A1(s),this.said=new Ks(e),this.summaryBuilder=new Ec(this.messages,new uM(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(l=>l.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 Ks(["en"]);tags=new A1({});connectedCallback(){ja.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=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===ma||t===ga)&&this.forwardPlayerAttributes(),t===Uu&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===D0&&this.setComparing(this.hasAttribute(D0))}forwardPlayerAttributes(){for(const t of[ma,ga]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=jo.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(yn.isCase(i)){yn.check(i);const n=yn.sightingUrls(i,new URL(t,location.href).href);if(n.length===0)throw new Error(`${t} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(n,{json:i,url:new URL(t,location.href).href})}else this.setEntries([{src:t,sighting:i}],void 0)}get sightingData(){return this.entries.find(t=>t.src===this.currentSrc)?.sighting}set sightingData(t){const e=Fi.toCurrent(t);this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:e}],void 0)}seekTo(t,e){const i=this.caseSource,n=e===void 0?void 0:this.entries.find(s=>{const r=this.plain(s).id;return(i?yn.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 jo.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=yn.problems(t,e.map(s=>this.plain(s).id).filter(s=>s!==void 0));for(const s of i)console.warn(`The case ${t.id??""} gives the id "${s}" to more than one event: a reference to it is ambiguous.`);for(const{reading:s,reference:r}of n)console.warn(`The reading ${s} of the case ${t.id??""} is "interpretationOf" "${r}", which no event of the case has as its id, nor any recording it lists.`)}setEntries(t,e){this.entries=t.map(r=>({...r,sighting:Fi.toCurrent(r.sighting)})),this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";const n=t.map((r,a)=>this.observerDisplayName(this.plain(r).observer)??this.caseTitleOf(r)??(this.messages?.unnamedObserver??"").replace("{n}",String(a+1)));for(const[r,a]of t.entries()){const c=document.createElement("option");c.value=a.src;const l=n.filter(h=>h===n[r]).length>1;c.textContent=(l?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(Uu)?.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===C0))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===C0}editorUrl(){if(!this.currentSrc)return x1;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${x1}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${x1}?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=yn.interpretationEvents(t.json,yn.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?[[Uu,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?[`${Uu}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${J0}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${J0}/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([y1,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([ma,""]),t.milestones.input.checked||e.push([ga,""]),t.compare.input.checked&&e.push([D0,""]),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,C0,this.messages?.shareScopeCase??"");for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??this.caseTitleOf(i)??(this.messages?.unnamedObserver??"").replace("{n}",String(this.entries.indexOf(i)+1));e(this.shareScope,i.src,n),e(this.shareOpens,i.src,n)}this.shareScope.value=C0,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(O0,this.messages?.account??"",()=>Promise.resolve(r));const a=this.caseSource;a&&yn.interpretationEvents(a.json,yn.accountIds(a.json,a.url,t.src,this.plain(t).id)).forEach((u,d)=>{const f=this.said.read(u.title)??`#${d+1}`,p=(u.by??[]).map(m=>this.agentName(m)).filter(Boolean).join(", ");n(`case-${d}`,p?(this.messages?.interpretationBy??"").replace("{title}",f).replace("{by}",p):f,()=>yn.interpretationOf(u,a.url,m=>jo.recording(m)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${P0}${u}`,`${this.variantLabel(d)} (${this.messages?.verdicts[d.variant.verdict]??""})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const h=e&&[...this.interpretationSelect.options].some(u=>u.value===i)?i:O0;this.interpretationSelect.value=h,h===O0?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(h),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.messages)return;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(O0,this.messages?.account??"");for(const{index:i,kept:n}of t)e(`${P0}${i}`,n.variant.label??n.variant.candidate,n.variant.verdict);this.showVariantMoved()}showVariantMoved(){if(!this.messages)return;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(P0)?Number(t.slice(P0.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)}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],l)=>{l>0&&s.append(" · ");const h=document.createElement("span");h.textContent=a,c&&(h.className="disagrees"),s.append(h)}),this.confrontationList.appendChild(s)}}startPending=!1;startSeconds(t){const e=Vn.clock(this.getAttribute(MS)),i=this.plain(t).time;return(e?Vn.elapsedSince(i===void 0?void 0:bh(i),e):void 0)??Vn.delta(this.getAttribute(y1))}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(a7,{detail:{src:t}}))}async runAssessments(){if(!this.messages)return;const t=++this.assessmentToken,e=await new bM(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=ms.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(l=>c===l||c.startsWith(`${l}.`))).map(c=>i.at(c)),r=s.reduce((c,l)=>n[l.basis]>n[c]?l.basis:c,"stated"),a=s.filter(c=>c.basis===r&&c.rationale).map(c=>c.rationale);return{basis:r,rationales:a}}formatDate(t){const e=t.place?.locations?.[0],i=Sc((t.time?bh(t.time):void 0)??{},e?.lng??0,t.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(t,e?.lng??0)*36e5;if(Number.isFinite(n))return new Intl.DateTimeFormat(this.language,{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(t,e){return t.utcOffsetHours??Math.round(e/15)}formatLocation(t){const e=t.place?.locations?.[0];if(e)return`${e.lat.toFixed(4)}, ${e.lng.toFixed(4)}`}toggleInfoPanel(){const t=!this.infoOpen;if(this.supportsPopover){const e=this.infoPanel.matches(":popover-open");t&&!e?this.infoPanel.showPopover():!t&&e&&this.infoPanel.hidePopover();return}t&&this.bringInfoButtonIntoView(),this.syncInfoOpen(t),this.infoPanel.hidden=!t,t?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const t=this.infoButton.getBoundingClientRect(),e=window.innerHeight||document.documentElement.clientHeight;t.top>=0&&t.bottom<=e||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(t){t!==this.infoOpen&&(this.infoOpen=t,this.infoButton.setAttribute("aria-expanded",String(t)),t?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=t=>{const e=t.composedPath();!e.includes(this.infoPanel)&&!e.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}revealInPanel(t){t.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(t){this.toggleAttribute("show-labels",t)}applyLabels(t){this.labelsShown=t,this.syncLabelsToggle(),this.refreshParamSummary(),this.populateInfoPanel()}syncLabelsToggle(){this.labelsToggle.textContent=this.labelsShown?this.messages?.hideLabels??"":this.messages?.showLabels??"",this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,!this.labelsShown){this.paramSummary.replaceChildren(),this.summarySignature="";return}const t=this.sceneElement.ufoElement.sighting,e=[...this.summaryBuilder?.entriesFor(t,this.sceneElement.ufoElement.currentTime,{roadGradeDeg:this.sceneElement.roadGradeDeg})??[],...this.assessmentEntries],i=e.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.full??""}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of e){s&&s.group!==r.group&&(s=void 0);const a=r.group==="summary"?this.messages?.summaryGroup??"":r.group==="observer"?this.messages?.observerGroup??"":this.messages&&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 l=document.createElement("span");l.className="param-nest";const h=document.createElement("span");h.className="param-nest-label",h.textContent=a,l.append(h),s={group:r.group,element:l},n.push(l)}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),OS.sync(this.paramSummary,this.openDescription,this.messages?.summaryDescription??"",this.messages?.closeDescription??"",()=>{this.openDescription=void 0,this.syncDescription(t)})}paramItem(t){const e=document.createElement("span");if(e.className=t.fromSource?"param-label from-source":"param-label",t.detail&&(e.title=t.detail),t.full!==void 0){e.classList.add("describable"),e.tabIndex=0,e.setAttribute("role","button");const s=()=>{this.openDescription=t.full,this.syncDescription([t])};e.addEventListener("click",s),e.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),s())})}const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${t.label} `,e.append(i),t.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=t.color,e.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=t.unit===""?t.value:`${t.value} ${t.unit}`,e.append(n),e}populateInfoPanel(){const t=this.entries.find(e=>e.src===this.currentSrc);if(this.infoObservationList.innerHTML="",t){const e=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(e&&this.appendInfoRow(this.infoObservationList,this.messages?.case??"",e),!this.labelsShown){const s=this.formatDate(this.plain(t));s&&this.appendInfoRow(this.infoObservationList,this.messages?.date??"",s,this.basisOf(t,$p.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages?.location??"",r,this.basisOf(t,$p.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=J0,this.infoAppLink.textContent="UFO@home v0.170.1",Bn.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=this.said.read(i.title)??i.url??"";if(i.url&&/^https?:\/\//i.test(i.url)){const c=document.createElement("a");c.href=i.url,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,s.appendChild(c)}else s.append(r);const a=[i.authors?.join(", "),i.publication?.publisher,i.publication?.time,i.index].filter(Boolean);a.length>0&&s.append(`, ${a.join(", ")}`),t.append(n,s)}static DATE_PATHS=["time","utcOffsetHours","timeZone"];static PLACE_PATHS=["place"];appendInfoRow(t,e,i,n){if(!this.messages)return;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(`
|
|
9563
9563
|
`)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const yS="rr0-sighting",a7="observerchange";function o7(){i3(),Uh.register(),customElements.get(yS)||customElements.define(yS,$p)}o7();export{pu as $,Gc as A,Ht as B,rt as C,Jl as D,jr as E,fe as F,Xe as G,wt as H,b7 as I,_e as J,ro as K,E1 as L,Ae as M,Wt as N,u7 as O,kT as P,pv as Q,Dt as R,Ks as S,Di as T,s4 as U,yr as V,v7 as W,Xs as X,G0 as Y,cc as Z,Et as _,On as a,GE as a$,Ms as a0,bn as a1,x7 as a2,qc as a3,_n as a4,g7 as a5,Nn as a6,ge as a7,Fn as a8,Oi as a9,Ix as aA,y7 as aB,S7 as aC,EE as aD,qs as aE,pf as aF,Hm as aG,v5 as aH,ti as aI,ic as aJ,L1 as aK,Ki as aL,Ta as aM,SR as aN,li as aO,d7 as aP,p7 as aQ,TE as aR,m7 as aS,Wn as aT,Js as aU,_E as aV,qx as aW,vR as aX,WA as aY,pp as aZ,dv as a_,an as aa,os as ab,Pi as ac,Y9 as ad,My as ae,K9 as af,js as ag,De as ah,L0 as ai,ep as aj,Kl as ak,cr as al,tp as am,fs as an,pa as ao,c7 as ap,h7 as aq,l7 as ar,nf as as,w7 as at,M7 as au,vp as av,WE as aw,Ep as ax,f7 as ay,rs as az,ZS as b,VM as b0,WM as b1,Fe as b2,Sa as b3,ef as b4,qt as b5,wn as b6,Kr as b7,ya as b8,xi as b9,sc as ba,Yd as bb,pt as bc,IP as bd,Ch as be,Gt as bf,oh as bg,qM as bh,Ft as bi,GM as bj,Qo as bk,Ea as bl,ys as bm,as as bn,tu as bo,Zi as bp,Ld as c,t0 as d,ld as e,JS as f,Is as g,o4 as h,ae as i,Mt as j,tt as k,Ps as l,Zu as m,ye as n,Fo as o,MT as p,ve as q,Cr as r,Sc as s,pr as t,E7 as u,wp as v,Ke as w,fr as x,R as y,Re as z};
|