@rr0/ufoathome 0.178.4 → 0.179.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-interview/InterviewMessages_en-ru7GkZlQ.js +1 -0
- package/dist-embed-interview/InterviewMessages_es-DkJurNrG.js +1 -0
- package/dist-embed-interview/InterviewMessages_fr-DAYgf8Ms.js +1 -0
- package/dist-embed-interview/InterviewMessages_it-6lenkmSg.js +1 -0
- package/dist-embed-interview/rr0-interview.mjs +2 -2
- package/dist-embed-scene/{BeamEditor-DFGRzRny.js → BeamEditor-DXIKipID.js} +1 -1
- package/dist-embed-scene/{LanternEditor-H8VYYbRn.js → LanternEditor-JvQQ8GOQ.js} +1 -1
- package/dist-embed-scene/LaunchEditor-DIxYPs4d.js +22 -0
- package/dist-embed-scene/{LaunchPlume-eEIp7_hM.js → LaunchPlume-FP3Yk-8B.js} +1 -1
- package/dist-embed-scene/{LaunchSimulation-DNNEzmzs.js → LaunchSimulation-v4khqz4r.js} +1 -1
- package/dist-embed-scene/{ModuleSession-DLoAutYP.js → ModuleSession-CLUE46BO.js} +2 -2
- package/dist-embed-scene/{ModuleThree-R2LhnY95.js → ModuleThree-DQfMGMDy.js} +1 -1
- package/dist-embed-scene/{ParameterForm-ez-n_0Dw.js → ParameterForm-BFp5BoHL.js} +9 -12
- package/dist-embed-scene/{ReentryEditor-CwY4oANp.js → ReentryEditor-ByVtt--5.js} +6 -6
- package/dist-embed-scene/{ReentrySimulation-BDgEPekW.js → ReentrySimulation-nzg5V3kJ.js} +1 -1
- package/dist-embed-scene/{TimelineTracks-BQXJMJaJ.js → TimelineTracks-BOjTfdGu.js} +2 -2
- package/dist-embed-scene/rr0-scene.mjs +333 -322
- package/dist-embed-sighting/{CaseReportExport-DHdgnsTQ.js → CaseReportExport-C30Foqx0.js} +1 -1
- package/dist-embed-sighting/{InterviewElement-Byb_sxbO.js → InterviewElement-BduwyUn5.js} +2 -2
- package/dist-embed-sighting/InterviewMessages_en-ru7GkZlQ.js +1 -0
- package/dist-embed-sighting/InterviewMessages_es-DkJurNrG.js +1 -0
- package/dist-embed-sighting/InterviewMessages_fr-DAYgf8Ms.js +1 -0
- package/dist-embed-sighting/InterviewMessages_it-6lenkmSg.js +1 -0
- package/dist-embed-sighting/rr0-sighting.mjs +36 -28
- package/dist-embed-sighting-editor/{AdsbLolArchiveProvider-fZkxLAHp.js → AdsbLolArchiveProvider-DEqEth50.js} +1 -1
- package/dist-embed-sighting-editor/AssemblyAiTranscriptionProvider-o2kkPD5o.js +1 -0
- package/dist-embed-sighting-editor/{BallesterGuaspAssessor-DASadJjI.js → BallesterGuaspAssessor-ClwhCo4B.js} +1 -1
- package/dist-embed-sighting-editor/{BeamEditor-B2diaX_e.js → BeamEditor-vxinYAhV.js} +1 -1
- package/dist-embed-sighting-editor/{BeamSystem-BfNJfayv.js → BeamSystem-BMyP16H9.js} +1 -1
- package/dist-embed-sighting-editor/{BodyEditor-CCBXFuuL.js → BodyEditor-Dn5HrH2t.js} +1 -1
- package/dist-embed-sighting-editor/BrowserWhisperProvider-Dn44ZE45.js +1 -0
- package/dist-embed-sighting-editor/{CaseReportExport-D_e5Uij7.js → CaseReportExport-Ct_2DUSO.js} +2 -2
- package/dist-embed-sighting-editor/{ContrailSystem-BWvO9taK.js → ContrailSystem-Y75rFfLJ.js} +1 -1
- package/dist-embed-sighting-editor/{ControlPasses-BQ_DUxa_.js → ControlPasses-oqSnNDq6.js} +1 -1
- package/dist-embed-sighting-editor/{CoverageAssessor-CSktyUlP.js → CoverageAssessor-CN-3cMS9.js} +1 -1
- package/dist-embed-sighting-editor/{Flightradar24Provider-OvRZWZWj.js → Flightradar24Provider-D3bM2ckV.js} +1 -1
- package/dist-embed-sighting-editor/GLTFLoader-CJy8wjmO.js +1 -0
- package/dist-embed-sighting-editor/{GenerativeKitMessages-BtNG1usJ.js → GenerativeKitMessages-I8xH2ec9.js} +1 -1
- package/dist-embed-sighting-editor/{GeoExportTexts-DBGGdRnP.js → GeoExportTexts-DAllttgw.js} +1 -1
- package/dist-embed-sighting-editor/{GeoJsonExport-BZ-0v8fM.js → GeoJsonExport-_yjIEd4F.js} +1 -1
- package/dist-embed-sighting-editor/GeographicFigures-DC6Tw3ja.js +1 -0
- package/dist-embed-sighting-editor/{HeadlightSystem-C-8Gl3vu.js → HeadlightSystem-DZN_EX7x.js} +1 -1
- package/dist-embed-sighting-editor/{HynekAssessor-CH2E88xV.js → HynekAssessor-CKjvYcVe.js} +1 -1
- package/dist-embed-sighting-editor/InterviewEditorElement-C7eNBUfn.js +270 -0
- package/dist-embed-sighting-editor/InterviewMessages_en-ru7GkZlQ.js +1 -0
- package/dist-embed-sighting-editor/InterviewMessages_es-DkJurNrG.js +1 -0
- package/dist-embed-sighting-editor/InterviewMessages_fr-DAYgf8Ms.js +1 -0
- package/dist-embed-sighting-editor/InterviewMessages_it-6lenkmSg.js +1 -0
- package/dist-embed-sighting-editor/{KmlExport-Bh4eTycx.js → KmlExport-dpml2tIJ.js} +1 -1
- package/dist-embed-sighting-editor/LanternEditor-CKKUIplQ.js +9 -0
- package/dist-embed-sighting-editor/{LaserBeam-CtogDP38.js → LaserBeam-Ct6opxMs.js} +1 -1
- package/dist-embed-sighting-editor/LaunchEditor-BfggZKq5.js +22 -0
- package/dist-embed-sighting-editor/{LaunchPlume-BtRrJTP9.js → LaunchPlume-CT777Ivp.js} +1 -1
- package/dist-embed-sighting-editor/{LaunchSimulation-xKwguVJt.js → LaunchSimulation-BSlF3Uq4.js} +1 -1
- package/dist-embed-sighting-editor/{ModelSource-CnKzaNDn.js → ModelSource-BQm0eN7H.js} +1 -1
- package/dist-embed-sighting-editor/{ModelThumbnails-UE_Er5EW.js → ModelThumbnails-Bwh2px6A.js} +1 -1
- package/dist-embed-sighting-editor/{ModelViewer-DoCshJc6.js → ModelViewer-Dl5ichWV.js} +1 -1
- package/dist-embed-sighting-editor/ModuleConformance-B8OYKQop.js +2 -0
- package/dist-embed-sighting-editor/{ModuleSession-CJstaNEN.js → ModuleSession-BQSTCqob.js} +3 -3
- package/dist-embed-sighting-editor/ModuleThree-DwGM2nF4.js +1 -0
- package/dist-embed-sighting-editor/{ModulesPanelElement-DdGqqdn4.js → ModulesPanelElement-CZcbo6lq.js} +3 -3
- package/dist-embed-sighting-editor/{NearestApproach-BH3Yw8Qz.js → NearestApproach-DkpM-8sl.js} +1 -1
- package/dist-embed-sighting-editor/OpenAiTranscriptionProvider-DDW446tK.js +1 -0
- package/dist-embed-sighting-editor/{PictureRegistration-B9C6iY17.js → PictureRegistration-CbfytwCX.js} +1 -1
- package/dist-embed-sighting-editor/{PoherAssessor-DWcCWUfa.js → PoherAssessor-C5-F9VMn.js} +1 -1
- package/dist-embed-sighting-editor/{RailwaySystem-D3VBmx1X.js → RailwaySystem-BxHS7Jka.js} +1 -1
- package/dist-embed-sighting-editor/{ReentryEditor-BDyG-48K.js → ReentryEditor-BgpCftyc.js} +2 -2
- package/dist-embed-sighting-editor/{ReentrySimulation-BQj0wWXW.js → ReentrySimulation-BHjJYTL1.js} +1 -1
- package/dist-embed-sighting-editor/{ReferenceSystem-C9NRL7UY.js → ReferenceSystem-BxKEbMVI.js} +1 -1
- package/dist-embed-sighting-editor/{RoadMarkings-ByQL2MTo.js → RoadMarkings-D9-6Cy9S.js} +1 -1
- package/dist-embed-sighting-editor/{SceneNames_en-BdRB6cjg.js → SceneNames_en-09L_ZfER.js} +1 -1
- package/dist-embed-sighting-editor/{SceneNames_es-Dk0UmXHp.js → SceneNames_es-C4PEieol.js} +1 -1
- package/dist-embed-sighting-editor/{SceneNames_fr-_z2iZ8Bm.js → SceneNames_fr-BGTFI_pF.js} +1 -1
- package/dist-embed-sighting-editor/{SceneNames_it-CE7fanb3.js → SceneNames_it-DHk5C-uS.js} +1 -1
- package/dist-embed-sighting-editor/{TraceSystem-g262KZ3G.js → TraceSystem-DAa5Lzof.js} +2 -2
- package/dist-embed-sighting-editor/TranscriptionAudio-C_xvRUv2.js +5 -0
- package/dist-embed-sighting-editor/TranscriptionError-D_TCbYbt.js +1 -0
- package/dist-embed-sighting-editor/{UfoMessages_en-JeMK-39o.js → UfoMessages_en-FAvzKxmR.js} +1 -1
- package/dist-embed-sighting-editor/{WaterSystem-CIbQPMqE.js → WaterSystem-C7hE-tnY.js} +1 -1
- package/dist-embed-sighting-editor/interviewImport-CgWyTdKb.js +4 -0
- package/dist-embed-sighting-editor/{interviewJson-DXD8FSBX.js → interviewJson-iURHP4Zk.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +30 -22
- package/dist-embed-sighting-editor/{surroundingsSources-BExFsNzP.js → surroundingsSources-YIawBCws.js} +1 -1
- package/dist-embed-sighting-editor/{trafficRuntime-CPRQW0Ho.js → trafficRuntime-j8tnHTec.js} +1 -1
- package/package.json +1 -1
- package/dist-embed-interview/InterviewMessages_en-BNau2xU8.js +0 -1
- package/dist-embed-interview/InterviewMessages_es-ypa0EDh9.js +0 -1
- package/dist-embed-interview/InterviewMessages_fr-OCQdwn9j.js +0 -1
- package/dist-embed-interview/InterviewMessages_it-awuOqf5v.js +0 -1
- package/dist-embed-scene/LaunchEditor-CIYcS0Y-.js +0 -22
- package/dist-embed-sighting/InterviewMessages_en-BNau2xU8.js +0 -1
- package/dist-embed-sighting/InterviewMessages_es-ypa0EDh9.js +0 -1
- package/dist-embed-sighting/InterviewMessages_fr-OCQdwn9j.js +0 -1
- package/dist-embed-sighting/InterviewMessages_it-awuOqf5v.js +0 -1
- package/dist-embed-sighting-editor/GLTFLoader-CM7Uk25s.js +0 -1
- package/dist-embed-sighting-editor/GeographicFigures-DqhWddS9.js +0 -1
- package/dist-embed-sighting-editor/InterviewEditorElement-Bz3hyZ-m.js +0 -234
- package/dist-embed-sighting-editor/InterviewMessages_en-BNau2xU8.js +0 -1
- package/dist-embed-sighting-editor/InterviewMessages_es-ypa0EDh9.js +0 -1
- package/dist-embed-sighting-editor/InterviewMessages_fr-OCQdwn9j.js +0 -1
- package/dist-embed-sighting-editor/InterviewMessages_it-awuOqf5v.js +0 -1
- package/dist-embed-sighting-editor/LanternEditor-tTk1vUZm.js +0 -9
- package/dist-embed-sighting-editor/LaunchEditor-CteAalch.js +0 -22
- package/dist-embed-sighting-editor/ModuleConformance-BKvZnuw9.js +0 -2
- package/dist-embed-sighting-editor/ModuleThree-1hxqvWFa.js +0 -1
- package/dist-embed-sighting-editor/interviewImport-C-TiARLK.js +0 -4
|
@@ -8,7 +8,7 @@ rr0-hint .hint-button { box-sizing: border-box; width: 1.35em; height: 1.35em; m
|
|
|
8
8
|
rr0-hint .hint-button:is(:hover, :focus-visible) { opacity: 1; }
|
|
9
9
|
rr0-hint .hint-pop { max-width: 22em; padding: .35em .6em; border-radius: 4px; background: rgba(0, 0, 0, .88); color: #fff; font: 400 .8rem/1.35 var(--sans, sans-serif); white-space: normal; }
|
|
10
10
|
${Ia.css("rr0-hint .hint-pop")}
|
|
11
|
-
`;button;popup;said="";static of(t){zr.register();const e=document.createElement(zr.TAG);return e.text=t,e}static say(t,e,i){t.textContent=e,i&&t.append(zr.of(i))}static register(){customElements.get(zr.TAG)||customElements.define(zr.TAG,zr)}get text(){return this.said}set text(t){this.said=t,this.build(),this.button.title=t,this.button.setAttribute("aria-label",t),this.popup.textContent=t}connectedCallback(){this.build()}build(){if(this.button)return;const t=document.createElement("button");t.type="button",t.className="hint-button",t.textContent="?";const e=document.createElement("span");e.className="hint-pop",e.setAttribute("role","tooltip"),Ia.attach(t,e),t.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Ia.show(e,e.hidden)}),t.addEventListener("blur",()=>Ia.show(e,!1)),this.append(t,e),this.button=t,this.popup=e}}const TT=["en","fr","es","it"];class Xn{static catalog(t){const e=new Map;return{load(i){const n=Xn.languageOf(i);let s=e.get(n);return s||(s=t[n](),e.set(n,s),s.catch(()=>e.delete(n))),s}}}static none(){return new Proxy({},{get:()=>""})}static blank(){const t=new Proxy(()=>t,{get:(e,i)=>i===Symbol.toPrimitive?()=>"":i===Symbol.iterator?function*(){}:i==="toString"||i==="valueOf"?()=>"":i==="then"?void 0:t,apply:()=>t,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{}});return t}static languageOf(t){const e=t.toLowerCase().split("-")[0];return TT.includes(e)?e:"en"}}const Mo=["en","fr","es","it"],RT={en:()=>at(()=>import("./UfoMessages_en-cLvtpfIC.js"),[],import.meta.url).then(o=>o.ufoMessages_en),fr:()=>at(()=>import("./UfoMessages_fr-CGkQBn5r.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>at(()=>import("./UfoMessages_es-CO-v8Jl6.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>at(()=>import("./UfoMessages_it-BScqxIaH.js"),[],import.meta.url).then(o=>o.ufoMessages_it)},IT=Xn.catalog(RT),DT={en:()=>at(()=>import("./SightingMessages_en-Xm6PILcs.js"),[],import.meta.url).then(o=>o.sightingMessages_en),fr:()=>at(()=>import("./SightingMessages_fr-NvQKGPaf.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>at(()=>import("./SightingMessages_es-DMp0MUjJ.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>at(()=>import("./SightingMessages_it-CKIf49Zt.js"),[],import.meta.url).then(o=>o.sightingMessages_it)},CT=Xn.catalog(DT),OT={en:()=>at(()=>import("./CaseMessages_en-CBS5QChl.js"),[],import.meta.url).then(o=>o.caseMessages_en),fr:()=>at(()=>import("./CaseMessages_fr-C3wQxAk_.js"),[],import.meta.url).then(o=>o.caseMessages_fr),es:()=>at(()=>import("./CaseMessages_es-DAMl4aTC.js"),[],import.meta.url).then(o=>o.caseMessages_es),it:()=>at(()=>import("./CaseMessages_it-CyrREg6v.js"),[],import.meta.url).then(o=>o.caseMessages_it)},PT=Xn.catalog(OT);function NT(o){return PT.load(o)}const LT={en:()=>at(()=>import("./ShareMessages_en-B43x8LgJ.js"),[],import.meta.url).then(o=>o.shareMessages_en),fr:()=>at(()=>import("./ShareMessages_fr-CzZyVbbX.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>at(()=>import("./ShareMessages_es-DZCJojSc.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>at(()=>import("./ShareMessages_it-C_Z6eDQK.js"),[],import.meta.url).then(o=>o.shareMessages_it)},kT=Xn.catalog(LT);function FT(o){switch(o){case"fr":return at(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return at(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return at(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}const UT={en:()=>at(()=>import("./ReadingSensitivityMessages_en-CF6XauSj.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_en),fr:()=>at(()=>import("./ReadingSensitivityMessages_fr-Djdd6Hdq.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_fr),es:()=>at(()=>import("./ReadingSensitivityMessages_es-Ca-13TTT.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_es),it:()=>at(()=>import("./ReadingSensitivityMessages_it-CPUXxMqD.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_it)},vE=Xn.catalog(UT),zT={en:()=>at(()=>import("./CaseExportMessages_en-jHlu58Y7.js"),[],import.meta.url).then(o=>o.caseExportMessages_en),fr:()=>at(()=>import("./CaseExportMessages_fr-sDfEgjWg.js"),[],import.meta.url).then(o=>o.caseExportMessages_fr),es:()=>at(()=>import("./CaseExportMessages_es-dCQQFgjq.js"),[],import.meta.url).then(o=>o.caseExportMessages_es),it:()=>at(()=>import("./CaseExportMessages_it-BJaglZtP.js"),[],import.meta.url).then(o=>o.caseExportMessages_it)},BT=Xn.catalog(zT),HT={en:()=>at(()=>import("./InterviewMessages_en-
|
|
11
|
+
`;button;popup;said="";static of(t){zr.register();const e=document.createElement(zr.TAG);return e.text=t,e}static say(t,e,i){t.textContent=e,i&&t.append(zr.of(i))}static register(){customElements.get(zr.TAG)||customElements.define(zr.TAG,zr)}get text(){return this.said}set text(t){this.said=t,this.build(),this.button.title=t,this.button.setAttribute("aria-label",t),this.popup.textContent=t}connectedCallback(){this.build()}build(){if(this.button)return;const t=document.createElement("button");t.type="button",t.className="hint-button",t.textContent="?";const e=document.createElement("span");e.className="hint-pop",e.setAttribute("role","tooltip"),Ia.attach(t,e),t.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Ia.show(e,e.hidden)}),t.addEventListener("blur",()=>Ia.show(e,!1)),this.append(t,e),this.button=t,this.popup=e}}const TT=["en","fr","es","it"];class Xn{static catalog(t){const e=new Map;return{load(i){const n=Xn.languageOf(i);let s=e.get(n);return s||(s=t[n](),e.set(n,s),s.catch(()=>e.delete(n))),s}}}static none(){return new Proxy({},{get:()=>""})}static blank(){const t=new Proxy(()=>t,{get:(e,i)=>i===Symbol.toPrimitive?()=>"":i===Symbol.iterator?function*(){}:i==="toString"||i==="valueOf"?()=>"":i==="then"?void 0:t,apply:()=>t,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{}});return t}static languageOf(t){const e=t.toLowerCase().split("-")[0];return TT.includes(e)?e:"en"}}const Mo=["en","fr","es","it"],RT={en:()=>at(()=>import("./UfoMessages_en-cLvtpfIC.js"),[],import.meta.url).then(o=>o.ufoMessages_en),fr:()=>at(()=>import("./UfoMessages_fr-CGkQBn5r.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>at(()=>import("./UfoMessages_es-CO-v8Jl6.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>at(()=>import("./UfoMessages_it-BScqxIaH.js"),[],import.meta.url).then(o=>o.ufoMessages_it)},IT=Xn.catalog(RT),DT={en:()=>at(()=>import("./SightingMessages_en-Xm6PILcs.js"),[],import.meta.url).then(o=>o.sightingMessages_en),fr:()=>at(()=>import("./SightingMessages_fr-NvQKGPaf.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>at(()=>import("./SightingMessages_es-DMp0MUjJ.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>at(()=>import("./SightingMessages_it-CKIf49Zt.js"),[],import.meta.url).then(o=>o.sightingMessages_it)},CT=Xn.catalog(DT),OT={en:()=>at(()=>import("./CaseMessages_en-CBS5QChl.js"),[],import.meta.url).then(o=>o.caseMessages_en),fr:()=>at(()=>import("./CaseMessages_fr-C3wQxAk_.js"),[],import.meta.url).then(o=>o.caseMessages_fr),es:()=>at(()=>import("./CaseMessages_es-DAMl4aTC.js"),[],import.meta.url).then(o=>o.caseMessages_es),it:()=>at(()=>import("./CaseMessages_it-CyrREg6v.js"),[],import.meta.url).then(o=>o.caseMessages_it)},PT=Xn.catalog(OT);function NT(o){return PT.load(o)}const LT={en:()=>at(()=>import("./ShareMessages_en-B43x8LgJ.js"),[],import.meta.url).then(o=>o.shareMessages_en),fr:()=>at(()=>import("./ShareMessages_fr-CzZyVbbX.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>at(()=>import("./ShareMessages_es-DZCJojSc.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>at(()=>import("./ShareMessages_it-C_Z6eDQK.js"),[],import.meta.url).then(o=>o.shareMessages_it)},kT=Xn.catalog(LT);function FT(o){switch(o){case"fr":return at(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return at(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return at(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}const UT={en:()=>at(()=>import("./ReadingSensitivityMessages_en-CF6XauSj.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_en),fr:()=>at(()=>import("./ReadingSensitivityMessages_fr-Djdd6Hdq.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_fr),es:()=>at(()=>import("./ReadingSensitivityMessages_es-Ca-13TTT.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_es),it:()=>at(()=>import("./ReadingSensitivityMessages_it-CPUXxMqD.js"),[],import.meta.url).then(o=>o.readingSensitivityMessages_it)},vE=Xn.catalog(UT),zT={en:()=>at(()=>import("./CaseExportMessages_en-jHlu58Y7.js"),[],import.meta.url).then(o=>o.caseExportMessages_en),fr:()=>at(()=>import("./CaseExportMessages_fr-sDfEgjWg.js"),[],import.meta.url).then(o=>o.caseExportMessages_fr),es:()=>at(()=>import("./CaseExportMessages_es-dCQQFgjq.js"),[],import.meta.url).then(o=>o.caseExportMessages_es),it:()=>at(()=>import("./CaseExportMessages_it-BJaglZtP.js"),[],import.meta.url).then(o=>o.caseExportMessages_it)},BT=Xn.catalog(zT),HT={en:()=>at(()=>import("./InterviewMessages_en-ru7GkZlQ.js"),[],import.meta.url).then(o=>o.interviewMessages_en),fr:()=>at(()=>import("./InterviewMessages_fr-DAYgf8Ms.js"),[],import.meta.url).then(o=>o.interviewMessages_fr),es:()=>at(()=>import("./InterviewMessages_es-DkJurNrG.js"),[],import.meta.url).then(o=>o.interviewMessages_es),it:()=>at(()=>import("./InterviewMessages_it-6lenkmSg.js"),[],import.meta.url).then(o=>o.interviewMessages_it)},J7=Xn.catalog(HT),GT=Xn.catalog({en:()=>at(()=>import("./SceneNames_en-ChY7v63o.js"),[],import.meta.url).then(o=>o.sceneNames_en),fr:()=>at(()=>import("./SceneNames_fr-Ca52lykk.js"),[],import.meta.url).then(o=>o.sceneNames_fr),es:()=>at(()=>import("./SceneNames_es-DH4YgJV5.js"),[],import.meta.url).then(o=>o.sceneNames_es),it:()=>at(()=>import("./SceneNames_it-BQe9GLaj.js"),[],import.meta.url).then(o=>o.sceneNames_it)});function ME(o){return GT.load(o)}class As extends HTMLElement{static TAG="rr0-reading-sensitivity";static CSS=`
|
|
12
12
|
:host { display: block; font-size: 13px; line-height: 1.4; color: var(--ink-dim, inherit); }
|
|
13
13
|
:host([hidden]) { display: none; }
|
|
14
14
|
details > summary { cursor: pointer; list-style-position: inside; }
|
|
@@ -780,7 +780,7 @@ ${yE.CSS}
|
|
|
780
780
|
* @license
|
|
781
781
|
* Copyright 2010-2026 Three.js Authors
|
|
782
782
|
* SPDX-License-Identifier: MIT
|
|
783
|
-
*/const _f="185",g4=0,Mw=1,v4=2,dd=1,M4=2,cd=3,Ba=0,zi=1,Tn=2,Ys=0,Mc=1,Cn=2,yw=3,ww=4,Ml=5,ao=100,y4=101,w4=102,x4=103,b4=104,Ta=200,yl=201,S4=202,E4=203,k0=204,af=205,A4=206,_4=207,T4=208,R4=209,I4=210,D4=211,C4=212,O4=213,P4=214,fv=0,pv=1,mv=2,fu=3,gv=4,vv=5,Mv=6,yv=7,ay=0,N4=1,L4=2,ka=0,XE=1,$E=2,YE=3,KE=4,qE=5,ZE=6,JE=7,xw="attached",k4="detached",jE=300,wl=301,pu=302,ag=303,og=304,Dm=306,bc=1e3,Qi=1001,wv=1002,si=1003,F4=1004,zf=1005,Me=1006,cg=1007,cr=1008,fs=1009,QE=1010,tA=1011,of=1012,oy=1013,_r=1014,ts=1015,Ye=1016,cy=1017,ly=1018,cf=1020,eA=35902,iA=35899,nA=1021,sA=1022,tn=1023,So=1026,tl=1027,mu=1028,hy=1029,xl=1030,uy=1031,dy=1033,s0=33776,r0=33777,a0=33778,o0=33779,xv=35840,bv=35841,Sv=35842,Ev=35843,Av=36196,_v=37492,Tv=37496,Rv=37488,Iv=37489,F0=37490,Dv=37491,Cv=37808,Ov=37809,Pv=37810,Nv=37811,Lv=37812,kv=37813,Fv=37814,Uv=37815,zv=37816,Bv=37817,Hv=37818,Gv=37819,Vv=37820,Wv=37821,Xv=36492,$v=36494,Yv=36495,Kv=36283,qv=36284,U0=36285,Zv=36286,rA=2200,U4=2201,z4=2202,z0=2300,Jv=2301,lg=2302,bw=2303,Eh=2400,Ah=2401,B0=2402,fy=2500,B4=2501,j7=0,Q7=1,tk=2,H4=3200,H0=0,G4=1,tc="",Bn="srgb",G0="srgb-linear",V0="linear",ui="srgb",Pl=7680,Sw=519,V4=512,W4=513,X4=514,py=515,$4=516,Y4=517,my=518,K4=519,jv=35044,W0="300 es",Ca=2e3,lf=2001;function q4(o){for(let t=o.length-1;t>=0;--t)if(o[t]>=65535)return!0;return!1}function Z4(o){return ArrayBuffer.isView(o)&&!(o instanceof DataView)}function hf(o){return document.createElementNS("http://www.w3.org/1999/xhtml",o)}function J4(){const o=hf("canvas");return o.style.display="block",o}const Ew={};function X0(...o){const t="THREE."+o.shift();console.log(t,...o)}function aA(o){const t=o[0];if(typeof t=="string"&&t.startsWith("TSL:")){const e=o[1];e&&e.isStackTrace?o[0]+=" "+e.getLocation():o[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return o}function Ht(...o){o=aA(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...o)}}function le(...o){o=aA(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...o)}}function Jh(...o){const t=o.join(" ");t in Ew||(Ew[t]=!0,Ht(...o))}function j4(o,t,e){return new Promise(function(i,n){function s(){switch(o.clientWaitSync(t,o.SYNC_FLUSH_COMMANDS_BIT,0)){case o.WAIT_FAILED:n();break;case o.TIMEOUT_EXPIRED:setTimeout(s,e);break;default:i()}}setTimeout(s,e)})}const Q4={[fv]:pv,[mv]:Mv,[gv]:yv,[fu]:vv,[pv]:fv,[Mv]:mv,[yv]:gv,[vv]:fu};class _c{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i===void 0?!1:i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const i=this._listeners;if(i===void 0)return;const n=i[t];if(n!==void 0){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}}dispatchEvent(t){const e=this._listeners;if(e===void 0)return;const i=e[t.type];if(i!==void 0){t.target=this;const n=i.slice(0);for(let s=0,r=n.length;s<r;s++)n[s].call(this,t);t.target=null}}}const ns=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Aw=1234567;const fd=Math.PI/180,gu=180/Math.PI;function Ar(){const o=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(ns[o&255]+ns[o>>8&255]+ns[o>>16&255]+ns[o>>24&255]+"-"+ns[t&255]+ns[t>>8&255]+"-"+ns[t>>16&15|64]+ns[t>>24&255]+"-"+ns[e&63|128]+ns[e>>8&255]+"-"+ns[e>>16&255]+ns[e>>24&255]+ns[i&255]+ns[i>>8&255]+ns[i>>16&255]+ns[i>>24&255]).toLowerCase()}function ge(o,t,e){return Math.max(t,Math.min(e,o))}function gy(o,t){return(o%t+t)%t}function tR(o,t,e,i,n){return i+(o-t)*(n-i)/(e-t)}function eR(o,t,e){return o!==t?(e-o)/(t-o):0}function pd(o,t,e){return(1-e)*o+e*t}function iR(o,t,e,i){return pd(o,t,1-Math.exp(-e*i))}function nR(o,t=1){return t-Math.abs(gy(o,t*2)-t)}function sR(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*(3-2*o))}function rR(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*o*(o*(o*6-15)+10))}function aR(o,t){return o+Math.floor(Math.random()*(t-o+1))}function oR(o,t){return o+Math.random()*(t-o)}function cR(o){return o*(.5-Math.random())}function lR(o){o!==void 0&&(Aw=o);let t=Aw+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function hR(o){return o*fd}function uR(o){return o*gu}function dR(o){return(o&o-1)===0&&o!==0}function fR(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function pR(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function mR(o,t,e,i,n){const s=Math.cos,r=Math.sin,a=s(e/2),c=r(e/2),l=s((t+i)/2),h=r((t+i)/2),u=s((t-i)/2),d=r((t-i)/2),f=s((i-t)/2),p=r((i-t)/2);switch(n){case"XYX":o.set(a*h,c*u,c*d,a*l);break;case"YZY":o.set(c*d,a*h,c*u,a*l);break;case"ZXZ":o.set(c*u,c*d,a*h,a*l);break;case"XZX":o.set(a*h,c*p,c*f,a*l);break;case"YXY":o.set(c*f,a*h,c*p,a*l);break;case"ZYZ":o.set(c*p,c*f,a*h,a*l);break;default:Ht("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Gr(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function di(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const ek={DEG2RAD:fd,RAD2DEG:gu,generateUUID:Ar,clamp:ge,euclideanModulo:gy,mapLinear:tR,inverseLerp:eR,lerp:pd,damp:iR,pingpong:nR,smoothstep:sR,smootherstep:rR,randInt:aR,randFloat:oR,randFloatSpread:cR,seededRandom:lR,degToRad:hR,radToDeg:uR,isPowerOfTwo:dR,ceilPowerOfTwo:fR,floorPowerOfTwo:pR,setQuaternionFromProperEuler:mR,normalize:di,denormalize:Gr};class tt{static{tt.prototype.isVector2=!0}constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=ge(this.x,t.x,e.x),this.y=ge(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=ge(this.x,t,e),this.y=ge(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(ge(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ge(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),n=Math.sin(e),s=this.x-t.x,r=this.y-t.y;return this.x=s*i-r*n+t.x,this.y=s*n+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class es{constructor(t=0,e=0,i=0,n=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=n}static slerpFlat(t,e,i,n,s,r,a){let c=i[n+0],l=i[n+1],h=i[n+2],u=i[n+3],d=s[r+0],f=s[r+1],p=s[r+2],m=s[r+3];if(u!==m||c!==d||l!==f||h!==p){let g=c*d+l*f+h*p+u*m;g<0&&(d=-d,f=-f,p=-p,m=-m,g=-g);let v=1-a;if(g<.9995){const M=Math.acos(g),w=Math.sin(M);v=Math.sin(v*M)/w,a=Math.sin(a*M)/w,c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+m*a}else{c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+m*a;const M=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=M,l*=M,h*=M,u*=M}}t[e]=c,t[e+1]=l,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,i,n,s,r){const a=i[n],c=i[n+1],l=i[n+2],h=i[n+3],u=s[r],d=s[r+1],f=s[r+2],p=s[r+3];return t[e]=a*p+h*u+c*f-l*d,t[e+1]=c*p+h*d+l*u-a*f,t[e+2]=l*p+h*f+a*d-c*u,t[e+3]=h*p-a*u-c*d-l*f,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,n){return this._x=t,this._y=e,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,n=t._y,s=t._z,r=t._order,a=Math.cos,c=Math.sin,l=a(i/2),h=a(n/2),u=a(s/2),d=c(i/2),f=c(n/2),p=c(s/2);switch(r){case"XYZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"YZX":this._x=d*h*u+l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u-d*f*p;break;case"XZY":this._x=d*h*u-l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u+d*f*p;break;default:Ht("Quaternion: .setFromEuler() encountered an unknown order: "+r)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,n=Math.sin(i);return this._x=t.x*n,this._y=t.y*n,this._z=t.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],n=e[4],s=e[8],r=e[1],a=e[5],c=e[9],l=e[2],h=e[6],u=e[10],d=i+a+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(s-l)*f,this._z=(r-n)*f}else if(i>a&&i>u){const f=2*Math.sqrt(1+i-a-u);this._w=(h-c)/f,this._x=.25*f,this._y=(n+r)/f,this._z=(s+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-i-u);this._w=(s-l)/f,this._x=(n+r)/f,this._y=.25*f,this._z=(c+h)/f}else{const f=2*Math.sqrt(1+u-i-a);this._w=(r-n)/f,this._x=(s+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(ge(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const n=Math.min(1,e/i);return this.slerp(t,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,n=t._y,s=t._z,r=t._w,a=e._x,c=e._y,l=e._z,h=e._w;return this._x=i*h+r*a+n*l-s*c,this._y=n*h+r*c+s*a-i*l,this._z=s*h+r*l+i*c-n*a,this._w=r*h-i*a-n*c-s*l,this._onChangeCallback(),this}slerp(t,e){let i=t._x,n=t._y,s=t._z,r=t._w,a=this.dot(t);a<0&&(i=-i,n=-n,s=-s,r=-r,a=-a);let c=1-e;if(a<.9995){const l=Math.acos(a),h=Math.sin(l);c=Math.sin(c*l)/h,e=Math.sin(e*l)/h,this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this._onChangeCallback()}else this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(n*Math.sin(t),n*Math.cos(t),s*Math.sin(e),s*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class T{static{T.prototype.isVector3=!0}constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(_w.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(_w.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6]*n,this.y=s[1]*e+s[4]*i+s[7]*n,this.z=s[2]*e+s[5]*i+s[8]*n,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=t.elements,r=1/(s[3]*e+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*e+s[4]*i+s[8]*n+s[12])*r,this.y=(s[1]*e+s[5]*i+s[9]*n+s[13])*r,this.z=(s[2]*e+s[6]*i+s[10]*n+s[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,a=t.z,c=t.w,l=2*(r*n-a*i),h=2*(a*e-s*n),u=2*(s*i-r*e);return this.x=e+c*l+r*u-a*h,this.y=i+c*h+a*l-s*u,this.z=n+c*u+s*h-r*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[4]*i+s[8]*n,this.y=s[1]*e+s[5]*i+s[9]*n,this.z=s[2]*e+s[6]*i+s[10]*n,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=ge(this.x,t.x,e.x),this.y=ge(this.y,t.y,e.y),this.z=ge(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=ge(this.x,t,e),this.y=ge(this.y,t,e),this.z=ge(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(ge(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,n=t.y,s=t.z,r=e.x,a=e.y,c=e.z;return this.x=n*c-s*a,this.y=s*r-i*c,this.z=i*a-n*r,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return hg.copy(this).projectOnVector(t),this.sub(hg)}reflect(t){return this.sub(hg.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ge(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const n=Math.sin(e)*t;return this.x=n*Math.sin(i),this.y=Math.cos(e)*t,this.z=n*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const hg=new T,_w=new es;class de{static{de.prototype.isMatrix3=!0}constructor(t,e,i,n,s,r,a,c,l){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l)}set(t,e,i,n,s,r,a,c,l){const h=this.elements;return h[0]=t,h[1]=n,h[2]=a,h[3]=e,h[4]=s,h[5]=c,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[3],c=i[6],l=i[1],h=i[4],u=i[7],d=i[2],f=i[5],p=i[8],m=n[0],g=n[3],v=n[6],M=n[1],w=n[4],y=n[7],x=n[2],b=n[5],E=n[8];return s[0]=r*m+a*M+c*x,s[3]=r*g+a*w+c*b,s[6]=r*v+a*y+c*E,s[1]=l*m+h*M+u*x,s[4]=l*g+h*w+u*b,s[7]=l*v+h*y+u*E,s[2]=d*m+f*M+p*x,s[5]=d*g+f*w+p*b,s[8]=d*v+f*y+p*E,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8];return e*r*h-e*a*l-i*s*h+i*a*c+n*s*l-n*r*c}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=h*r-a*l,d=a*c-h*s,f=l*s-r*c,p=e*u+i*d+n*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=u*m,t[1]=(n*l-h*i)*m,t[2]=(a*i-n*r)*m,t[3]=d*m,t[4]=(h*e-n*c)*m,t[5]=(n*s-a*e)*m,t[6]=f*m,t[7]=(i*c-l*e)*m,t[8]=(r*e-i*s)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,n,s,r,a){const c=Math.cos(s),l=Math.sin(s);return this.set(i*c,i*l,-i*(c*r+l*a)+r+t,-n*l,n*c,-n*(-l*r+c*a)+a+e,0,0,1),this}scale(t,e){return Jh("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(ug.makeScale(t,e)),this}rotate(t){return Jh("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(ug.makeRotation(-t)),this}translate(t,e){return Jh("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(ug.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<9;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new this.constructor().fromArray(this.elements)}}const ug=new de,Tw=new de().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Rw=new de().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function gR(){const o={enabled:!0,workingColorSpace:G0,spaces:{},convert:function(n,s,r){return this.enabled===!1||s===r||!s||!r||(this.spaces[s].transfer===ui&&(n.r=wo(n.r),n.g=wo(n.g),n.b=wo(n.b)),this.spaces[s].primaries!==this.spaces[r].primaries&&(n.applyMatrix3(this.spaces[s].toXYZ),n.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===ui&&(n.r=jh(n.r),n.g=jh(n.g),n.b=jh(n.b))),n},workingToColorSpace:function(n,s){return this.convert(n,this.workingColorSpace,s)},colorSpaceToWorking:function(n,s){return this.convert(n,s,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===tc?V0:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,s=this.workingColorSpace){return n.fromArray(this.spaces[s].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,s,r){return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,s){return Jh("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),o.workingToColorSpace(n,s)},toWorkingColorSpace:function(n,s){return Jh("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),o.colorSpaceToWorking(n,s)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],i=[.3127,.329];return o.define({[G0]:{primaries:t,whitePoint:i,transfer:V0,toXYZ:Tw,fromXYZ:Rw,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:Bn},outputColorSpaceConfig:{drawingBufferColorSpace:Bn}},[Bn]:{primaries:t,whitePoint:i,transfer:ui,toXYZ:Tw,fromXYZ:Rw,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:Bn}}}),o}const He=gR();function wo(o){return o<.04045?o*.0773993808:Math.pow(o*.9478672986+.0521327014,2.4)}function jh(o){return o<.0031308?o*12.92:1.055*Math.pow(o,.41666)-.055}let Nl;class vR{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{Nl===void 0&&(Nl=hf("canvas")),Nl.width=t.width,Nl.height=t.height;const n=Nl.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),i=Nl}return i.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=hf("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const n=i.getImageData(0,0,t.width,t.height),s=n.data;for(let r=0;r<s.length;r++)s[r]=wo(s[r]/255)*255;return i.putImageData(n,0,0),e}else if(t.data){const e=t.data.slice(0);for(let i=0;i<e.length;i++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[i]=Math.floor(wo(e[i]/255)*255):e[i]=wo(e[i]);return{data:e,width:t.width,height:t.height}}else return Ht("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let MR=0;class vy{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:MR++}),this.uuid=Ar(),this.data=t,this.dataReady=!0,this.version=0}getSize(t){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?t.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?t.set(e.displayWidth,e.displayHeight,0):e!==null?t.set(e.width,e.height,e.depth||0):t.set(0,0,0),t}set needsUpdate(t){t===!0&&this.version++}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.images[this.uuid]!==void 0)return t.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let s;if(Array.isArray(n)){s=[];for(let r=0,a=n.length;r<a;r++)n[r].isDataTexture?s.push(dg(n[r].image)):s.push(dg(n[r]))}else s=dg(n);i.url=s}return e||(t.images[this.uuid]=i),i}}function dg(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap?vR.getDataURL(o):o.data?{data:Array.from(o.data),width:o.width,height:o.height,type:o.data.constructor.name}:(Ht("Texture: Unable to serialize Texture."),{})}let yR=0;const fg=new T;class Wn extends _c{constructor(t=Wn.DEFAULT_IMAGE,e=Wn.DEFAULT_MAPPING,i=Qi,n=Qi,s=Me,r=cr,a=tn,c=fs,l=Wn.DEFAULT_ANISOTROPY,h=tc){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:yR++}),this.uuid=Ar(),this.name="",this.source=new vy(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new tt(0,0),this.repeat=new tt(1,1),this.center=new tt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new de,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(fg).x}get height(){return this.source.getSize(fg).y}get depth(){return this.source.getSize(fg).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(i===void 0){Ht(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Ht(`Texture.setValues(): property '${e}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==jE)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case bc:t.x=t.x-Math.floor(t.x);break;case Qi:t.x=t.x<0?0:1;break;case wv:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case bc:t.y=t.y-Math.floor(t.y);break;case Qi:t.y=t.y<0?0:1;break;case wv:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}}Wn.DEFAULT_IMAGE=null;Wn.DEFAULT_MAPPING=jE;Wn.DEFAULT_ANISOTROPY=1;class Ie{static{Ie.prototype.isVector4=!0}constructor(t=0,e=0,i=0,n=1){this.x=t,this.y=e,this.z=i,this.w=n}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,n,s;const c=t.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],p=c[9],m=c[2],g=c[6],v=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(p-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(p+g)<.1&&Math.abs(l+f+v-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const w=(l+1)/2,y=(f+1)/2,x=(v+1)/2,b=(h+d)/4,E=(u+m)/4,S=(p+g)/4;return w>y&&w>x?w<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(w),n=b/i,s=E/i):y>x?y<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(y),i=b/n,s=S/n):x<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(x),i=E/s,n=S/s),this.set(i,n,s,e),this}let M=Math.sqrt((g-p)*(g-p)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(M)<.001&&(M=1),this.x=(g-p)/M,this.y=(u-m)/M,this.z=(d-h)/M,this.w=Math.acos((l+f+v-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=ge(this.x,t.x,e.x),this.y=ge(this.y,t.y,e.y),this.z=ge(this.z,t.z,e.z),this.w=ge(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=ge(this.x,t,e),this.y=ge(this.y,t,e),this.z=ge(this.z,t,e),this.w=ge(this.w,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(ge(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class wR extends _c{constructor(t=1,e=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Me,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=i.depth,this.scissor=new Ie(0,0,t,e),this.scissorTest=!1,this.viewport=new Ie(0,0,t,e),this.textures=[];const n={width:t,height:e,depth:i.depth},s=new Wn(n),r=i.count;for(let a=0;a<r;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(t={}){const e={minFilter:Me,generateMipmaps:!1,flipY:!1,internalFormat:null};t.mapping!==void 0&&(e.mapping=t.mapping),t.wrapS!==void 0&&(e.wrapS=t.wrapS),t.wrapT!==void 0&&(e.wrapT=t.wrapT),t.wrapR!==void 0&&(e.wrapR=t.wrapR),t.magFilter!==void 0&&(e.magFilter=t.magFilter),t.minFilter!==void 0&&(e.minFilter=t.minFilter),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.anisotropy!==void 0&&(e.anisotropy=t.anisotropy),t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),t.internalFormat!==void 0&&(e.internalFormat=t.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(e)}get texture(){return this.textures[0]}set texture(t){this.textures[0]=t}set depthTexture(t){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),t!==null&&(t.renderTarget=this),this._depthTexture=t}get depthTexture(){return this._depthTexture}setSize(t,e,i=1){if(this.width!==t||this.height!==e||this.depth!==i){this.width=t,this.height=e,this.depth=i;for(let n=0,s=this.textures.length;n<s;n++)this.textures[n].image.width=t,this.textures[n].image.height=e,this.textures[n].image.depth=i,this.textures[n].isData3DTexture!==!0&&(this.textures[n].isArrayTexture=this.textures[n].image.depth>1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,i=t.textures.length;e<i;e++){this.textures[e]=t.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;const n=Object.assign({},t.textures[e].image);this.textures[e].source=new vy(n)}return this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.resolveDepthBuffer=t.resolveDepthBuffer,this.resolveStencilBuffer=t.resolveStencilBuffer,t.depthTexture!==null&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this.multiview=t.multiview,this.useArrayDepthTexture=t.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Qe extends wR{constructor(t=1,e=1,i={}){super(t,e,i),this.isWebGLRenderTarget=!0}}class oA extends Wn{constructor(t=null,e=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=si,this.minFilter=si,this.wrapR=Qi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class cA extends Wn{constructor(t=null,e=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=si,this.minFilter=si,this.wrapR=Qi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Gt{static{Gt.prototype.isMatrix4=!0}constructor(t,e,i,n,s,r,a,c,l,h,u,d,f,p,m,g){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,m,g)}set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,m,g){const v=this.elements;return v[0]=t,v[4]=e,v[8]=i,v[12]=n,v[1]=s,v[5]=r,v[9]=a,v[13]=c,v[2]=l,v[6]=h,v[10]=u,v[14]=d,v[3]=f,v[7]=p,v[11]=m,v[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Gt().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return this.determinantAffine()===0?(t.set(1,0,0),e.set(0,1,0),i.set(0,0,1),this):(t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){if(t.determinantAffine()===0)return this.identity();const e=this.elements,i=t.elements,n=1/Ll.setFromMatrixColumn(t,0).length(),s=1/Ll.setFromMatrixColumn(t,1).length(),r=1/Ll.setFromMatrixColumn(t,2).length();return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=0,e[4]=i[4]*s,e[5]=i[5]*s,e[6]=i[6]*s,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,n=t.y,s=t.z,r=Math.cos(i),a=Math.sin(i),c=Math.cos(n),l=Math.sin(n),h=Math.cos(s),u=Math.sin(s);if(t.order==="XYZ"){const d=r*h,f=r*u,p=a*h,m=a*u;e[0]=c*h,e[4]=-c*u,e[8]=l,e[1]=f+p*l,e[5]=d-m*l,e[9]=-a*c,e[2]=m-d*l,e[6]=p+f*l,e[10]=r*c}else if(t.order==="YXZ"){const d=c*h,f=c*u,p=l*h,m=l*u;e[0]=d+m*a,e[4]=p*a-f,e[8]=r*l,e[1]=r*u,e[5]=r*h,e[9]=-a,e[2]=f*a-p,e[6]=m+d*a,e[10]=r*c}else if(t.order==="ZXY"){const d=c*h,f=c*u,p=l*h,m=l*u;e[0]=d-m*a,e[4]=-r*u,e[8]=p+f*a,e[1]=f+p*a,e[5]=r*h,e[9]=m-d*a,e[2]=-r*l,e[6]=a,e[10]=r*c}else if(t.order==="ZYX"){const d=r*h,f=r*u,p=a*h,m=a*u;e[0]=c*h,e[4]=p*l-f,e[8]=d*l+m,e[1]=c*u,e[5]=m*l+d,e[9]=f*l-p,e[2]=-l,e[6]=a*c,e[10]=r*c}else if(t.order==="YZX"){const d=r*c,f=r*l,p=a*c,m=a*l;e[0]=c*h,e[4]=m-d*u,e[8]=p*u+f,e[1]=u,e[5]=r*h,e[9]=-a*h,e[2]=-l*h,e[6]=f*u+p,e[10]=d-m*u}else if(t.order==="XZY"){const d=r*c,f=r*l,p=a*c,m=a*l;e[0]=c*h,e[4]=-u,e[8]=l*h,e[1]=d*u+m,e[5]=r*h,e[9]=f*u-p,e[2]=p*u-f,e[6]=a*h,e[10]=m*u+d}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(xR,t,bR)}lookAt(t,e,i){const n=this.elements;return Js.subVectors(t,e),Js.lengthSq()===0&&(Js.z=1),Js.normalize(),Oo.crossVectors(i,Js),Oo.lengthSq()===0&&(Math.abs(i.z)===1?Js.x+=1e-4:Js.z+=1e-4,Js.normalize(),Oo.crossVectors(i,Js)),Oo.normalize(),Bf.crossVectors(Js,Oo),n[0]=Oo.x,n[4]=Bf.x,n[8]=Js.x,n[1]=Oo.y,n[5]=Bf.y,n[9]=Js.y,n[2]=Oo.z,n[6]=Bf.z,n[10]=Js.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[4],c=i[8],l=i[12],h=i[1],u=i[5],d=i[9],f=i[13],p=i[2],m=i[6],g=i[10],v=i[14],M=i[3],w=i[7],y=i[11],x=i[15],b=n[0],E=n[4],S=n[8],A=n[12],_=n[1],I=n[5],D=n[9],O=n[13],P=n[2],N=n[6],k=n[10],B=n[14],W=n[3],Q=n[7],Z=n[11],nt=n[15];return s[0]=r*b+a*_+c*P+l*W,s[4]=r*E+a*I+c*N+l*Q,s[8]=r*S+a*D+c*k+l*Z,s[12]=r*A+a*O+c*B+l*nt,s[1]=h*b+u*_+d*P+f*W,s[5]=h*E+u*I+d*N+f*Q,s[9]=h*S+u*D+d*k+f*Z,s[13]=h*A+u*O+d*B+f*nt,s[2]=p*b+m*_+g*P+v*W,s[6]=p*E+m*I+g*N+v*Q,s[10]=p*S+m*D+g*k+v*Z,s[14]=p*A+m*O+g*B+v*nt,s[3]=M*b+w*_+y*P+x*W,s[7]=M*E+w*I+y*N+x*Q,s[11]=M*S+w*D+y*k+x*Z,s[15]=M*A+w*O+y*B+x*nt,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[12],r=t[1],a=t[5],c=t[9],l=t[13],h=t[2],u=t[6],d=t[10],f=t[14],p=t[3],m=t[7],g=t[11],v=t[15],M=c*f-l*d,w=a*f-l*u,y=a*d-c*u,x=r*f-l*h,b=r*d-c*h,E=r*u-a*h;return e*(m*M-g*w+v*y)-i*(p*M-g*x+v*b)+n*(p*w-m*x+v*E)-s*(p*y-m*b+g*E)}determinantAffine(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[1],r=t[5],a=t[9],c=t[2],l=t[6],h=t[10];return e*(r*h-a*l)-i*(s*h-a*c)+n*(s*l-r*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const n=this.elements;return t.isVector3?(n[12]=t.x,n[13]=t.y,n[14]=t.z):(n[12]=t,n[13]=e,n[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=t[9],d=t[10],f=t[11],p=t[12],m=t[13],g=t[14],v=t[15],M=e*a-i*r,w=e*c-n*r,y=e*l-s*r,x=i*c-n*a,b=i*l-s*a,E=n*l-s*c,S=h*m-u*p,A=h*g-d*p,_=h*v-f*p,I=u*g-d*m,D=u*v-f*m,O=d*v-f*g,P=M*O-w*D+y*I+x*_-b*A+E*S;if(P===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const N=1/P;return t[0]=(a*O-c*D+l*I)*N,t[1]=(n*D-i*O-s*I)*N,t[2]=(m*E-g*b+v*x)*N,t[3]=(d*b-u*E-f*x)*N,t[4]=(c*_-r*O-l*A)*N,t[5]=(e*O-n*_+s*A)*N,t[6]=(g*y-p*E-v*w)*N,t[7]=(h*E-d*y+f*w)*N,t[8]=(r*D-a*_+l*S)*N,t[9]=(i*_-e*D-s*S)*N,t[10]=(p*b-m*y+v*M)*N,t[11]=(u*y-h*b-f*M)*N,t[12]=(a*A-r*I-c*S)*N,t[13]=(e*I-i*A+n*S)*N,t[14]=(m*w-p*x-g*M)*N,t[15]=(h*x-u*w+d*M)*N,this}scale(t){const e=this.elements,i=t.x,n=t.y,s=t.z;return e[0]*=i,e[4]*=n,e[8]*=s,e[1]*=i,e[5]*=n,e[9]*=s,e[2]*=i,e[6]*=n,e[10]*=s,e[3]*=i,e[7]*=n,e[11]*=s,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],n=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,n))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,a=t.y,c=t.z,l=s*r,h=s*a;return this.set(l*r+i,l*a-n*c,l*c+n*a,0,l*a+n*c,h*a+i,h*c-n*r,0,l*c-n*a,h*c+n*r,s*c*c+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,n,s,r){return this.set(1,i,s,0,t,1,r,0,e,n,1,0,0,0,0,1),this}compose(t,e,i){const n=this.elements,s=e._x,r=e._y,a=e._z,c=e._w,l=s+s,h=r+r,u=a+a,d=s*l,f=s*h,p=s*u,m=r*h,g=r*u,v=a*u,M=c*l,w=c*h,y=c*u,x=i.x,b=i.y,E=i.z;return n[0]=(1-(m+v))*x,n[1]=(f+y)*x,n[2]=(p-w)*x,n[3]=0,n[4]=(f-y)*b,n[5]=(1-(d+v))*b,n[6]=(g+M)*b,n[7]=0,n[8]=(p+w)*E,n[9]=(g-M)*E,n[10]=(1-(d+m))*E,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this}decompose(t,e,i){const n=this.elements;t.x=n[12],t.y=n[13],t.z=n[14];const s=this.determinantAffine();if(s===0)return i.set(1,1,1),e.identity(),this;let r=Ll.set(n[0],n[1],n[2]).length();const a=Ll.set(n[4],n[5],n[6]).length(),c=Ll.set(n[8],n[9],n[10]).length();s<0&&(r=-r),Ir.copy(this);const l=1/r,h=1/a,u=1/c;return Ir.elements[0]*=l,Ir.elements[1]*=l,Ir.elements[2]*=l,Ir.elements[4]*=h,Ir.elements[5]*=h,Ir.elements[6]*=h,Ir.elements[8]*=u,Ir.elements[9]*=u,Ir.elements[10]*=u,e.setFromRotationMatrix(Ir),i.x=r,i.y=a,i.z=c,this}makePerspective(t,e,i,n,s,r,a=Ca,c=!1){const l=this.elements,h=2*s/(e-t),u=2*s/(i-n),d=(e+t)/(e-t),f=(i+n)/(i-n);let p,m;if(c)p=s/(r-s),m=r*s/(r-s);else if(a===Ca)p=-(r+s)/(r-s),m=-2*r*s/(r-s);else if(a===lf)p=-r/(r-s),m=-r*s/(r-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,i,n,s,r,a=Ca,c=!1){const l=this.elements,h=2/(e-t),u=2/(i-n),d=-(e+t)/(e-t),f=-(i+n)/(i-n);let p,m;if(c)p=1/(r-s),m=r/(r-s);else if(a===Ca)p=-2/(r-s),m=-(r+s)/(r-s);else if(a===lf)p=-1/(r-s),m=-s/(r-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=0,l[12]=d,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<16;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const Ll=new T,Ir=new Gt,xR=new T(0,0,0),bR=new T(1,1,1),Oo=new T,Bf=new T,Js=new T,Iw=new Gt,Dw=new es;class Yr{constructor(t=0,e=0,i=0,n=Yr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=n}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,n=this._order){return this._x=t,this._y=e,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const n=t.elements,s=n[0],r=n[4],a=n[8],c=n[1],l=n[5],h=n[9],u=n[2],d=n[6],f=n[10];switch(e){case"XYZ":this._y=Math.asin(ge(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-r,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-ge(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(ge(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-ge(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(ge(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-ge(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-h,f),this._y=0);break;default:Ht("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return Iw.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Iw,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return Dw.setFromEuler(this),this.setFromQuaternion(Dw,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Yr.DEFAULT_ORDER="XYZ";class My{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return(this.mask&t.mask)!==0}isEnabled(t){return(this.mask&(1<<t|0))!==0}}let SR=0;const Cw=new T,kl=new es,Wa=new Gt,Hf=new T,Cu=new T,ER=new T,AR=new es,Ow=new T(1,0,0),Pw=new T(0,1,0),Nw=new T(0,0,1),Lw={type:"added"},_R={type:"removed"},Fl={type:"childadded",child:null},pg={type:"childremoved",child:null};class Bi extends _c{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:SR++}),this.uuid=Ar(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Bi.DEFAULT_UP.clone();const t=new T,e=new Yr,i=new es,n=new T(1,1,1);function s(){i.setFromEuler(e,!1)}function r(){e.setFromQuaternion(i,void 0,!1)}e._onChange(s),i._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new Gt},normalMatrix:{value:new de}}),this.matrix=new Gt,this.matrixWorld=new Gt,this.matrixAutoUpdate=Bi.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new My,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return kl.setFromAxisAngle(t,e),this.quaternion.multiply(kl),this}rotateOnWorldAxis(t,e){return kl.setFromAxisAngle(t,e),this.quaternion.premultiply(kl),this}rotateX(t){return this.rotateOnAxis(Ow,t)}rotateY(t){return this.rotateOnAxis(Pw,t)}rotateZ(t){return this.rotateOnAxis(Nw,t)}translateOnAxis(t,e){return Cw.copy(t).applyQuaternion(this.quaternion),this.position.add(Cw.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Ow,t)}translateY(t){return this.translateOnAxis(Pw,t)}translateZ(t){return this.translateOnAxis(Nw,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(Wa.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?Hf.copy(t):Hf.set(t,e,i);const n=this.parent;this.updateWorldMatrix(!0,!1),Cu.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Wa.lookAt(Cu,Hf,this.up):Wa.lookAt(Hf,Cu,this.up),this.quaternion.setFromRotationMatrix(Wa),n&&(Wa.extractRotation(n.matrixWorld),kl.setFromRotationMatrix(Wa),this.quaternion.premultiply(kl.invert()))}add(t){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return t===this?(le("Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Lw),Fl.child=t,this.dispatchEvent(Fl),Fl.child=null):le("Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const e=this.children.indexOf(t);return e!==-1&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(_R),pg.child=t,this.dispatchEvent(pg),pg.child=null),this}removeFromParent(){const t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),Wa.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),Wa.multiply(t.parent.matrixWorld)),t.applyMatrix4(Wa),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Lw),Fl.child=t,this.dispatchEvent(Fl),Fl.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,n=this.children.length;i<n;i++){const r=this.children[i].getObjectByProperty(t,e);if(r!==void 0)return r}}getObjectsByProperty(t,e,i=[]){this[t]===e&&i.push(this);const n=this.children;for(let s=0,r=n.length;s<r;s++)n[s].getObjectsByProperty(t,e,i);return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Cu,t,ER),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Cu,AR,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;e!==null&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const t=this.pivot;if(t!==null){const e=t.x,i=t.y,n=t.z,s=this.matrix.elements;s[12]+=e-s[0]*e-s[4]*i-s[8]*n,s[13]+=i-s[1]*e-s[5]*i-s[9]*n,s[14]+=n-s[2]*e-s[6]*i-s[10]*n}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].updateMatrixWorld(t)}updateWorldMatrix(t,e,i=!1){const n=this.parent;if(t===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),e===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0,i)}}toJSON(t){const e=t===void 0||typeof t=="string",i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),this.static!==!1&&(n.static=this.static),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.pivot!==null&&(n.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(a=>({...a})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(t),n.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(t)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(t.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){const u=c[l];s(t.shapes,u)}else s(t.shapes,c)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(t.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(s(t.materials,this.material[c]));n.material=a}else n.material=s(t.materials,this.material);if(this.children.length>0){n.children=[];for(let a=0;a<this.children.length;a++)n.children.push(this.children[a].toJSON(t).object)}if(this.animations.length>0){n.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];n.animations.push(s(t.animations,c))}}if(e){const a=r(t.geometries),c=r(t.materials),l=r(t.textures),h=r(t.images),u=r(t.shapes),d=r(t.skeletons),f=r(t.animations),p=r(t.nodes);a.length>0&&(i.geometries=a),c.length>0&&(i.materials=c),l.length>0&&(i.textures=l),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=n,i;function r(a){const c=[];for(const l in a){const h=a[l];delete h.metadata,c.push(h)}return c}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let i=0;i<t.children.length;i++){const n=t.children[i];this.add(n.clone())}return this}}Bi.DEFAULT_UP=new T(0,1,0);Bi.DEFAULT_MATRIX_AUTO_UPDATE=!0;Bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Ke extends Bi{constructor(){super(),this.isGroup=!0,this.type="Group"}}const TR={type:"move"};class mg{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Ke,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Ke,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new T,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new T),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Ke,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new T,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new T,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,i){let n=null,s=null,r=null;const a=this._targetRay,c=this._grip,l=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(l&&t.hand){r=!0;for(const m of t.hand.values()){const g=e.getJointPose(m,i),v=this._getHandJoint(l,m);g!==null&&(v.matrix.fromArray(g.transform.matrix),v.matrix.decompose(v.position,v.rotation,v.scale),v.matrixWorldNeedsUpdate=!0,v.jointRadius=g.radius),v.visible=g!==null}const h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;l.inputState.pinching&&d>f+p?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&d<=f-p&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else c!==null&&t.gripSpace&&(s=e.getPose(t.gripSpace,i),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1,c.eventsEnabled&&c.dispatchEvent({type:"gripUpdated",data:t,target:this})));a!==null&&(n=e.getPose(t.targetRaySpace,i),n===null&&s!==null&&(n=s),n!==null&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(TR)))}return a!==null&&(a.visible=n!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=r!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){const i=new Ke;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}const lA={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Po={h:0,s:0,l:0},Gf={h:0,s:0,l:0};function gg(o,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+(t-o)*6*e:e<1/2?t:e<2/3?o+(t-o)*6*(2/3-e):o}class rt{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(e===void 0&&i===void 0){const n=t;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Bn){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,He.colorSpaceToWorking(this,e),this}setRGB(t,e,i,n=He.workingColorSpace){return this.r=t,this.g=e,this.b=i,He.colorSpaceToWorking(this,n),this}setHSL(t,e,i,n=He.workingColorSpace){if(t=gy(t,1),e=ge(e,0,1),i=ge(i,0,1),e===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,r=2*i-s;this.r=gg(r,s,t+1/3),this.g=gg(r,s,t),this.b=gg(r,s,t-1/3)}return He.colorSpaceToWorking(this,n),this}setStyle(t,e=Bn){function i(s){s!==void 0&&parseFloat(s)<1&&Ht("Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(t)){let s;const r=n[1],a=n[2];switch(r){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,e);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,e);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,e);break;default:Ht("Color: Unknown color model "+t)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const s=n[1],r=s.length;if(r===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,e);if(r===6)return this.setHex(parseInt(s,16),e);Ht("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Bn){const i=lA[t.toLowerCase()];return i!==void 0?this.setHex(i,e):Ht("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=wo(t.r),this.g=wo(t.g),this.b=wo(t.b),this}copyLinearToSRGB(t){return this.r=jh(t.r),this.g=jh(t.g),this.b=jh(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Bn){return He.workingToColorSpace(ss.copy(this),t),Math.round(ge(ss.r*255,0,255))*65536+Math.round(ge(ss.g*255,0,255))*256+Math.round(ge(ss.b*255,0,255))}getHexString(t=Bn){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=He.workingColorSpace){He.workingToColorSpace(ss.copy(this),e);const i=ss.r,n=ss.g,s=ss.b,r=Math.max(i,n,s),a=Math.min(i,n,s);let c,l;const h=(a+r)/2;if(a===r)c=0,l=0;else{const u=r-a;switch(l=h<=.5?u/(r+a):u/(2-r-a),r){case i:c=(n-s)/u+(n<s?6:0);break;case n:c=(s-i)/u+2;break;case s:c=(i-n)/u+4;break}c/=6}return t.h=c,t.s=l,t.l=h,t}getRGB(t,e=He.workingColorSpace){return He.workingToColorSpace(ss.copy(this),e),t.r=ss.r,t.g=ss.g,t.b=ss.b,t}getStyle(t=Bn){He.workingToColorSpace(ss.copy(this),t);const e=ss.r,i=ss.g,n=ss.b;return t!==Bn?`color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(t,e,i){return this.getHSL(Po),this.setHSL(Po.h+t,Po.s+e,Po.l+i)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,i){return this.r=t.r+(e.r-t.r)*i,this.g=t.g+(e.g-t.g)*i,this.b=t.b+(e.b-t.b)*i,this}lerpHSL(t,e){this.getHSL(Po),t.getHSL(Gf);const i=pd(Po.h,Gf.h,e),n=pd(Po.s,Gf.s,e),s=pd(Po.l,Gf.l,e);return this.setHSL(i,n,s),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,i=this.g,n=this.b,s=t.elements;return this.r=s[0]*e+s[3]*i+s[6]*n,this.g=s[1]*e+s[4]*i+s[7]*n,this.b=s[2]*e+s[5]*i+s[8]*n,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const ss=new rt;rt.NAMES=lA;class yy{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new rt(t),this.near=e,this.far=i}clone(){return new yy(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class hr extends Bi{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Yr,this.environmentIntensity=1,this.environmentRotation=new Yr,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const Dr=new T,Xa=new T,vg=new T,$a=new T,Ul=new T,zl=new T,kw=new T,Mg=new T,yg=new T,wg=new T,xg=new Ie,bg=new Ie,Sg=new Ie;class Hn{constructor(t=new T,e=new T,i=new T){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,n){n.subVectors(i,e),Dr.subVectors(t,e),n.cross(Dr);const s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(t,e,i,n,s){Dr.subVectors(n,e),Xa.subVectors(i,e),vg.subVectors(t,e);const r=Dr.dot(Dr),a=Dr.dot(Xa),c=Dr.dot(vg),l=Xa.dot(Xa),h=Xa.dot(vg),u=r*l-a*a;if(u===0)return s.set(0,0,0),null;const d=1/u,f=(l*c-a*h)*d,p=(r*h-a*c)*d;return s.set(1-f-p,p,f)}static containsPoint(t,e,i,n){return this.getBarycoord(t,e,i,n,$a)===null?!1:$a.x>=0&&$a.y>=0&&$a.x+$a.y<=1}static getInterpolation(t,e,i,n,s,r,a,c){return this.getBarycoord(t,e,i,n,$a)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,$a.x),c.addScaledVector(r,$a.y),c.addScaledVector(a,$a.z),c)}static getInterpolatedAttribute(t,e,i,n,s,r){return xg.setScalar(0),bg.setScalar(0),Sg.setScalar(0),xg.fromBufferAttribute(t,e),bg.fromBufferAttribute(t,i),Sg.fromBufferAttribute(t,n),r.setScalar(0),r.addScaledVector(xg,s.x),r.addScaledVector(bg,s.y),r.addScaledVector(Sg,s.z),r}static isFrontFacing(t,e,i,n){return Dr.subVectors(i,e),Xa.subVectors(t,e),Dr.cross(Xa).dot(n)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this}setFromAttributeAndIndices(t,e,i,n){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,n),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Dr.subVectors(this.c,this.b),Xa.subVectors(this.a,this.b),Dr.cross(Xa).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Hn.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Hn.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,n,s){return Hn.getInterpolation(t,this.a,this.b,this.c,e,i,n,s)}containsPoint(t){return Hn.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Hn.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,n=this.b,s=this.c;let r,a;Ul.subVectors(n,i),zl.subVectors(s,i),Mg.subVectors(t,i);const c=Ul.dot(Mg),l=zl.dot(Mg);if(c<=0&&l<=0)return e.copy(i);yg.subVectors(t,n);const h=Ul.dot(yg),u=zl.dot(yg);if(h>=0&&u<=h)return e.copy(n);const d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return r=c/(c-h),e.copy(i).addScaledVector(Ul,r);wg.subVectors(t,s);const f=Ul.dot(wg),p=zl.dot(wg);if(p>=0&&f<=p)return e.copy(s);const m=f*l-c*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(zl,a);const g=h*p-f*u;if(g<=0&&u-h>=0&&f-p>=0)return kw.subVectors(s,n),a=(u-h)/(u-h+(f-p)),e.copy(n).addScaledVector(kw,a);const v=1/(g+m+d);return r=m*v,a=d*v,e.copy(i).addScaledVector(Ul,r).addScaledVector(zl,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class Je{constructor(t=new T(1/0,1/0,1/0),e=new T(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(Cr.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(Cr.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=Cr.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const i=t.geometry;if(i!==void 0){const s=i.getAttribute("position");if(e===!0&&s!==void 0&&t.isInstancedMesh!==!0)for(let r=0,a=s.count;r<a;r++)t.isMesh===!0?t.getVertexPosition(r,Cr):Cr.fromBufferAttribute(s,r),Cr.applyMatrix4(t.matrixWorld),this.expandByPoint(Cr);else t.boundingBox!==void 0?(t.boundingBox===null&&t.computeBoundingBox(),Vf.copy(t.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Vf.copy(i.boundingBox)),Vf.applyMatrix4(t.matrixWorld),this.union(Vf)}const n=t.children;for(let s=0,r=n.length;s<r;s++)this.expandByObject(n[s],e);return this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,Cr),Cr.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Ou),Wf.subVectors(this.max,Ou),Bl.subVectors(t.a,Ou),Hl.subVectors(t.b,Ou),Gl.subVectors(t.c,Ou),No.subVectors(Hl,Bl),Lo.subVectors(Gl,Hl),Ic.subVectors(Bl,Gl);let e=[0,-No.z,No.y,0,-Lo.z,Lo.y,0,-Ic.z,Ic.y,No.z,0,-No.x,Lo.z,0,-Lo.x,Ic.z,0,-Ic.x,-No.y,No.x,0,-Lo.y,Lo.x,0,-Ic.y,Ic.x,0];return!Eg(e,Bl,Hl,Gl,Wf)||(e=[1,0,0,0,1,0,0,0,1],!Eg(e,Bl,Hl,Gl,Wf))?!1:(Xf.crossVectors(No,Lo),e=[Xf.x,Xf.y,Xf.z],Eg(e,Bl,Hl,Gl,Wf))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Cr).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(Cr).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Ya[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Ya[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Ya[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Ya[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Ya[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Ya[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Ya[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Ya[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Ya),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Ya=[new T,new T,new T,new T,new T,new T,new T,new T],Cr=new T,Vf=new Je,Bl=new T,Hl=new T,Gl=new T,No=new T,Lo=new T,Ic=new T,Ou=new T,Wf=new T,Xf=new T,Dc=new T;function Eg(o,t,e,i,n){for(let s=0,r=o.length-3;s<=r;s+=3){Dc.fromArray(o,s);const a=n.x*Math.abs(Dc.x)+n.y*Math.abs(Dc.y)+n.z*Math.abs(Dc.z),c=t.dot(Dc),l=e.dot(Dc),h=i.dot(Dc);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}const oo=RR();function RR(){const o=new ArrayBuffer(4),t=new Float32Array(o),e=new Uint32Array(o),i=new Uint32Array(512),n=new Uint32Array(512);for(let c=0;c<256;++c){const l=c-127;l<-27?(i[c]=0,i[c|256]=32768,n[c]=24,n[c|256]=24):l<-14?(i[c]=1024>>-l-14,i[c|256]=1024>>-l-14|32768,n[c]=-l-1,n[c|256]=-l-1):l<=15?(i[c]=l+15<<10,i[c|256]=l+15<<10|32768,n[c]=13,n[c|256]=13):l<128?(i[c]=31744,i[c|256]=64512,n[c]=24,n[c|256]=24):(i[c]=31744,i[c|256]=64512,n[c]=13,n[c|256]=13)}const s=new Uint32Array(2048),r=new Uint32Array(64),a=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,s[c]=l|h}for(let c=1024;c<2048;++c)s[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)r[c]=c<<23;r[31]=1199570944,r[32]=2147483648;for(let c=33;c<63;++c)r[c]=2147483648+(c-32<<23);r[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(a[c]=1024);return{floatView:t,uint32View:e,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:r,offsetTable:a}}function IR(o){Math.abs(o)>65504&&Ht("DataUtils.toHalfFloat(): Value out of range."),o=ge(o,-65504,65504),oo.floatView[0]=o;const t=oo.uint32View[0],e=t>>23&511;return oo.baseTable[e]+((t&8388607)>>oo.shiftTable[e])}function DR(o){const t=o>>10;return oo.uint32View[0]=oo.mantissaTable[oo.offsetTable[t]+(o&1023)]+oo.exponentTable[t],oo.floatView[0]}class Gn{static toHalfFloat(t){return IR(t)}static fromHalfFloat(t){return DR(t)}}const dn=new T,$f=new tt;let CR=0;class ye extends _c{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:CR++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=i,this.usage=jv,this.updateRanges=[],this.gpuType=ts,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let n=0,s=this.itemSize;n<s;n++)this.array[t+n]=e.array[i+n];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(this.itemSize===2)for(let e=0,i=this.count;e<i;e++)$f.fromBufferAttribute(this,e),$f.applyMatrix3(t),this.setXY(e,$f.x,$f.y);else if(this.itemSize===3)for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.applyMatrix3(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.applyMatrix4(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.applyNormalMatrix(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.transformDirection(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=Gr(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=di(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=Gr(e,this.array)),e}setX(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=Gr(e,this.array)),e}setY(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=Gr(e,this.array)),e}setZ(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=Gr(e,this.array)),e}setW(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=di(e,this.array),i=di(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,n){return t*=this.itemSize,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t*=this.itemSize,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array),s=di(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this.array[t+3]=s,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(t.name=this.name),this.usage!==jv&&(t.usage=this.usage),t}dispose(){this.dispatchEvent({type:"dispose"})}}class hA extends ye{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class wy extends ye{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class pe extends ye{constructor(t,e,i){super(new Float32Array(t),e,i)}}const OR=new Je,Pu=new T,Ag=new T;class Tr{constructor(t=new T,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;e!==void 0?i.copy(e):OR.setFromPoints(t).getCenter(i);let n=0;for(let s=0,r=t.length;s<r;s++)n=Math.max(n,i.distanceToSquared(t[s]));return this.radius=Math.sqrt(n),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Pu.subVectors(t,this.center);const e=Pu.lengthSq();if(e>this.radius*this.radius){const i=Math.sqrt(e),n=(i-this.radius)*.5;this.center.addScaledVector(Pu,n/i),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Ag.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Pu.copy(t.center).add(Ag)),this.expandByPoint(Pu.copy(t.center).sub(Ag))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let PR=0;const fr=new Gt,_g=new Bi,Vl=new T,js=new Je,Nu=new Je,Nn=new T;class be extends _c{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:PR++}),this.uuid=Ar(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(q4(t)?wy:hA)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new de().getNormalMatrix(t);i.applyNormalMatrix(s),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(t),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return fr.makeRotationFromQuaternion(t),this.applyMatrix4(fr),this}rotateX(t){return fr.makeRotationX(t),this.applyMatrix4(fr),this}rotateY(t){return fr.makeRotationY(t),this.applyMatrix4(fr),this}rotateZ(t){return fr.makeRotationZ(t),this.applyMatrix4(fr),this}translate(t,e,i){return fr.makeTranslation(t,e,i),this.applyMatrix4(fr),this}scale(t,e,i){return fr.makeScale(t,e,i),this.applyMatrix4(fr),this}lookAt(t){return _g.lookAt(t),_g.updateMatrix(),this.applyMatrix4(_g.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Vl).negate(),this.translate(Vl.x,Vl.y,Vl.z),this}setFromPoints(t){const e=this.getAttribute("position");if(e===void 0){const i=[];for(let n=0,s=t.length;n<s;n++){const r=t[n];i.push(r.x,r.y,r.z||0)}this.setAttribute("position",new pe(i,3))}else{const i=Math.min(t.length,e.count);for(let n=0;n<i;n++){const s=t[n];e.setXYZ(n,s.x,s.y,s.z||0)}t.length>e.count&&Ht("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Je);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){le("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new T(-1/0,-1/0,-1/0),new T(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let i=0,n=e.length;i<n;i++){const s=e[i];js.setFromBufferAttribute(s),this.morphTargetsRelative?(Nn.addVectors(this.boundingBox.min,js.min),this.boundingBox.expandByPoint(Nn),Nn.addVectors(this.boundingBox.max,js.max),this.boundingBox.expandByPoint(Nn)):(this.boundingBox.expandByPoint(js.min),this.boundingBox.expandByPoint(js.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&le('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Tr);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){le("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new T,1/0);return}if(t){const i=this.boundingSphere.center;if(js.setFromBufferAttribute(t),e)for(let s=0,r=e.length;s<r;s++){const a=e[s];Nu.setFromBufferAttribute(a),this.morphTargetsRelative?(Nn.addVectors(js.min,Nu.min),js.expandByPoint(Nn),Nn.addVectors(js.max,Nu.max),js.expandByPoint(Nn)):(js.expandByPoint(Nu.min),js.expandByPoint(Nu.max))}js.getCenter(i);let n=0;for(let s=0,r=t.count;s<r;s++)Nn.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(Nn));if(e)for(let s=0,r=e.length;s<r;s++){const a=e[s],c=this.morphTargetsRelative;for(let l=0,h=a.count;l<h;l++)Nn.fromBufferAttribute(a,l),c&&(Vl.fromBufferAttribute(t,l),Nn.add(Vl)),n=Math.max(n,i.distanceToSquared(Nn))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&le('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(t===null||e.position===void 0||e.normal===void 0||e.uv===void 0){le("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.position,n=e.normal,s=e.uv;let r=this.getAttribute("tangent");(r===void 0||r.count!==i.count)&&(r=new ye(new Float32Array(4*i.count),4),this.setAttribute("tangent",r));const a=[],c=[];for(let S=0;S<i.count;S++)a[S]=new T,c[S]=new T;const l=new T,h=new T,u=new T,d=new tt,f=new tt,p=new tt,m=new T,g=new T;function v(S,A,_){l.fromBufferAttribute(i,S),h.fromBufferAttribute(i,A),u.fromBufferAttribute(i,_),d.fromBufferAttribute(s,S),f.fromBufferAttribute(s,A),p.fromBufferAttribute(s,_),h.sub(l),u.sub(l),f.sub(d),p.sub(d);const I=1/(f.x*p.y-p.x*f.y);isFinite(I)&&(m.copy(h).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(I),g.copy(u).multiplyScalar(f.x).addScaledVector(h,-p.x).multiplyScalar(I),a[S].add(m),a[A].add(m),a[_].add(m),c[S].add(g),c[A].add(g),c[_].add(g))}let M=this.groups;M.length===0&&(M=[{start:0,count:t.count}]);for(let S=0,A=M.length;S<A;++S){const _=M[S],I=_.start,D=_.count;for(let O=I,P=I+D;O<P;O+=3)v(t.getX(O+0),t.getX(O+1),t.getX(O+2))}const w=new T,y=new T,x=new T,b=new T;function E(S){x.fromBufferAttribute(n,S),b.copy(x);const A=a[S];w.copy(A),w.sub(x.multiplyScalar(x.dot(A))).normalize(),y.crossVectors(b,A);const I=y.dot(c[S])<0?-1:1;r.setXYZW(S,w.x,w.y,w.z,I)}for(let S=0,A=M.length;S<A;++S){const _=M[S],I=_.start,D=_.count;for(let O=I,P=I+D;O<P;O+=3)E(t.getX(O+0)),E(t.getX(O+1)),E(t.getX(O+2))}this._transformed=!0}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(e!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==e.count)i=new ye(new Float32Array(e.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);const n=new T,s=new T,r=new T,a=new T,c=new T,l=new T,h=new T,u=new T;if(t)for(let d=0,f=t.count;d<f;d+=3){const p=t.getX(d+0),m=t.getX(d+1),g=t.getX(d+2);n.fromBufferAttribute(e,p),s.fromBufferAttribute(e,m),r.fromBufferAttribute(e,g),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),a.fromBufferAttribute(i,p),c.fromBufferAttribute(i,m),l.fromBufferAttribute(i,g),a.add(h),c.add(h),l.add(h),i.setXYZ(p,a.x,a.y,a.z),i.setXYZ(m,c.x,c.y,c.z),i.setXYZ(g,l.x,l.y,l.z)}else for(let d=0,f=e.count;d<f;d+=3)n.fromBufferAttribute(e,d+0),s.fromBufferAttribute(e,d+1),r.fromBufferAttribute(e,d+2),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)Nn.fromBufferAttribute(t,e),Nn.normalize(),t.setXYZ(e,Nn.x,Nn.y,Nn.z)}toNonIndexed(){function t(a,c){const l=a.array,h=a.itemSize,u=a.normalized,d=new l.constructor(c.length*h);let f=0,p=0;for(let m=0,g=c.length;m<g;m++){a.isInterleavedBufferAttribute?f=c[m]*a.data.stride+a.offset:f=c[m]*h;for(let v=0;v<h;v++)d[p++]=l[f++]}return new ye(d,h,u)}if(this.index===null)return Ht("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new be,i=this.index.array,n=this.attributes;for(const a in n){const c=n[a],l=t(c,i);e.setAttribute(a,l)}const s=this.morphAttributes;for(const a in s){const c=[],l=s[a];for(let h=0,u=l.length;h<u;h++){const d=l[h],f=t(d,i);c.push(f)}e.morphAttributes[a]=c}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,c=r.length;a<c;a++){const l=r[a];e.addGroup(l.start,l.count,l.materialIndex)}return e}toJSON(){const t={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(t[l]=c[l]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const c in i){const l=i[c];t.data.attributes[c]=l.toJSON(t.data)}const n={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){const f=l[u];h.push(f.toJSON(t.data))}h.length>0&&(n[c]=h,s=!0)}s&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;i!==null&&this.setIndex(i.clone());const n=t.attributes;for(const l in n){const h=n[l];this.setAttribute(l,h.clone(e))}const s=t.morphAttributes;for(const l in s){const h=[],u=s[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(e));this.morphAttributes[l]=h}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let l=0,h=r.length;l<h;l++){const u=r[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=t.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=t.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this._transformed=t._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class uA{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=t!==void 0?t.length/e:0,this.usage=jv,this.updateRanges=[],this.version=0,this.uuid=Ar()}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let n=0,s=this.stride;n<s;n++)this.array[t+n]=e.array[i+n];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ar()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(e,this.stride);return i.setUsage(this.usage),i}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ar()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Ms=new T;class $0{constructor(t,e,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=t,this.itemSize=e,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,i=this.data.count;e<i;e++)Ms.fromBufferAttribute(this,e),Ms.applyMatrix4(t),this.setXYZ(e,Ms.x,Ms.y,Ms.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)Ms.fromBufferAttribute(this,e),Ms.applyNormalMatrix(t),this.setXYZ(e,Ms.x,Ms.y,Ms.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)Ms.fromBufferAttribute(this,e),Ms.transformDirection(t),this.setXYZ(e,Ms.x,Ms.y,Ms.z);return this}getComponent(t,e){let i=this.array[t*this.data.stride+this.offset+e];return this.normalized&&(i=Gr(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=di(i,this.array)),this.data.array[t*this.data.stride+this.offset+e]=i,this}setX(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){let e=this.data.array[t*this.data.stride+this.offset];return this.normalized&&(e=Gr(e,this.array)),e}getY(t){let e=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(e=Gr(e,this.array)),e}getZ(t){let e=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(e=Gr(e,this.array)),e}getW(t){let e=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(e=Gr(e,this.array)),e}setXY(t,e,i){return t=t*this.data.stride+this.offset,this.normalized&&(e=di(e,this.array),i=di(i,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this}setXYZ(t,e,i,n){return t=t*this.data.stride+this.offset,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t=t*this.data.stride+this.offset,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array),s=di(s,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this.data.array[t+3]=s,this}clone(t){if(t===void 0){X0("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return new ye(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new $0(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(t===void 0){X0("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let NR=0;class Ga extends _c{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:NR++}),this.uuid=Ar(),this.name="",this.type="Material",this.blending=Mc,this.side=Ba,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=k0,this.blendDst=af,this.blendEquation=ao,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new rt(0,0,0),this.blendAlpha=0,this.depthFunc=fu,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Sw,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Pl,this.stencilZFail=Pl,this.stencilZPass=Pl,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(const e in t){const i=t[e];if(i===void 0){Ht(`Material: parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Ht(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector2&&i&&i.isVector2||n&&n.isEuler&&i&&i.isEuler||n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Mc&&(i.blending=this.blending),this.side!==Ba&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==k0&&(i.blendSrc=this.blendSrc),this.blendDst!==af&&(i.blendDst=this.blendDst),this.blendEquation!==ao&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==fu&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Sw&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Pl&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Pl&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Pl&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(s){const r=[];for(const a in s){const c=s[a];delete c.metadata,r.push(c)}return r}if(e){const s=n(t.textures),r=n(t.images);s.length>0&&(i.textures=s),r.length>0&&(i.images=r)}return i}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new rt().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let i=t.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new tt().fromArray(i)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new tt().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(e!==null){const n=e.length;i=new Array(n);for(let s=0;s!==n;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}}class c0 extends Ga{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new rt(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}let Wl;const Lu=new T,Xl=new T,$l=new T,Yl=new tt,ku=new tt,dA=new Gt,Yf=new T,Fu=new T,Kf=new T,Fw=new tt,Tg=new tt,Uw=new tt;class Uu extends Bi{constructor(t=new c0){if(super(),this.isSprite=!0,this.type="Sprite",Wl===void 0){Wl=new be;const e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new uA(e,5);Wl.setIndex([0,1,2,0,2,3]),Wl.setAttribute("position",new $0(i,3,0,!1)),Wl.setAttribute("uv",new $0(i,2,3,!1))}this.geometry=Wl,this.material=t,this.center=new tt(.5,.5),this.count=1}raycast(t,e){t.camera===null&&le('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Xl.setFromMatrixScale(this.matrixWorld),dA.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),$l.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Xl.multiplyScalar(-$l.z);const i=this.material.rotation;let n,s;i!==0&&(s=Math.cos(i),n=Math.sin(i));const r=this.center;qf(Yf.set(-.5,-.5,0),$l,r,Xl,n,s),qf(Fu.set(.5,-.5,0),$l,r,Xl,n,s),qf(Kf.set(.5,.5,0),$l,r,Xl,n,s),Fw.set(0,0),Tg.set(1,0),Uw.set(1,1);let a=t.ray.intersectTriangle(Yf,Fu,Kf,!1,Lu);if(a===null&&(qf(Fu.set(-.5,.5,0),$l,r,Xl,n,s),Tg.set(0,1),a=t.ray.intersectTriangle(Yf,Kf,Fu,!1,Lu),a===null))return;const c=t.ray.origin.distanceTo(Lu);c<t.near||c>t.far||e.push({distance:c,point:Lu.clone(),uv:Hn.getInterpolation(Lu,Yf,Fu,Kf,Fw,Tg,Uw,new tt),face:null,object:this})}copy(t,e){return super.copy(t,e),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}}function qf(o,t,e,i,n,s){Yl.subVectors(o,e).addScalar(.5).multiply(i),n!==void 0?(ku.x=s*Yl.x-n*Yl.y,ku.y=n*Yl.x+s*Yl.y):ku.copy(Yl),o.copy(t),o.x+=ku.x,o.y+=ku.y,o.applyMatrix4(dA)}const Ka=new T,Rg=new T,Zf=new T,ko=new T,Ig=new T,Jf=new T,Dg=new T;class El{constructor(t=new T,e=new T(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Ka)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Ka.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Ka.copy(this.origin).addScaledVector(this.direction,e),Ka.distanceToSquared(t))}distanceSqToSegment(t,e,i,n){Rg.copy(t).add(e).multiplyScalar(.5),Zf.copy(e).sub(t).normalize(),ko.copy(this.origin).sub(Rg);const s=t.distanceTo(e)*.5,r=-this.direction.dot(Zf),a=ko.dot(this.direction),c=-ko.dot(Zf),l=ko.lengthSq(),h=Math.abs(1-r*r);let u,d,f,p;if(h>0)if(u=r*c-a,d=r*a-c,p=s*h,u>=0)if(d>=-p)if(d<=p){const m=1/h;u*=m,d*=m,f=u*(u+r*d+2*a)+d*(r*u+d+2*c)+l}else d=s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d=-s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d<=-p?(u=Math.max(0,-(-r*s+a)),d=u>0?-s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l):d<=p?(u=0,d=Math.min(Math.max(-s,-c),s),f=d*(d+2*c)+l):(u=Math.max(0,-(r*s+a)),d=u>0?s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l);else d=r>0?-s:s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(Rg).addScaledVector(Zf,d),f}intersectSphere(t,e){Ka.subVectors(t.center,this.origin);const i=Ka.dot(this.direction),n=Ka.dot(Ka)-i*i,s=t.radius*t.radius;if(n>s)return null;const r=Math.sqrt(s-n),a=i-r,c=i+r;return c<0?null:a<0?this.at(c,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return i===null?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,n,s,r,a,c;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(i=(t.min.x-d.x)*l,n=(t.max.x-d.x)*l):(i=(t.max.x-d.x)*l,n=(t.min.x-d.x)*l),h>=0?(s=(t.min.y-d.y)*h,r=(t.max.y-d.y)*h):(s=(t.max.y-d.y)*h,r=(t.min.y-d.y)*h),i>r||s>n||((s>i||isNaN(i))&&(i=s),(r<n||isNaN(n))&&(n=r),u>=0?(a=(t.min.z-d.z)*u,c=(t.max.z-d.z)*u):(a=(t.max.z-d.z)*u,c=(t.min.z-d.z)*u),i>c||a>n)||((a>i||i!==i)&&(i=a),(c<n||n!==n)&&(n=c),n<0)?null:this.at(i>=0?i:n,e)}intersectsBox(t){return this.intersectBox(t,Ka)!==null}intersectTriangle(t,e,i,n,s){Ig.subVectors(e,t),Jf.subVectors(i,t),Dg.crossVectors(Ig,Jf);let r=this.direction.dot(Dg),a;if(r>0){if(n)return null;a=1}else if(r<0)a=-1,r=-r;else return null;ko.subVectors(this.origin,t);const c=a*this.direction.dot(Jf.crossVectors(ko,Jf));if(c<0)return null;const l=a*this.direction.dot(Ig.cross(ko));if(l<0||c+l>r)return null;const h=-a*ko.dot(Dg);return h<0?null:this.at(h/r,s)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Is extends Ga{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new rt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yr,this.combine=ay,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const zw=new Gt,Cc=new El,jf=new Tr,Bw=new T,Qf=new T,tp=new T,ep=new T,Cg=new T,ip=new T,Hw=new T,np=new T;class yt extends Bi{constructor(t=new be,e=new Is){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}getVertexPosition(t,e){const i=this.geometry,n=i.attributes.position,s=i.morphAttributes.position,r=i.morphTargetsRelative;e.fromBufferAttribute(n,t);const a=this.morphTargetInfluences;if(s&&a){ip.set(0,0,0);for(let c=0,l=s.length;c<l;c++){const h=a[c],u=s[c];h!==0&&(Cg.fromBufferAttribute(u,t),r?ip.addScaledVector(Cg,h):ip.addScaledVector(Cg.sub(e),h))}e.add(ip)}return e}raycast(t,e){const i=this.geometry,n=this.material,s=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),jf.copy(i.boundingSphere),jf.applyMatrix4(s),Cc.copy(t.ray).recast(t.near),!(jf.containsPoint(Cc.origin)===!1&&(Cc.intersectSphere(jf,Bw)===null||Cc.origin.distanceToSquared(Bw)>(t.far-t.near)**2))&&(zw.copy(s).invert(),Cc.copy(t.ray).applyMatrix4(zw),!(i.boundingBox!==null&&Cc.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(t,e,Cc)))}_computeIntersections(t,e,i){let n;const s=this.geometry,r=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,f=s.drawRange;if(a!==null)if(Array.isArray(r))for(let p=0,m=d.length;p<m;p++){const g=d[p],v=r[g.materialIndex],M=Math.max(g.start,f.start),w=Math.min(a.count,Math.min(g.start+g.count,f.start+f.count));for(let y=M,x=w;y<x;y+=3){const b=a.getX(y),E=a.getX(y+1),S=a.getX(y+2);n=sp(this,v,t,i,l,h,u,b,E,S),n&&(n.faceIndex=Math.floor(y/3),n.face.materialIndex=g.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),m=Math.min(a.count,f.start+f.count);for(let g=p,v=m;g<v;g+=3){const M=a.getX(g),w=a.getX(g+1),y=a.getX(g+2);n=sp(this,r,t,i,l,h,u,M,w,y),n&&(n.faceIndex=Math.floor(g/3),e.push(n))}}else if(c!==void 0)if(Array.isArray(r))for(let p=0,m=d.length;p<m;p++){const g=d[p],v=r[g.materialIndex],M=Math.max(g.start,f.start),w=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let y=M,x=w;y<x;y+=3){const b=y,E=y+1,S=y+2;n=sp(this,v,t,i,l,h,u,b,E,S),n&&(n.faceIndex=Math.floor(y/3),n.face.materialIndex=g.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),m=Math.min(c.count,f.start+f.count);for(let g=p,v=m;g<v;g+=3){const M=g,w=g+1,y=g+2;n=sp(this,r,t,i,l,h,u,M,w,y),n&&(n.faceIndex=Math.floor(g/3),e.push(n))}}}}function LR(o,t,e,i,n,s,r,a){let c;if(t.side===zi?c=i.intersectTriangle(r,s,n,!0,a):c=i.intersectTriangle(n,s,r,t.side===Ba,a),c===null)return null;np.copy(a),np.applyMatrix4(o.matrixWorld);const l=e.ray.origin.distanceTo(np);return l<e.near||l>e.far?null:{distance:l,point:np.clone(),object:o}}function sp(o,t,e,i,n,s,r,a,c,l){o.getVertexPosition(a,Qf),o.getVertexPosition(c,tp),o.getVertexPosition(l,ep);const h=LR(o,t,e,i,Qf,tp,ep,Hw);if(h){const u=new T;Hn.getBarycoord(Hw,Qf,tp,ep,u),n&&(h.uv=Hn.getInterpolatedAttribute(n,a,c,l,u,new tt)),s&&(h.uv1=Hn.getInterpolatedAttribute(s,a,c,l,u,new tt)),r&&(h.normal=Hn.getInterpolatedAttribute(r,a,c,l,u,new T),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const d={a,b:c,c:l,normal:new T,materialIndex:0};Hn.getNormal(Qf,tp,ep,d.normal),h.face=d,h.barycoord=u}return h}const zu=new Ie,Gw=new Ie,Vw=new Ie,kR=new Ie,Ww=new Gt,rp=new T,Og=new Tr,Xw=new Gt,Pg=new El;class ik extends yt{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=xw,this.bindMatrix=new Gt,this.bindMatrixInverse=new Gt,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;this.boundingBox===null&&(this.boundingBox=new Je),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,rp),this.boundingBox.expandByPoint(rp)}computeBoundingSphere(){const t=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Tr),this.boundingSphere.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,rp),this.boundingSphere.expandByPoint(rp)}copy(t,e){return super.copy(t,e),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}raycast(t,e){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Og.copy(this.boundingSphere),Og.applyMatrix4(n),t.ray.intersectsSphere(Og)!==!1&&(Xw.copy(n).invert(),Pg.copy(t.ray).applyMatrix4(Xw),!(this.boundingBox!==null&&Pg.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(t,e,Pg)))}getVertexPosition(t,e){return super.getVertexPosition(t,e),this.applyBoneTransform(t,e),e}bind(t,e){this.skeleton=t,e===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new Ie,e=this.geometry.attributes.skinWeight;for(let i=0,n=e.count;i<n;i++){t.fromBufferAttribute(e,i);const s=1/t.manhattanLength();s!==1/0?t.multiplyScalar(s):t.set(1,0,0,0),e.setXYZW(i,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.bindMode===xw?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===k4?this.bindMatrixInverse.copy(this.bindMatrix).invert():Ht("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(t,e){const i=this.skeleton,n=this.geometry;Gw.fromBufferAttribute(n.attributes.skinIndex,t),Vw.fromBufferAttribute(n.attributes.skinWeight,t),e.isVector4?(zu.copy(e),e.set(0,0,0,0)):(zu.set(...e,1),e.set(0,0,0)),zu.applyMatrix4(this.bindMatrix);for(let s=0;s<4;s++){const r=Vw.getComponent(s);if(r!==0){const a=Gw.getComponent(s);Ww.multiplyMatrices(i.bones[a].matrixWorld,i.boneInverses[a]),e.addScaledVector(kR.copy(zu).applyMatrix4(Ww),r)}}return e.isVector4&&(e.w=zu.w),e.applyMatrix4(this.bindMatrixInverse)}}class FR extends Bi{constructor(){super(),this.isBone=!0,this.type="Bone"}}class Ds extends Wn{constructor(t=null,e=1,i=1,n,s,r,a,c,l=si,h=si,u,d){super(null,r,a,c,l,h,n,s,u,d),this.isDataTexture=!0,this.image={data:t,width:e,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const $w=new Gt,UR=new Gt;class fA{constructor(t=[],e=[]){this.uuid=Ar(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(t.length*16),e.length===0)this.calculateInverses();else if(t.length!==e.length){Ht("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new Gt)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const i=new Gt;this.bones[t]&&i.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&i.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const t=this.bones,e=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,r=t.length;s<r;s++){const a=t[s]?t[s].matrixWorld:UR;$w.multiplyMatrices(a,e[s]),$w.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new fA(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(this.bones.length*4);t=Math.ceil(t/4)*4,t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const i=new Ds(e,t,t,tn,ts);return i.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=i,this}getBoneByName(t){for(let e=0,i=this.bones.length;e<i;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let i=0,n=t.bones.length;i<n;i++){const s=t.bones[i];let r=e[s];r===void 0&&(Ht("Skeleton: No bone found with UUID:",s),r=new FR),this.bones.push(r),this.boneInverses.push(new Gt().fromArray(t.boneInverses[i]))}return this.init(),this}toJSON(){const t={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,i=this.boneInverses;for(let n=0,s=e.length;n<s;n++){const r=e[n];t.bones.push(r.uuid);const a=i[n];t.boneInverses.push(a.toArray())}return t}}class Yw extends ye{constructor(t,e,i,n=1){super(t,e,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}const Kl=new Gt,Kw=new Gt,ap=[],qw=new Je,zR=new Gt,Bu=new yt,Hu=new Tr;class nk extends yt{constructor(t,e,i){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new Yw(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,zR)}computeBoundingBox(){const t=this.geometry,e=this.count;this.boundingBox===null&&(this.boundingBox=new Je),t.boundingBox===null&&t.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,Kl),qw.copy(t.boundingBox).applyMatrix4(Kl),this.boundingBox.union(qw)}computeBoundingSphere(){const t=this.geometry,e=this.count;this.boundingSphere===null&&(this.boundingSphere=new Tr),t.boundingSphere===null&&t.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,Kl),Hu.copy(t.boundingSphere).applyMatrix4(Kl),this.boundingSphere.union(Hu)}copy(t,e){return super.copy(t,e),this.instanceMatrix.copy(t.instanceMatrix),t.morphTexture!==null&&(this.morphTexture=t.morphTexture.clone()),t.instanceColor!==null&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}getColorAt(t,e){return this.instanceColor===null?e.setRGB(1,1,1):e.fromArray(this.instanceColor.array,t*3)}getMatrixAt(t,e){return e.fromArray(this.instanceMatrix.array,t*16)}getMorphAt(t,e){const i=e.morphTargetInfluences,n=this.morphTexture.source.data.data,s=i.length+1,r=t*s+1;for(let a=0;a<i.length;a++)i[a]=n[r+a]}raycast(t,e){const i=this.matrixWorld,n=this.count;if(Bu.geometry=this.geometry,Bu.material=this.material,Bu.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Hu.copy(this.boundingSphere),Hu.applyMatrix4(i),t.ray.intersectsSphere(Hu)!==!1))for(let s=0;s<n;s++){this.getMatrixAt(s,Kl),Kw.multiplyMatrices(i,Kl),Bu.matrixWorld=Kw,Bu.raycast(t,ap);for(let r=0,a=ap.length;r<a;r++){const c=ap[r];c.instanceId=s,c.object=this,e.push(c)}ap.length=0}}setColorAt(t,e){return this.instanceColor===null&&(this.instanceColor=new Yw(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),e.toArray(this.instanceColor.array,t*3),this}setMatrixAt(t,e){return e.toArray(this.instanceMatrix.array,t*16),this}setMorphAt(t,e){const i=e.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new Ds(new Float32Array(n*this.count),n,this.count,mu,ts));const s=this.morphTexture.source.data.data;let r=0;for(let l=0;l<i.length;l++)r+=i[l];const a=this.geometry.morphTargetsRelative?1:1-r,c=n*t;return s[c]=a,s.set(i,c+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const Ng=new T,BR=new T,HR=new de;class Hr{constructor(t=new T(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,n){return this.normal.set(t,e,i),this.constant=n,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const n=Ng.subVectors(i,e).cross(BR.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(n,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e,i=!0){const n=t.delta(Ng),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/s;return i===!0&&(r<0||r>1)?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||HR.getNormalMatrix(t),n=this.coplanarPoint(Ng).applyMatrix4(t),s=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(s),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Oc=new Tr,GR=new tt(.5,.5),op=new T;class Cm{constructor(t=new Hr,e=new Hr,i=new Hr,n=new Hr,s=new Hr,r=new Hr){this.planes=[t,e,i,n,s,r]}set(t,e,i,n,s,r){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(n),a[4].copy(s),a[5].copy(r),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=Ca,i=!1){const n=this.planes,s=t.elements,r=s[0],a=s[1],c=s[2],l=s[3],h=s[4],u=s[5],d=s[6],f=s[7],p=s[8],m=s[9],g=s[10],v=s[11],M=s[12],w=s[13],y=s[14],x=s[15];if(n[0].setComponents(l-r,f-h,v-p,x-M).normalize(),n[1].setComponents(l+r,f+h,v+p,x+M).normalize(),n[2].setComponents(l+a,f+u,v+m,x+w).normalize(),n[3].setComponents(l-a,f-u,v-m,x-w).normalize(),i)n[4].setComponents(c,d,g,y).normalize(),n[5].setComponents(l-c,f-d,v-g,x-y).normalize();else if(n[4].setComponents(l-c,f-d,v-g,x-y).normalize(),e===Ca)n[5].setComponents(l+c,f+d,v+g,x+y).normalize();else if(e===lf)n[5].setComponents(c,d,g,y).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),Oc.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Oc.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(Oc)}intersectsSprite(t){Oc.center.set(0,0,0);const e=GR.distanceTo(t.center);return Oc.radius=.7071067811865476+e,Oc.applyMatrix4(t.matrixWorld),this.intersectsSphere(Oc)}intersectsSphere(t){const e=this.planes,i=t.center,n=-t.radius;for(let s=0;s<6;s++)if(e[s].distanceToPoint(i)<n)return!1;return!0}intersectsBox(t){const e=this.planes;for(let i=0;i<6;i++){const n=e[i];if(op.x=n.normal.x>0?t.max.x:t.min.x,op.y=n.normal.y>0?t.max.y:t.min.y,op.z=n.normal.z>0?t.max.z:t.min.z,n.distanceToPoint(op)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class VR extends Ga{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new rt(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}}const Y0=new T,K0=new T,Zw=new Gt,Gu=new El,cp=new Tr,Lg=new T,Jw=new T;class pA extends Bi{constructor(t=new be,e=new VR){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[0];for(let n=1,s=e.count;n<s;n++)Y0.fromBufferAttribute(e,n-1),K0.fromBufferAttribute(e,n),i[n]=i[n-1],i[n]+=Y0.distanceTo(K0);t.setAttribute("lineDistance",new pe(i,1))}else Ht("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Line.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),cp.copy(i.boundingSphere),cp.applyMatrix4(n),cp.radius+=s,t.ray.intersectsSphere(cp)===!1)return;Zw.copy(n).invert(),Gu.copy(t.ray).applyMatrix4(Zw);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,h=i.index,d=i.attributes.position;if(h!==null){const f=Math.max(0,r.start),p=Math.min(h.count,r.start+r.count);for(let m=f,g=p-1;m<g;m+=l){const v=h.getX(m),M=h.getX(m+1),w=lp(this,t,Gu,c,v,M,m);w&&e.push(w)}if(this.isLineLoop){const m=h.getX(p-1),g=h.getX(f),v=lp(this,t,Gu,c,m,g,p-1);v&&e.push(v)}}else{const f=Math.max(0,r.start),p=Math.min(d.count,r.start+r.count);for(let m=f,g=p-1;m<g;m+=l){const v=lp(this,t,Gu,c,m,m+1,m);v&&e.push(v)}if(this.isLineLoop){const m=lp(this,t,Gu,c,p-1,f,p-1);m&&e.push(m)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function lp(o,t,e,i,n,s,r){const a=o.geometry.attributes.position;if(Y0.fromBufferAttribute(a,n),K0.fromBufferAttribute(a,s),e.distanceSqToSegment(Y0,K0,Lg,Jw)>i)return;Lg.applyMatrix4(o.matrixWorld);const l=t.ray.origin.distanceTo(Lg);if(!(l<t.near||l>t.far))return{distance:l,point:Jw.clone().applyMatrix4(o.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:o}}const jw=new T,Qw=new T;class sk extends pA{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[];for(let n=0,s=e.count;n<s;n+=2)jw.fromBufferAttribute(e,n),Qw.fromBufferAttribute(e,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+jw.distanceTo(Qw);t.setAttribute("lineDistance",new pe(i,1))}else Ht("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class rk extends pA{constructor(t,e){super(t,e),this.isLineLoop=!0,this.type="LineLoop"}}class Qv extends Ga{constructor(t){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new rt(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const tx=new Gt,tM=new El,hp=new Tr,up=new T;class ir extends Bi{constructor(t=new be,e=new Qv){super(),this.isPoints=!0,this.type="Points",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Points.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),hp.copy(i.boundingSphere),hp.applyMatrix4(n),hp.radius+=s,t.ray.intersectsSphere(hp)===!1)return;tx.copy(n).invert(),tM.copy(t.ray).applyMatrix4(tx);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=i.index,u=i.attributes.position;if(l!==null){const d=Math.max(0,r.start),f=Math.min(l.count,r.start+r.count);for(let p=d,m=f;p<m;p++){const g=l.getX(p);up.fromBufferAttribute(u,g),ex(up,g,c,n,t,e,this)}}else{const d=Math.max(0,r.start),f=Math.min(u.count,r.start+r.count);for(let p=d,m=f;p<m;p++)up.fromBufferAttribute(u,p),ex(up,p,c,n,t,e,this)}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function ex(o,t,e,i,n,s,r){const a=tM.distanceSqToPoint(o);if(a<e){const c=new T;tM.closestPointToPoint(o,c),c.applyMatrix4(i);const l=n.ray.origin.distanceTo(c);if(l<n.near||l>n.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:r})}}class ak extends Wn{constructor(t,e,i,n,s=Me,r=Me,a,c,l){super(t,e,i,n,s,r,a,c,l),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const h=this;function u(){h.needsUpdate=!0,h._requestVideoFrameCallbackId=t.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in t&&(this._requestVideoFrameCallbackId=t.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;"requestVideoFrameCallback"in t===!1&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class mA extends Wn{constructor(t=[],e=wl,i,n,s,r,a,c,l,h){super(t,e,i,n,s,r,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class Tc extends Wn{constructor(t,e,i,n,s,r,a,c,l){super(t,e,i,n,s,r,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Sc extends Wn{constructor(t,e,i=_r,n,s,r,a=si,c=si,l,h=So,u=1){if(h!==So&&h!==tl)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:t,height:e,depth:u};super(d,n,s,r,a,c,h,i,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new vy(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class WR extends Sc{constructor(t,e=_r,i=wl,n,s,r=si,a=si,c,l=So){const h={width:t,height:t,depth:1},u=[h,h,h,h,h,h];super(t,t,e,i,n,s,r,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class gA extends Wn{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class en extends be{constructor(t=1,e=1,i=1,n=1,s=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:n,heightSegments:s,depthSegments:r};const a=this;n=Math.floor(n),s=Math.floor(s),r=Math.floor(r);const c=[],l=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,i,e,t,r,s,0),p("z","y","x",1,-1,i,e,-t,r,s,1),p("x","z","y",1,1,t,i,e,n,r,2),p("x","z","y",1,-1,t,i,-e,n,r,3),p("x","y","z",1,-1,t,e,i,n,s,4),p("x","y","z",-1,-1,t,e,-i,n,s,5),this.setIndex(c),this.setAttribute("position",new pe(l,3)),this.setAttribute("normal",new pe(h,3)),this.setAttribute("uv",new pe(u,2));function p(m,g,v,M,w,y,x,b,E,S,A){const _=y/E,I=x/S,D=y/2,O=x/2,P=b/2,N=E+1,k=S+1;let B=0,W=0;const Q=new T;for(let Z=0;Z<k;Z++){const nt=Z*I-O;for(let ot=0;ot<N;ot++){const Ut=ot*_-D;Q[m]=Ut*M,Q[g]=nt*w,Q[v]=P,l.push(Q.x,Q.y,Q.z),Q[m]=0,Q[g]=0,Q[v]=b>0?1:-1,h.push(Q.x,Q.y,Q.z),u.push(ot/E),u.push(1-Z/S),B+=1}}for(let Z=0;Z<S;Z++)for(let nt=0;nt<E;nt++){const ot=d+nt+N*Z,Ut=d+nt+N*(Z+1),Zt=d+(nt+1)+N*(Z+1),jt=d+(nt+1)+N*Z;c.push(ot,Ut,jt),c.push(Ut,Zt,jt),W+=6}a.addGroup(f,W,A),f+=W,d+=B}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new en(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}class xy extends be{constructor(t=1,e=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:i,thetaLength:n},e=Math.max(3,e);const s=[],r=[],a=[],c=[],l=new T,h=new tt;r.push(0,0,0),a.push(0,0,1),c.push(.5,.5);for(let u=0,d=3;u<=e;u++,d+=3){const f=i+u/e*n;l.x=t*Math.cos(f),l.y=t*Math.sin(f),r.push(l.x,l.y,l.z),a.push(0,0,1),h.x=(r[d]/t+1)/2,h.y=(r[d+1]/t+1)/2,c.push(h.x,h.y)}for(let u=1;u<=e;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new pe(r,3)),this.setAttribute("normal",new pe(a,3)),this.setAttribute("uv",new pe(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new xy(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class gs extends be{constructor(t=1,e=1,i=1,n=32,s=1,r=!1,a=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:i,radialSegments:n,heightSegments:s,openEnded:r,thetaStart:a,thetaLength:c};const l=this;n=Math.floor(n),s=Math.floor(s);const h=[],u=[],d=[],f=[];let p=0;const m=[],g=i/2;let v=0;M(),r===!1&&(t>0&&w(!0),e>0&&w(!1)),this.setIndex(h),this.setAttribute("position",new pe(u,3)),this.setAttribute("normal",new pe(d,3)),this.setAttribute("uv",new pe(f,2));function M(){const y=new T,x=new T;let b=0;const E=(e-t)/i;for(let S=0;S<=s;S++){const A=[],_=S/s,I=_*(e-t)+t;for(let D=0;D<=n;D++){const O=D/n,P=O*c+a,N=Math.sin(P),k=Math.cos(P);x.x=I*N,x.y=-_*i+g,x.z=I*k,u.push(x.x,x.y,x.z),y.set(N,E,k).normalize(),d.push(y.x,y.y,y.z),f.push(O,1-_),A.push(p++)}m.push(A)}for(let S=0;S<n;S++)for(let A=0;A<s;A++){const _=m[A][S],I=m[A+1][S],D=m[A+1][S+1],O=m[A][S+1];(t>0||A!==0)&&(h.push(_,I,O),b+=3),(e>0||A!==s-1)&&(h.push(I,D,O),b+=3)}l.addGroup(v,b,0),v+=b}function w(y){const x=p,b=new tt,E=new T;let S=0;const A=y===!0?t:e,_=y===!0?1:-1;for(let D=1;D<=n;D++)u.push(0,g*_,0),d.push(0,_,0),f.push(.5,.5),p++;const I=p;for(let D=0;D<=n;D++){const P=D/n*c+a,N=Math.cos(P),k=Math.sin(P);E.x=A*k,E.y=g*_,E.z=A*N,u.push(E.x,E.y,E.z),d.push(0,_,0),b.x=N*.5+.5,b.y=k*.5*_+.5,f.push(b.x,b.y),p++}for(let D=0;D<n;D++){const O=x+D,P=I+D;y===!0?h.push(P,P+1,O):h.push(P+1,P,O),S+=3}l.addGroup(v,S,y===!0?1:2),v+=S}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new gs(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class bu extends gs{constructor(t=1,e=1,i=32,n=1,s=!1,r=0,a=Math.PI*2){super(0,t,e,i,n,s,r,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:r,thetaLength:a}}static fromJSON(t){return new bu(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class Va{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Ht("Curve: .getPoint() not implemented.")}getPointAt(t,e){const i=this.getUtoTmapping(t);return this.getPoint(i,e)}getPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return e}getSpacedPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPointAt(i/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let i,n=this.getPoint(0),s=0;e.push(0);for(let r=1;r<=t;r++)i=this.getPoint(r/t),s+=i.distanceTo(n),e.push(s),n=i;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e=null){const i=this.getLengths();let n=0;const s=i.length;let r;e?r=e:r=t*i[s-1];let a=0,c=s-1,l;for(;a<=c;)if(n=Math.floor(a+(c-a)/2),l=i[n]-r,l<0)a=n+1;else if(l>0)c=n-1;else{c=n;break}if(n=c,i[n]===r)return n/(s-1);const h=i[n],d=i[n+1]-h,f=(r-h)/d;return(n+f)/(s-1)}getTangent(t,e){let n=t-1e-4,s=t+1e-4;n<0&&(n=0),s>1&&(s=1);const r=this.getPoint(n),a=this.getPoint(s),c=e||(r.isVector2?new tt:new T);return c.copy(a).sub(r).normalize(),c}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e=!1){const i=new T,n=[],s=[],r=[],a=new T,c=new Gt;for(let f=0;f<=t;f++){const p=f/t;n[f]=this.getTangentAt(p,new T)}s[0]=new T,r[0]=new T;let l=Number.MAX_VALUE;const h=Math.abs(n[0].x),u=Math.abs(n[0].y),d=Math.abs(n[0].z);h<=l&&(l=h,i.set(1,0,0)),u<=l&&(l=u,i.set(0,1,0)),d<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),s[0].crossVectors(n[0],a),r[0].crossVectors(n[0],s[0]);for(let f=1;f<=t;f++){if(s[f]=s[f-1].clone(),r[f]=r[f-1].clone(),a.crossVectors(n[f-1],n[f]),a.length()>Number.EPSILON){a.normalize();const p=Math.acos(ge(n[f-1].dot(n[f]),-1,1));s[f].applyMatrix4(c.makeRotationAxis(a,p))}r[f].crossVectors(n[f],s[f])}if(e===!0){let f=Math.acos(ge(s[0].dot(s[t]),-1,1));f/=t,n[0].dot(a.crossVectors(s[0],s[t]))>0&&(f=-f);for(let p=1;p<=t;p++)s[p].applyMatrix4(c.makeRotationAxis(n[p],f*p)),r[p].crossVectors(n[p],s[p])}return{tangents:n,normals:s,binormals:r}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class by extends Va{constructor(t=0,e=0,i=1,n=1,s=0,r=Math.PI*2,a=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=s,this.aEndAngle=r,this.aClockwise=a,this.aRotation=c}getPoint(t,e=new tt){const i=e,n=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const r=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=n;for(;s>n;)s-=n;s<Number.EPSILON&&(r?s=0:s=n),this.aClockwise===!0&&!r&&(s===n?s=-n:s=s-n);const a=this.aStartAngle+t*s;let c=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){const h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=c-this.aX,f=l-this.aY;c=d*h-f*u+this.aX,l=d*u+f*h+this.aY}return i.set(c,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}class XR extends by{constructor(t,e,i,n,s,r){super(t,e,i,i,n,s,r),this.isArcCurve=!0,this.type="ArcCurve"}}function Sy(){let o=0,t=0,e=0,i=0;function n(s,r,a,c){o=s,t=a,e=-3*s+3*r-2*a-c,i=2*s-2*r+a+c}return{initCatmullRom:function(s,r,a,c,l){n(r,a,l*(a-s),l*(c-r))},initNonuniformCatmullRom:function(s,r,a,c,l,h,u){let d=(r-s)/l-(a-s)/(l+h)+(a-r)/h,f=(a-r)/h-(c-r)/(h+u)+(c-a)/u;d*=h,f*=h,n(r,a,d,f)},calc:function(s){const r=s*s,a=r*s;return o+t*s+e*r+i*a}}}const ix=new T,nx=new T,kg=new Sy,Fg=new Sy,Ug=new Sy;class $R extends Va{constructor(t=[],e=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=i,this.tension=n}getPoint(t,e=new T){const i=e,n=this.points,s=n.length,r=(s-(this.closed?0:1))*t;let a=Math.floor(r),c=r-a;this.closed?a+=a>0?0:(Math.floor(Math.abs(a)/s)+1)*s:c===0&&a===s-1&&(a=s-2,c=1);let l,h;this.closed||a>0?l=n[(a-1)%s]:(nx.subVectors(n[0],n[1]).add(n[0]),l=nx);const u=n[a%s],d=n[(a+1)%s];if(this.closed||a+2<s?h=n[(a+2)%s]:(ix.subVectors(n[s-1],n[s-2]).add(n[s-1]),h=ix),this.curveType==="centripetal"||this.curveType==="chordal"){const f=this.curveType==="chordal"?.5:.25;let p=Math.pow(l.distanceToSquared(u),f),m=Math.pow(u.distanceToSquared(d),f),g=Math.pow(d.distanceToSquared(h),f);m<1e-4&&(m=1),p<1e-4&&(p=m),g<1e-4&&(g=m),kg.initNonuniformCatmullRom(l.x,u.x,d.x,h.x,p,m,g),Fg.initNonuniformCatmullRom(l.y,u.y,d.y,h.y,p,m,g),Ug.initNonuniformCatmullRom(l.z,u.z,d.z,h.z,p,m,g)}else this.curveType==="catmullrom"&&(kg.initCatmullRom(l.x,u.x,d.x,h.x,this.tension),Fg.initCatmullRom(l.y,u.y,d.y,h.y,this.tension),Ug.initCatmullRom(l.z,u.z,d.z,h.z,this.tension));return i.set(kg.calc(c),Fg.calc(c),Ug.calc(c)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new T().fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function sx(o,t,e,i,n){const s=(i-t)*.5,r=(n-e)*.5,a=o*o,c=o*a;return(2*e-2*i+s+r)*c+(-3*e+3*i-2*s-r)*a+s*o+e}function YR(o,t){const e=1-o;return e*e*t}function KR(o,t){return 2*(1-o)*o*t}function qR(o,t){return o*o*t}function md(o,t,e,i){return YR(o,t)+KR(o,e)+qR(o,i)}function ZR(o,t){const e=1-o;return e*e*e*t}function JR(o,t){const e=1-o;return 3*e*e*o*t}function jR(o,t){return 3*(1-o)*o*o*t}function QR(o,t){return o*o*o*t}function gd(o,t,e,i,n){return ZR(o,t)+JR(o,e)+jR(o,i)+QR(o,n)}class vA extends Va{constructor(t=new tt,e=new tt,i=new tt,n=new tt){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new tt){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(gd(t,n.x,s.x,r.x,a.x),gd(t,n.y,s.y,r.y,a.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class tI extends Va{constructor(t=new T,e=new T,i=new T,n=new T){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new T){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(gd(t,n.x,s.x,r.x,a.x),gd(t,n.y,s.y,r.y,a.y),gd(t,n.z,s.z,r.z,a.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class MA extends Va{constructor(t=new tt,e=new tt){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new tt){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new tt){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class eI extends Va{constructor(t=new T,e=new T){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=t,this.v2=e}getPoint(t,e=new T){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new T){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class yA extends Va{constructor(t=new tt,e=new tt,i=new tt){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new tt){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(md(t,n.x,s.x,r.x),md(t,n.y,s.y,r.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class iI extends Va{constructor(t=new T,e=new T,i=new T){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new T){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(md(t,n.x,s.x,r.x),md(t,n.y,s.y,r.y),md(t,n.z,s.z,r.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class wA extends Va{constructor(t=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=t}getPoint(t,e=new tt){const i=e,n=this.points,s=(n.length-1)*t,r=Math.floor(s),a=s-r,c=n[r===0?r:r-1],l=n[r],h=n[r>n.length-2?n.length-1:r+1],u=n[r>n.length-3?n.length-1:r+2];return i.set(sx(a,c.x,l.x,h.x,u.x),sx(a,c.y,l.y,h.y,u.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new tt().fromArray(n))}return this}}var rx=Object.freeze({__proto__:null,ArcCurve:XR,CatmullRomCurve3:$R,CubicBezierCurve:vA,CubicBezierCurve3:tI,EllipseCurve:by,LineCurve:MA,LineCurve3:eI,QuadraticBezierCurve:yA,QuadraticBezierCurve3:iI,SplineCurve:wA});class nI extends Va{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);if(!t.equals(e)){const i=t.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new rx[i](e,t))}return this}getPoint(t,e){const i=t*this.getLength(),n=this.getCurveLengths();let s=0;for(;s<n.length;){if(n[s]>=i){const r=n[s]-i,a=this.curves[s],c=a.getLength(),l=c===0?0:1-r/c;return a.getPointAt(l,e)}s++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,n=this.curves.length;i<n;i++)e+=this.curves[i].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let i;for(let n=0,s=this.curves;n<s.length;n++){const r=s[n],a=r.isEllipseCurve?t*2:r.isLineCurve||r.isLineCurve3?1:r.isSplineCurve?t*r.points.length:t,c=r.getPoints(a);for(let l=0;l<c.length;l++){const h=c[l];i&&i.equals(h)||(e.push(h),i=h)}}return this.autoClose&&e.length>1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,i=this.curves.length;e<i;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(new rx[n.type]().fromJSON(n))}return this}}class ax extends nI{constructor(t){super(),this.type="Path",this.currentPoint=new tt,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,i=t.length;e<i;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const i=new MA(this.currentPoint.clone(),new tt(t,e));return this.curves.push(i),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,i,n){const s=new yA(this.currentPoint.clone(),new tt(t,e),new tt(i,n));return this.curves.push(s),this.currentPoint.set(i,n),this}bezierCurveTo(t,e,i,n,s,r){const a=new vA(this.currentPoint.clone(),new tt(t,e),new tt(i,n),new tt(s,r));return this.curves.push(a),this.currentPoint.set(s,r),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),i=new wA(e);return this.curves.push(i),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,i,n,s,r){const a=this.currentPoint.x,c=this.currentPoint.y;return this.absarc(t+a,e+c,i,n,s,r),this}absarc(t,e,i,n,s,r){return this.absellipse(t,e,i,i,n,s,r),this}ellipse(t,e,i,n,s,r,a,c){const l=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(t+l,e+h,i,n,s,r,a,c),this}absellipse(t,e,i,n,s,r,a,c){const l=new by(t,e,i,n,s,r,a,c);if(this.curves.length>0){const u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);const h=l.getPoint(1);return this.currentPoint.copy(h),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class eM extends ax{constructor(t){super(t),this.uuid=Ar(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,n=this.holes.length;i<n;i++)e[i]=this.holes[i].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,i=this.holes.length;e<i;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(new ax().fromJSON(n))}return this}}function sI(o,t,e=2){const i=t&&t.length,n=i?t[0]*e:o.length;let s=xA(o,0,n,e,!0);const r=[];if(!s||s.next===s.prev)return r;let a,c,l;if(i&&(s=lI(o,t,s,e)),o.length>80*e){a=o[0],c=o[1];let h=a,u=c;for(let d=e;d<n;d+=e){const f=o[d],p=o[d+1];f<a&&(a=f),p<c&&(c=p),f>h&&(h=f),p>u&&(u=p)}l=Math.max(h-a,u-c),l=l!==0?32767/l:0}return uf(s,r,e,a,c,l,0),r}function xA(o,t,e,i,n){let s;if(n===wI(o,t,e,i)>0)for(let r=t;r<e;r+=i)s=ox(r/i|0,o[r],o[r+1],s);else for(let r=e-i;r>=t;r-=i)s=ox(r/i|0,o[r],o[r+1],s);return s&&vu(s,s.next)&&(ff(s),s=s.next),s}function bl(o,t){if(!o)return o;t||(t=o);let e=o,i;do if(i=!1,!e.steiner&&(vu(e,e.next)||Xi(e.prev,e,e.next)===0)){if(ff(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function uf(o,t,e,i,n,s,r){if(!o)return;!r&&s&&pI(o,i,n,s);let a=o;for(;o.prev!==o.next;){const c=o.prev,l=o.next;if(s?aI(o,i,n,s):rI(o)){t.push(c.i,o.i,l.i),ff(o),o=l.next,a=l.next;continue}if(o=l,o===a){r?r===1?(o=oI(bl(o),t),uf(o,t,e,i,n,s,2)):r===2&&cI(o,t,e,i,n,s):uf(bl(o),t,e,i,n,s,1);break}}}function rI(o){const t=o.prev,e=o,i=o.next;if(Xi(t,e,i)>=0)return!1;const n=t.x,s=e.x,r=i.x,a=t.y,c=e.y,l=i.y,h=Math.min(n,s,r),u=Math.min(a,c,l),d=Math.max(n,s,r),f=Math.max(a,c,l);let p=i.next;for(;p!==t;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&ld(n,a,s,c,r,l,p.x,p.y)&&Xi(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function aI(o,t,e,i){const n=o.prev,s=o,r=o.next;if(Xi(n,s,r)>=0)return!1;const a=n.x,c=s.x,l=r.x,h=n.y,u=s.y,d=r.y,f=Math.min(a,c,l),p=Math.min(h,u,d),m=Math.max(a,c,l),g=Math.max(h,u,d),v=iM(f,p,t,e,i),M=iM(m,g,t,e,i);let w=o.prevZ,y=o.nextZ;for(;w&&w.z>=v&&y&&y.z<=M;){if(w.x>=f&&w.x<=m&&w.y>=p&&w.y<=g&&w!==n&&w!==r&&ld(a,h,c,u,l,d,w.x,w.y)&&Xi(w.prev,w,w.next)>=0||(w=w.prevZ,y.x>=f&&y.x<=m&&y.y>=p&&y.y<=g&&y!==n&&y!==r&&ld(a,h,c,u,l,d,y.x,y.y)&&Xi(y.prev,y,y.next)>=0))return!1;y=y.nextZ}for(;w&&w.z>=v;){if(w.x>=f&&w.x<=m&&w.y>=p&&w.y<=g&&w!==n&&w!==r&&ld(a,h,c,u,l,d,w.x,w.y)&&Xi(w.prev,w,w.next)>=0)return!1;w=w.prevZ}for(;y&&y.z<=M;){if(y.x>=f&&y.x<=m&&y.y>=p&&y.y<=g&&y!==n&&y!==r&&ld(a,h,c,u,l,d,y.x,y.y)&&Xi(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function oI(o,t){let e=o;do{const i=e.prev,n=e.next.next;!vu(i,n)&&SA(i,e,e.next,n)&&df(i,n)&&df(n,i)&&(t.push(i.i,e.i,n.i),ff(e),ff(e.next),e=o=n),e=e.next}while(e!==o);return bl(e)}function cI(o,t,e,i,n,s){let r=o;do{let a=r.next.next;for(;a!==r.prev;){if(r.i!==a.i&&vI(r,a)){let c=EA(r,a);r=bl(r,r.next),c=bl(c,c.next),uf(r,t,e,i,n,s,0),uf(c,t,e,i,n,s,0);return}a=a.next}r=r.next}while(r!==o)}function lI(o,t,e,i){const n=[];for(let s=0,r=t.length;s<r;s++){const a=t[s]*i,c=s<r-1?t[s+1]*i:o.length,l=xA(o,a,c,i,!1);l===l.next&&(l.steiner=!0),n.push(gI(l))}n.sort(hI);for(let s=0;s<n.length;s++)e=uI(n[s],e);return e}function hI(o,t){let e=o.x-t.x;if(e===0&&(e=o.y-t.y,e===0)){const i=(o.next.y-o.y)/(o.next.x-o.x),n=(t.next.y-t.y)/(t.next.x-t.x);e=i-n}return e}function uI(o,t){const e=dI(o,t);if(!e)return t;const i=EA(e,o);return bl(i,i.next),bl(e,e.next)}function dI(o,t){let e=t;const i=o.x,n=o.y;let s=-1/0,r;if(vu(o,e))return e;do{if(vu(o,e.next))return e.next;if(n<=e.y&&n>=e.next.y&&e.next.y!==e.y){const u=e.x+(n-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=i&&u>s&&(s=u,r=e.x<e.next.x?e:e.next,u===i))return r}e=e.next}while(e!==t);if(!r)return null;const a=r,c=r.x,l=r.y;let h=1/0;e=r;do{if(i>=e.x&&e.x>=c&&i!==e.x&&bA(n<l?i:s,n,c,l,n<l?s:i,n,e.x,e.y)){const u=Math.abs(n-e.y)/(i-e.x);df(e,o)&&(u<h||u===h&&(e.x>r.x||e.x===r.x&&fI(r,e)))&&(r=e,h=u)}e=e.next}while(e!==a);return r}function fI(o,t){return Xi(o.prev,o,t.prev)<0&&Xi(t.next,o,o.next)<0}function pI(o,t,e,i){let n=o;do n.z===0&&(n.z=iM(n.x,n.y,t,e,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==o);n.prevZ.nextZ=null,n.prevZ=null,mI(n)}function mI(o){let t,e=1;do{let i=o,n;o=null;let s=null;for(t=0;i;){t++;let r=i,a=0;for(let l=0;l<e&&(a++,r=r.nextZ,!!r);l++);let c=e;for(;a>0||c>0&&r;)a!==0&&(c===0||!r||i.z<=r.z)?(n=i,i=i.nextZ,a--):(n=r,r=r.nextZ,c--),s?s.nextZ=n:o=n,n.prevZ=s,s=n;i=r}s.nextZ=null,e*=2}while(t>1);return o}function iM(o,t,e,i,n){return o=(o-e)*n|0,t=(t-i)*n|0,o=(o|o<<8)&16711935,o=(o|o<<4)&252645135,o=(o|o<<2)&858993459,o=(o|o<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,o|t<<1}function gI(o){let t=o,e=o;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==o);return e}function bA(o,t,e,i,n,s,r,a){return(n-r)*(t-a)>=(o-r)*(s-a)&&(o-r)*(i-a)>=(e-r)*(t-a)&&(e-r)*(s-a)>=(n-r)*(i-a)}function ld(o,t,e,i,n,s,r,a){return!(o===r&&t===a)&&bA(o,t,e,i,n,s,r,a)}function vI(o,t){return o.next.i!==t.i&&o.prev.i!==t.i&&!MI(o,t)&&(df(o,t)&&df(t,o)&&yI(o,t)&&(Xi(o.prev,o,t.prev)||Xi(o,t.prev,t))||vu(o,t)&&Xi(o.prev,o,o.next)>0&&Xi(t.prev,t,t.next)>0)}function Xi(o,t,e){return(t.y-o.y)*(e.x-t.x)-(t.x-o.x)*(e.y-t.y)}function vu(o,t){return o.x===t.x&&o.y===t.y}function SA(o,t,e,i){const n=fp(Xi(o,t,e)),s=fp(Xi(o,t,i)),r=fp(Xi(e,i,o)),a=fp(Xi(e,i,t));return!!(n!==s&&r!==a||n===0&&dp(o,e,t)||s===0&&dp(o,i,t)||r===0&&dp(e,o,i)||a===0&&dp(e,t,i))}function dp(o,t,e){return t.x<=Math.max(o.x,e.x)&&t.x>=Math.min(o.x,e.x)&&t.y<=Math.max(o.y,e.y)&&t.y>=Math.min(o.y,e.y)}function fp(o){return o>0?1:o<0?-1:0}function MI(o,t){let e=o;do{if(e.i!==o.i&&e.next.i!==o.i&&e.i!==t.i&&e.next.i!==t.i&&SA(e,e.next,o,t))return!0;e=e.next}while(e!==o);return!1}function df(o,t){return Xi(o.prev,o,o.next)<0?Xi(o,t,o.next)>=0&&Xi(o,o.prev,t)>=0:Xi(o,t,o.prev)<0||Xi(o,o.next,t)<0}function yI(o,t){let e=o,i=!1;const n=(o.x+t.x)/2,s=(o.y+t.y)/2;do e.y>s!=e.next.y>s&&e.next.y!==e.y&&n<(e.next.x-e.x)*(s-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==o);return i}function EA(o,t){const e=nM(o.i,o.x,o.y),i=nM(t.i,t.x,t.y),n=o.next,s=t.prev;return o.next=t,t.prev=o,e.next=n,n.prev=e,i.next=e,e.prev=i,s.next=i,i.prev=s,i}function ox(o,t,e,i){const n=nM(o,t,e);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function ff(o){o.next.prev=o.prev,o.prev.next=o.next,o.prevZ&&(o.prevZ.nextZ=o.nextZ),o.nextZ&&(o.nextZ.prevZ=o.prevZ)}function nM(o,t,e){return{i:o,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function wI(o,t,e,i){let n=0;for(let s=t,r=e-i;s<e;s+=i)n+=(o[r]-o[s])*(o[s+1]+o[r+1]),r=s;return n}class xI{static triangulate(t,e,i=2){return sI(t,e,i)}}class vd{static area(t){const e=t.length;let i=0;for(let n=e-1,s=0;s<e;n=s++)i+=t[n].x*t[s].y-t[s].x*t[n].y;return i*.5}static isClockWise(t){return vd.area(t)<0}static triangulateShape(t,e){const i=[],n=[],s=[];cx(t),lx(i,t);let r=t.length;e.forEach(cx);for(let c=0;c<e.length;c++)n.push(r),r+=e[c].length,lx(i,e[c]);const a=xI.triangulate(i,n);for(let c=0;c<a.length;c+=3)s.push(a.slice(c,c+3));return s}}function cx(o){const t=o.length;t>2&&o[t-1].equals(o[0])&&o.pop()}function lx(o,t){for(let e=0;e<t.length;e++)o.push(t[e].x),o.push(t[e].y)}class Om extends be{constructor(t=[new tt(0,-.5),new tt(.5,0),new tt(0,.5)],e=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:i,phiLength:n},e=Math.floor(e),n=ge(n,0,Math.PI*2);const s=[],r=[],a=[],c=[],l=[],h=1/e,u=new T,d=new tt,f=new T,p=new T,m=new T;let g=0,v=0;for(let M=0;M<=t.length-1;M++)switch(M){case 0:g=t[M+1].x-t[M].x,v=t[M+1].y-t[M].y,f.x=v*1,f.y=-g,f.z=v*0,m.copy(f),f.normalize(),c.push(f.x,f.y,f.z);break;case t.length-1:c.push(m.x,m.y,m.z);break;default:g=t[M+1].x-t[M].x,v=t[M+1].y-t[M].y,f.x=v*1,f.y=-g,f.z=v*0,p.copy(f),f.x+=m.x,f.y+=m.y,f.z+=m.z,f.normalize(),c.push(f.x,f.y,f.z),m.copy(p)}for(let M=0;M<=e;M++){const w=i+M*h*n,y=Math.sin(w),x=Math.cos(w);for(let b=0;b<=t.length-1;b++){u.x=t[b].x*y,u.y=t[b].y,u.z=t[b].x*x,r.push(u.x,u.y,u.z),d.x=M/e,d.y=b/(t.length-1),a.push(d.x,d.y);const E=c[3*b+0]*y,S=c[3*b+1],A=c[3*b+0]*x;l.push(E,S,A)}}for(let M=0;M<e;M++)for(let w=0;w<t.length-1;w++){const y=w+M*t.length,x=y,b=y+t.length,E=y+t.length+1,S=y+1;s.push(x,b,S),s.push(E,S,b)}this.setIndex(s),this.setAttribute("position",new pe(r,3)),this.setAttribute("uv",new pe(a,2)),this.setAttribute("normal",new pe(l,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Om(t.points,t.segments,t.phiStart,t.phiLength)}}class vs extends be{constructor(t=1,e=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};const s=t/2,r=e/2,a=Math.floor(i),c=Math.floor(n),l=a+1,h=c+1,u=t/a,d=e/c,f=[],p=[],m=[],g=[];for(let v=0;v<h;v++){const M=v*d-r;for(let w=0;w<l;w++){const y=w*u-s;p.push(y,-M,0),m.push(0,0,1),g.push(w/a),g.push(1-v/c)}}for(let v=0;v<c;v++)for(let M=0;M<a;M++){const w=M+l*v,y=M+l*(v+1),x=M+1+l*(v+1),b=M+1+l*v;f.push(w,y,b),f.push(y,x,b)}this.setIndex(f),this.setAttribute("position",new pe(p,3)),this.setAttribute("normal",new pe(m,3)),this.setAttribute("uv",new pe(g,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new vs(t.width,t.height,t.widthSegments,t.heightSegments)}}class Ey extends be{constructor(t=new eM([new tt(0,.5),new tt(-.5,-.5),new tt(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const i=[],n=[],s=[],r=[];let a=0,c=0;if(Array.isArray(t)===!1)l(t);else for(let h=0;h<t.length;h++)l(t[h]),this.addGroup(a,c,h),a+=c,c=0;this.setIndex(i),this.setAttribute("position",new pe(n,3)),this.setAttribute("normal",new pe(s,3)),this.setAttribute("uv",new pe(r,2));function l(h){const u=n.length/3,d=h.extractPoints(e);let f=d.shape;const p=d.holes;vd.isClockWise(f)===!1&&(f=f.reverse());for(let g=0,v=p.length;g<v;g++){const M=p[g];vd.isClockWise(M)===!0&&(p[g]=M.reverse())}const m=vd.triangulateShape(f,p);for(let g=0,v=p.length;g<v;g++){const M=p[g];f=f.concat(M)}for(let g=0,v=f.length;g<v;g++){const M=f[g];n.push(M.x,M.y,0),s.push(0,0,1),r.push(M.x,M.y)}for(let g=0,v=m.length;g<v;g++){const M=m[g],w=M[0]+u,y=M[1]+u,x=M[2]+u;i.push(w,y,x),c+=3}}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON(),e=this.parameters.shapes;return bI(e,t)}static fromJSON(t,e){const i=[];for(let n=0,s=t.shapes.length;n<s;n++){const r=e[t.shapes[n]];i.push(r)}return new Ey(i,t.curveSegments)}}function bI(o,t){if(t.shapes=[],Array.isArray(o))for(let e=0,i=o.length;e<i;e++){const n=o[e];t.shapes.push(n.uuid)}else t.shapes.push(o.uuid);return t}class hn extends be{constructor(t=1,e=32,i=16,n=0,s=Math.PI*2,r=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:s,thetaStart:r,thetaLength:a},e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));const c=Math.min(r+a,Math.PI);let l=0;const h=[],u=new T,d=new T,f=[],p=[],m=[],g=[];for(let v=0;v<=i;v++){const M=[],w=v/i,y=r+w*a,x=t*Math.cos(y),b=Math.sqrt(t*t-x*x);let E=0;v===0&&r===0?E=.5/e:v===i&&c===Math.PI&&(E=-.5/e);for(let S=0;S<=e;S++){const A=S/e,_=n+A*s;u.x=-b*Math.cos(_),u.y=x,u.z=b*Math.sin(_),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),g.push(A+E,1-w),M.push(l++)}h.push(M)}for(let v=0;v<i;v++)for(let M=0;M<e;M++){const w=h[v][M+1],y=h[v][M],x=h[v+1][M],b=h[v+1][M+1];(v!==0||r>0)&&f.push(w,y,b),(v!==i-1||c<Math.PI)&&f.push(y,x,b)}this.setIndex(f),this.setAttribute("position",new pe(p,3)),this.setAttribute("normal",new pe(m,3)),this.setAttribute("uv",new pe(g,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new hn(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class Ay extends be{constructor(t=1,e=.4,i=12,n=48,s=Math.PI*2,r=0,a=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:s,thetaStart:r,thetaLength:a},i=Math.floor(i),n=Math.floor(n);const c=[],l=[],h=[],u=[],d=new T,f=new T,p=new T;for(let m=0;m<=i;m++){const g=r+m/i*a;for(let v=0;v<=n;v++){const M=v/n*s;f.x=(t+e*Math.cos(g))*Math.cos(M),f.y=(t+e*Math.cos(g))*Math.sin(M),f.z=e*Math.sin(g),l.push(f.x,f.y,f.z),d.x=t*Math.cos(M),d.y=t*Math.sin(M),p.subVectors(f,d).normalize(),h.push(p.x,p.y,p.z),u.push(v/n),u.push(m/i)}}for(let m=1;m<=i;m++)for(let g=1;g<=n;g++){const v=(n+1)*m+g-1,M=(n+1)*(m-1)+g-1,w=(n+1)*(m-1)+g,y=(n+1)*m+g;c.push(v,M,y),c.push(M,w,y)}this.setIndex(c),this.setAttribute("position",new pe(l,3)),this.setAttribute("normal",new pe(h,3)),this.setAttribute("uv",new pe(u,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Ay(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class ok extends be{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},t!==null){const e=[],i=new Set,n=new T,s=new T;if(t.index!==null){const r=t.attributes.position,a=t.index;let c=t.groups;c.length===0&&(c=[{start:0,count:a.count,materialIndex:0}]);for(let l=0,h=c.length;l<h;++l){const u=c[l],d=u.start,f=u.count;for(let p=d,m=d+f;p<m;p+=3)for(let g=0;g<3;g++){const v=a.getX(p+g),M=a.getX(p+(g+1)%3);n.fromBufferAttribute(r,v),s.fromBufferAttribute(r,M),hx(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}}else{const r=t.attributes.position;for(let a=0,c=r.count/3;a<c;a++)for(let l=0;l<3;l++){const h=3*a+l,u=3*a+(l+1)%3;n.fromBufferAttribute(r,h),s.fromBufferAttribute(r,u),hx(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}this.setAttribute("position",new pe(e,3))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}}function hx(o,t,e){const i=`${o.x},${o.y},${o.z}-${t.x},${t.y},${t.z}`,n=`${t.x},${t.y},${t.z}-${o.x},${o.y},${o.z}`;return e.has(i)===!0||e.has(n)===!0?!1:(e.add(i),e.add(n),!0)}function Mu(o){const t={};for(const e in o){t[e]={};for(const i in o[e]){const n=o[e][i];if(ux(n))n.isRenderTargetTexture?(Ht("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[e][i]=null):t[e][i]=n.clone();else if(Array.isArray(n))if(ux(n[0])){const s=[];for(let r=0,a=n.length;r<a;r++)s[r]=n[r].clone();t[e][i]=s}else t[e][i]=n.slice();else t[e][i]=n}}return t}function ws(o){const t={};for(let e=0;e<o.length;e++){const i=Mu(o[e]);for(const n in i)t[n]=i[n]}return t}function ux(o){return o&&(o.isColor||o.isMatrix3||o.isMatrix4||o.isVector2||o.isVector3||o.isVector4||o.isTexture||o.isQuaternion)}function SI(o){const t=[];for(let e=0;e<o.length;e++)t.push(o[e].clone());return t}function AA(o){const t=o.getRenderTarget();return t===null?o.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:He.workingColorSpace}const EI={clone:Mu,merge:ws};var AI=`void main() {
|
|
783
|
+
*/const _f="185",g4=0,Mw=1,v4=2,dd=1,M4=2,cd=3,Ba=0,zi=1,Tn=2,Ys=0,Mc=1,Cn=2,yw=3,ww=4,Ml=5,ao=100,y4=101,w4=102,x4=103,b4=104,Ta=200,yl=201,S4=202,E4=203,k0=204,af=205,A4=206,_4=207,T4=208,R4=209,I4=210,D4=211,C4=212,O4=213,P4=214,fv=0,pv=1,mv=2,fu=3,gv=4,vv=5,Mv=6,yv=7,ay=0,N4=1,L4=2,ka=0,XE=1,$E=2,YE=3,KE=4,qE=5,ZE=6,JE=7,xw="attached",k4="detached",jE=300,wl=301,pu=302,ag=303,og=304,Dm=306,bc=1e3,Qi=1001,wv=1002,si=1003,F4=1004,zf=1005,Me=1006,cg=1007,cr=1008,fs=1009,QE=1010,tA=1011,of=1012,oy=1013,_r=1014,ts=1015,Ye=1016,cy=1017,ly=1018,cf=1020,eA=35902,iA=35899,nA=1021,sA=1022,tn=1023,So=1026,tl=1027,mu=1028,hy=1029,xl=1030,uy=1031,dy=1033,s0=33776,r0=33777,a0=33778,o0=33779,xv=35840,bv=35841,Sv=35842,Ev=35843,Av=36196,_v=37492,Tv=37496,Rv=37488,Iv=37489,F0=37490,Dv=37491,Cv=37808,Ov=37809,Pv=37810,Nv=37811,Lv=37812,kv=37813,Fv=37814,Uv=37815,zv=37816,Bv=37817,Hv=37818,Gv=37819,Vv=37820,Wv=37821,Xv=36492,$v=36494,Yv=36495,Kv=36283,qv=36284,U0=36285,Zv=36286,rA=2200,U4=2201,z4=2202,z0=2300,Jv=2301,lg=2302,bw=2303,Eh=2400,Ah=2401,B0=2402,fy=2500,B4=2501,j7=0,Q7=1,tk=2,H4=3200,H0=0,G4=1,tc="",Bn="srgb",G0="srgb-linear",V0="linear",ui="srgb",Pl=7680,Sw=519,V4=512,W4=513,X4=514,py=515,$4=516,Y4=517,my=518,K4=519,jv=35044,W0="300 es",Ca=2e3,lf=2001;function q4(o){for(let t=o.length-1;t>=0;--t)if(o[t]>=65535)return!0;return!1}function Z4(o){return ArrayBuffer.isView(o)&&!(o instanceof DataView)}function hf(o){return document.createElementNS("http://www.w3.org/1999/xhtml",o)}function J4(){const o=hf("canvas");return o.style.display="block",o}const Ew={};function X0(...o){const t="THREE."+o.shift();console.log(t,...o)}function aA(o){const t=o[0];if(typeof t=="string"&&t.startsWith("TSL:")){const e=o[1];e&&e.isStackTrace?o[0]+=" "+e.getLocation():o[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return o}function Ht(...o){o=aA(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...o)}}function le(...o){o=aA(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...o)}}function Jh(...o){const t=o.join(" ");t in Ew||(Ew[t]=!0,Ht(...o))}function j4(o,t,e){return new Promise(function(i,n){function s(){switch(o.clientWaitSync(t,o.SYNC_FLUSH_COMMANDS_BIT,0)){case o.WAIT_FAILED:n();break;case o.TIMEOUT_EXPIRED:setTimeout(s,e);break;default:i()}}setTimeout(s,e)})}const Q4={[fv]:pv,[mv]:Mv,[gv]:yv,[fu]:vv,[pv]:fv,[Mv]:mv,[yv]:gv,[vv]:fu};class _c{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i===void 0?!1:i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const i=this._listeners;if(i===void 0)return;const n=i[t];if(n!==void 0){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}}dispatchEvent(t){const e=this._listeners;if(e===void 0)return;const i=e[t.type];if(i!==void 0){t.target=this;const n=i.slice(0);for(let s=0,r=n.length;s<r;s++)n[s].call(this,t);t.target=null}}}const ns=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Aw=1234567;const fd=Math.PI/180,gu=180/Math.PI;function Ar(){const o=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(ns[o&255]+ns[o>>8&255]+ns[o>>16&255]+ns[o>>24&255]+"-"+ns[t&255]+ns[t>>8&255]+"-"+ns[t>>16&15|64]+ns[t>>24&255]+"-"+ns[e&63|128]+ns[e>>8&255]+"-"+ns[e>>16&255]+ns[e>>24&255]+ns[i&255]+ns[i>>8&255]+ns[i>>16&255]+ns[i>>24&255]).toLowerCase()}function ge(o,t,e){return Math.max(t,Math.min(e,o))}function gy(o,t){return(o%t+t)%t}function tR(o,t,e,i,n){return i+(o-t)*(n-i)/(e-t)}function eR(o,t,e){return o!==t?(e-o)/(t-o):0}function pd(o,t,e){return(1-e)*o+e*t}function iR(o,t,e,i){return pd(o,t,1-Math.exp(-e*i))}function nR(o,t=1){return t-Math.abs(gy(o,t*2)-t)}function sR(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*(3-2*o))}function rR(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*o*(o*(o*6-15)+10))}function aR(o,t){return o+Math.floor(Math.random()*(t-o+1))}function oR(o,t){return o+Math.random()*(t-o)}function cR(o){return o*(.5-Math.random())}function lR(o){o!==void 0&&(Aw=o);let t=Aw+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function hR(o){return o*fd}function uR(o){return o*gu}function dR(o){return(o&o-1)===0&&o!==0}function fR(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function pR(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function mR(o,t,e,i,n){const s=Math.cos,r=Math.sin,a=s(e/2),c=r(e/2),l=s((t+i)/2),h=r((t+i)/2),u=s((t-i)/2),d=r((t-i)/2),f=s((i-t)/2),p=r((i-t)/2);switch(n){case"XYX":o.set(a*h,c*u,c*d,a*l);break;case"YZY":o.set(c*d,a*h,c*u,a*l);break;case"ZXZ":o.set(c*u,c*d,a*h,a*l);break;case"XZX":o.set(a*h,c*p,c*f,a*l);break;case"YXY":o.set(c*f,a*h,c*p,a*l);break;case"ZYZ":o.set(c*p,c*f,a*h,a*l);break;default:Ht("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Gr(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function di(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const ek={DEG2RAD:fd,RAD2DEG:gu,generateUUID:Ar,clamp:ge,euclideanModulo:gy,mapLinear:tR,inverseLerp:eR,lerp:pd,damp:iR,pingpong:nR,smoothstep:sR,smootherstep:rR,randInt:aR,randFloat:oR,randFloatSpread:cR,seededRandom:lR,degToRad:hR,radToDeg:uR,isPowerOfTwo:dR,ceilPowerOfTwo:fR,floorPowerOfTwo:pR,setQuaternionFromProperEuler:mR,normalize:di,denormalize:Gr};class tt{static{tt.prototype.isVector2=!0}constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=ge(this.x,t.x,e.x),this.y=ge(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=ge(this.x,t,e),this.y=ge(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(ge(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ge(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),n=Math.sin(e),s=this.x-t.x,r=this.y-t.y;return this.x=s*i-r*n+t.x,this.y=s*n+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class es{constructor(t=0,e=0,i=0,n=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=n}static slerpFlat(t,e,i,n,s,r,a){let c=i[n+0],l=i[n+1],h=i[n+2],u=i[n+3],d=s[r+0],f=s[r+1],p=s[r+2],m=s[r+3];if(u!==m||c!==d||l!==f||h!==p){let g=c*d+l*f+h*p+u*m;g<0&&(d=-d,f=-f,p=-p,m=-m,g=-g);let v=1-a;if(g<.9995){const M=Math.acos(g),w=Math.sin(M);v=Math.sin(v*M)/w,a=Math.sin(a*M)/w,c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+m*a}else{c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+m*a;const M=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=M,l*=M,h*=M,u*=M}}t[e]=c,t[e+1]=l,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,i,n,s,r){const a=i[n],c=i[n+1],l=i[n+2],h=i[n+3],u=s[r],d=s[r+1],f=s[r+2],p=s[r+3];return t[e]=a*p+h*u+c*f-l*d,t[e+1]=c*p+h*d+l*u-a*f,t[e+2]=l*p+h*f+a*d-c*u,t[e+3]=h*p-a*u-c*d-l*f,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,n){return this._x=t,this._y=e,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,n=t._y,s=t._z,r=t._order,a=Math.cos,c=Math.sin,l=a(i/2),h=a(n/2),u=a(s/2),d=c(i/2),f=c(n/2),p=c(s/2);switch(r){case"XYZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"YZX":this._x=d*h*u+l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u-d*f*p;break;case"XZY":this._x=d*h*u-l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u+d*f*p;break;default:Ht("Quaternion: .setFromEuler() encountered an unknown order: "+r)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,n=Math.sin(i);return this._x=t.x*n,this._y=t.y*n,this._z=t.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],n=e[4],s=e[8],r=e[1],a=e[5],c=e[9],l=e[2],h=e[6],u=e[10],d=i+a+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(s-l)*f,this._z=(r-n)*f}else if(i>a&&i>u){const f=2*Math.sqrt(1+i-a-u);this._w=(h-c)/f,this._x=.25*f,this._y=(n+r)/f,this._z=(s+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-i-u);this._w=(s-l)/f,this._x=(n+r)/f,this._y=.25*f,this._z=(c+h)/f}else{const f=2*Math.sqrt(1+u-i-a);this._w=(r-n)/f,this._x=(s+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(ge(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const n=Math.min(1,e/i);return this.slerp(t,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,n=t._y,s=t._z,r=t._w,a=e._x,c=e._y,l=e._z,h=e._w;return this._x=i*h+r*a+n*l-s*c,this._y=n*h+r*c+s*a-i*l,this._z=s*h+r*l+i*c-n*a,this._w=r*h-i*a-n*c-s*l,this._onChangeCallback(),this}slerp(t,e){let i=t._x,n=t._y,s=t._z,r=t._w,a=this.dot(t);a<0&&(i=-i,n=-n,s=-s,r=-r,a=-a);let c=1-e;if(a<.9995){const l=Math.acos(a),h=Math.sin(l);c=Math.sin(c*l)/h,e=Math.sin(e*l)/h,this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this._onChangeCallback()}else this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(n*Math.sin(t),n*Math.cos(t),s*Math.sin(e),s*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class T{static{T.prototype.isVector3=!0}constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(_w.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(_w.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6]*n,this.y=s[1]*e+s[4]*i+s[7]*n,this.z=s[2]*e+s[5]*i+s[8]*n,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=t.elements,r=1/(s[3]*e+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*e+s[4]*i+s[8]*n+s[12])*r,this.y=(s[1]*e+s[5]*i+s[9]*n+s[13])*r,this.z=(s[2]*e+s[6]*i+s[10]*n+s[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,a=t.z,c=t.w,l=2*(r*n-a*i),h=2*(a*e-s*n),u=2*(s*i-r*e);return this.x=e+c*l+r*u-a*h,this.y=i+c*h+a*l-s*u,this.z=n+c*u+s*h-r*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[4]*i+s[8]*n,this.y=s[1]*e+s[5]*i+s[9]*n,this.z=s[2]*e+s[6]*i+s[10]*n,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=ge(this.x,t.x,e.x),this.y=ge(this.y,t.y,e.y),this.z=ge(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=ge(this.x,t,e),this.y=ge(this.y,t,e),this.z=ge(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(ge(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,n=t.y,s=t.z,r=e.x,a=e.y,c=e.z;return this.x=n*c-s*a,this.y=s*r-i*c,this.z=i*a-n*r,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return hg.copy(this).projectOnVector(t),this.sub(hg)}reflect(t){return this.sub(hg.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ge(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const n=Math.sin(e)*t;return this.x=n*Math.sin(i),this.y=Math.cos(e)*t,this.z=n*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const hg=new T,_w=new es;class de{static{de.prototype.isMatrix3=!0}constructor(t,e,i,n,s,r,a,c,l){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l)}set(t,e,i,n,s,r,a,c,l){const h=this.elements;return h[0]=t,h[1]=n,h[2]=a,h[3]=e,h[4]=s,h[5]=c,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[3],c=i[6],l=i[1],h=i[4],u=i[7],d=i[2],f=i[5],p=i[8],m=n[0],g=n[3],v=n[6],M=n[1],w=n[4],y=n[7],x=n[2],b=n[5],E=n[8];return s[0]=r*m+a*M+c*x,s[3]=r*g+a*w+c*b,s[6]=r*v+a*y+c*E,s[1]=l*m+h*M+u*x,s[4]=l*g+h*w+u*b,s[7]=l*v+h*y+u*E,s[2]=d*m+f*M+p*x,s[5]=d*g+f*w+p*b,s[8]=d*v+f*y+p*E,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8];return e*r*h-e*a*l-i*s*h+i*a*c+n*s*l-n*r*c}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=h*r-a*l,d=a*c-h*s,f=l*s-r*c,p=e*u+i*d+n*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=u*m,t[1]=(n*l-h*i)*m,t[2]=(a*i-n*r)*m,t[3]=d*m,t[4]=(h*e-n*c)*m,t[5]=(n*s-a*e)*m,t[6]=f*m,t[7]=(i*c-l*e)*m,t[8]=(r*e-i*s)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,n,s,r,a){const c=Math.cos(s),l=Math.sin(s);return this.set(i*c,i*l,-i*(c*r+l*a)+r+t,-n*l,n*c,-n*(-l*r+c*a)+a+e,0,0,1),this}scale(t,e){return Jh("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(ug.makeScale(t,e)),this}rotate(t){return Jh("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(ug.makeRotation(-t)),this}translate(t,e){return Jh("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(ug.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<9;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new this.constructor().fromArray(this.elements)}}const ug=new de,Tw=new de().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Rw=new de().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function gR(){const o={enabled:!0,workingColorSpace:G0,spaces:{},convert:function(n,s,r){return this.enabled===!1||s===r||!s||!r||(this.spaces[s].transfer===ui&&(n.r=wo(n.r),n.g=wo(n.g),n.b=wo(n.b)),this.spaces[s].primaries!==this.spaces[r].primaries&&(n.applyMatrix3(this.spaces[s].toXYZ),n.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===ui&&(n.r=jh(n.r),n.g=jh(n.g),n.b=jh(n.b))),n},workingToColorSpace:function(n,s){return this.convert(n,this.workingColorSpace,s)},colorSpaceToWorking:function(n,s){return this.convert(n,s,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===tc?V0:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,s=this.workingColorSpace){return n.fromArray(this.spaces[s].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,s,r){return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,s){return Jh("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),o.workingToColorSpace(n,s)},toWorkingColorSpace:function(n,s){return Jh("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),o.colorSpaceToWorking(n,s)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],i=[.3127,.329];return o.define({[G0]:{primaries:t,whitePoint:i,transfer:V0,toXYZ:Tw,fromXYZ:Rw,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:Bn},outputColorSpaceConfig:{drawingBufferColorSpace:Bn}},[Bn]:{primaries:t,whitePoint:i,transfer:ui,toXYZ:Tw,fromXYZ:Rw,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:Bn}}}),o}const He=gR();function wo(o){return o<.04045?o*.0773993808:Math.pow(o*.9478672986+.0521327014,2.4)}function jh(o){return o<.0031308?o*12.92:1.055*Math.pow(o,.41666)-.055}let Nl;class vR{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{Nl===void 0&&(Nl=hf("canvas")),Nl.width=t.width,Nl.height=t.height;const n=Nl.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),i=Nl}return i.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=hf("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const n=i.getImageData(0,0,t.width,t.height),s=n.data;for(let r=0;r<s.length;r++)s[r]=wo(s[r]/255)*255;return i.putImageData(n,0,0),e}else if(t.data){const e=t.data.slice(0);for(let i=0;i<e.length;i++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[i]=Math.floor(wo(e[i]/255)*255):e[i]=wo(e[i]);return{data:e,width:t.width,height:t.height}}else return Ht("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let MR=0;class vy{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:MR++}),this.uuid=Ar(),this.data=t,this.dataReady=!0,this.version=0}getSize(t){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?t.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?t.set(e.displayWidth,e.displayHeight,0):e!==null?t.set(e.width,e.height,e.depth||0):t.set(0,0,0),t}set needsUpdate(t){t===!0&&this.version++}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.images[this.uuid]!==void 0)return t.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let s;if(Array.isArray(n)){s=[];for(let r=0,a=n.length;r<a;r++)n[r].isDataTexture?s.push(dg(n[r].image)):s.push(dg(n[r]))}else s=dg(n);i.url=s}return e||(t.images[this.uuid]=i),i}}function dg(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap?vR.getDataURL(o):o.data?{data:Array.from(o.data),width:o.width,height:o.height,type:o.data.constructor.name}:(Ht("Texture: Unable to serialize Texture."),{})}let yR=0;const fg=new T;class Wn extends _c{constructor(t=Wn.DEFAULT_IMAGE,e=Wn.DEFAULT_MAPPING,i=Qi,n=Qi,s=Me,r=cr,a=tn,c=fs,l=Wn.DEFAULT_ANISOTROPY,h=tc){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:yR++}),this.uuid=Ar(),this.name="",this.source=new vy(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new tt(0,0),this.repeat=new tt(1,1),this.center=new tt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new de,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(fg).x}get height(){return this.source.getSize(fg).y}get depth(){return this.source.getSize(fg).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(i===void 0){Ht(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Ht(`Texture.setValues(): property '${e}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==jE)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case bc:t.x=t.x-Math.floor(t.x);break;case Qi:t.x=t.x<0?0:1;break;case wv:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case bc:t.y=t.y-Math.floor(t.y);break;case Qi:t.y=t.y<0?0:1;break;case wv:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}}Wn.DEFAULT_IMAGE=null;Wn.DEFAULT_MAPPING=jE;Wn.DEFAULT_ANISOTROPY=1;class Ie{static{Ie.prototype.isVector4=!0}constructor(t=0,e=0,i=0,n=1){this.x=t,this.y=e,this.z=i,this.w=n}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,n,s;const c=t.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],p=c[9],m=c[2],g=c[6],v=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(p-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(p+g)<.1&&Math.abs(l+f+v-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const w=(l+1)/2,y=(f+1)/2,x=(v+1)/2,b=(h+d)/4,E=(u+m)/4,S=(p+g)/4;return w>y&&w>x?w<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(w),n=b/i,s=E/i):y>x?y<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(y),i=b/n,s=S/n):x<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(x),i=E/s,n=S/s),this.set(i,n,s,e),this}let M=Math.sqrt((g-p)*(g-p)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(M)<.001&&(M=1),this.x=(g-p)/M,this.y=(u-m)/M,this.z=(d-h)/M,this.w=Math.acos((l+f+v-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=ge(this.x,t.x,e.x),this.y=ge(this.y,t.y,e.y),this.z=ge(this.z,t.z,e.z),this.w=ge(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=ge(this.x,t,e),this.y=ge(this.y,t,e),this.z=ge(this.z,t,e),this.w=ge(this.w,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(ge(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class wR extends _c{constructor(t=1,e=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Me,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=i.depth,this.scissor=new Ie(0,0,t,e),this.scissorTest=!1,this.viewport=new Ie(0,0,t,e),this.textures=[];const n={width:t,height:e,depth:i.depth},s=new Wn(n),r=i.count;for(let a=0;a<r;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(t={}){const e={minFilter:Me,generateMipmaps:!1,flipY:!1,internalFormat:null};t.mapping!==void 0&&(e.mapping=t.mapping),t.wrapS!==void 0&&(e.wrapS=t.wrapS),t.wrapT!==void 0&&(e.wrapT=t.wrapT),t.wrapR!==void 0&&(e.wrapR=t.wrapR),t.magFilter!==void 0&&(e.magFilter=t.magFilter),t.minFilter!==void 0&&(e.minFilter=t.minFilter),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.anisotropy!==void 0&&(e.anisotropy=t.anisotropy),t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),t.internalFormat!==void 0&&(e.internalFormat=t.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(e)}get texture(){return this.textures[0]}set texture(t){this.textures[0]=t}set depthTexture(t){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),t!==null&&(t.renderTarget=this),this._depthTexture=t}get depthTexture(){return this._depthTexture}setSize(t,e,i=1){if(this.width!==t||this.height!==e||this.depth!==i){this.width=t,this.height=e,this.depth=i;for(let n=0,s=this.textures.length;n<s;n++)this.textures[n].image.width=t,this.textures[n].image.height=e,this.textures[n].image.depth=i,this.textures[n].isData3DTexture!==!0&&(this.textures[n].isArrayTexture=this.textures[n].image.depth>1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,i=t.textures.length;e<i;e++){this.textures[e]=t.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;const n=Object.assign({},t.textures[e].image);this.textures[e].source=new vy(n)}return this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.resolveDepthBuffer=t.resolveDepthBuffer,this.resolveStencilBuffer=t.resolveStencilBuffer,t.depthTexture!==null&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this.multiview=t.multiview,this.useArrayDepthTexture=t.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Qe extends wR{constructor(t=1,e=1,i={}){super(t,e,i),this.isWebGLRenderTarget=!0}}class oA extends Wn{constructor(t=null,e=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=si,this.minFilter=si,this.wrapR=Qi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class cA extends Wn{constructor(t=null,e=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=si,this.minFilter=si,this.wrapR=Qi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Gt{static{Gt.prototype.isMatrix4=!0}constructor(t,e,i,n,s,r,a,c,l,h,u,d,f,p,m,g){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,m,g)}set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,m,g){const v=this.elements;return v[0]=t,v[4]=e,v[8]=i,v[12]=n,v[1]=s,v[5]=r,v[9]=a,v[13]=c,v[2]=l,v[6]=h,v[10]=u,v[14]=d,v[3]=f,v[7]=p,v[11]=m,v[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Gt().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return this.determinantAffine()===0?(t.set(1,0,0),e.set(0,1,0),i.set(0,0,1),this):(t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){if(t.determinantAffine()===0)return this.identity();const e=this.elements,i=t.elements,n=1/Ll.setFromMatrixColumn(t,0).length(),s=1/Ll.setFromMatrixColumn(t,1).length(),r=1/Ll.setFromMatrixColumn(t,2).length();return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=0,e[4]=i[4]*s,e[5]=i[5]*s,e[6]=i[6]*s,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,n=t.y,s=t.z,r=Math.cos(i),a=Math.sin(i),c=Math.cos(n),l=Math.sin(n),h=Math.cos(s),u=Math.sin(s);if(t.order==="XYZ"){const d=r*h,f=r*u,p=a*h,m=a*u;e[0]=c*h,e[4]=-c*u,e[8]=l,e[1]=f+p*l,e[5]=d-m*l,e[9]=-a*c,e[2]=m-d*l,e[6]=p+f*l,e[10]=r*c}else if(t.order==="YXZ"){const d=c*h,f=c*u,p=l*h,m=l*u;e[0]=d+m*a,e[4]=p*a-f,e[8]=r*l,e[1]=r*u,e[5]=r*h,e[9]=-a,e[2]=f*a-p,e[6]=m+d*a,e[10]=r*c}else if(t.order==="ZXY"){const d=c*h,f=c*u,p=l*h,m=l*u;e[0]=d-m*a,e[4]=-r*u,e[8]=p+f*a,e[1]=f+p*a,e[5]=r*h,e[9]=m-d*a,e[2]=-r*l,e[6]=a,e[10]=r*c}else if(t.order==="ZYX"){const d=r*h,f=r*u,p=a*h,m=a*u;e[0]=c*h,e[4]=p*l-f,e[8]=d*l+m,e[1]=c*u,e[5]=m*l+d,e[9]=f*l-p,e[2]=-l,e[6]=a*c,e[10]=r*c}else if(t.order==="YZX"){const d=r*c,f=r*l,p=a*c,m=a*l;e[0]=c*h,e[4]=m-d*u,e[8]=p*u+f,e[1]=u,e[5]=r*h,e[9]=-a*h,e[2]=-l*h,e[6]=f*u+p,e[10]=d-m*u}else if(t.order==="XZY"){const d=r*c,f=r*l,p=a*c,m=a*l;e[0]=c*h,e[4]=-u,e[8]=l*h,e[1]=d*u+m,e[5]=r*h,e[9]=f*u-p,e[2]=p*u-f,e[6]=a*h,e[10]=m*u+d}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(xR,t,bR)}lookAt(t,e,i){const n=this.elements;return Js.subVectors(t,e),Js.lengthSq()===0&&(Js.z=1),Js.normalize(),Oo.crossVectors(i,Js),Oo.lengthSq()===0&&(Math.abs(i.z)===1?Js.x+=1e-4:Js.z+=1e-4,Js.normalize(),Oo.crossVectors(i,Js)),Oo.normalize(),Bf.crossVectors(Js,Oo),n[0]=Oo.x,n[4]=Bf.x,n[8]=Js.x,n[1]=Oo.y,n[5]=Bf.y,n[9]=Js.y,n[2]=Oo.z,n[6]=Bf.z,n[10]=Js.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[4],c=i[8],l=i[12],h=i[1],u=i[5],d=i[9],f=i[13],p=i[2],m=i[6],g=i[10],v=i[14],M=i[3],w=i[7],y=i[11],x=i[15],b=n[0],E=n[4],S=n[8],A=n[12],_=n[1],I=n[5],D=n[9],O=n[13],P=n[2],N=n[6],k=n[10],B=n[14],W=n[3],Q=n[7],Z=n[11],nt=n[15];return s[0]=r*b+a*_+c*P+l*W,s[4]=r*E+a*I+c*N+l*Q,s[8]=r*S+a*D+c*k+l*Z,s[12]=r*A+a*O+c*B+l*nt,s[1]=h*b+u*_+d*P+f*W,s[5]=h*E+u*I+d*N+f*Q,s[9]=h*S+u*D+d*k+f*Z,s[13]=h*A+u*O+d*B+f*nt,s[2]=p*b+m*_+g*P+v*W,s[6]=p*E+m*I+g*N+v*Q,s[10]=p*S+m*D+g*k+v*Z,s[14]=p*A+m*O+g*B+v*nt,s[3]=M*b+w*_+y*P+x*W,s[7]=M*E+w*I+y*N+x*Q,s[11]=M*S+w*D+y*k+x*Z,s[15]=M*A+w*O+y*B+x*nt,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[12],r=t[1],a=t[5],c=t[9],l=t[13],h=t[2],u=t[6],d=t[10],f=t[14],p=t[3],m=t[7],g=t[11],v=t[15],M=c*f-l*d,w=a*f-l*u,y=a*d-c*u,x=r*f-l*h,b=r*d-c*h,E=r*u-a*h;return e*(m*M-g*w+v*y)-i*(p*M-g*x+v*b)+n*(p*w-m*x+v*E)-s*(p*y-m*b+g*E)}determinantAffine(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[1],r=t[5],a=t[9],c=t[2],l=t[6],h=t[10];return e*(r*h-a*l)-i*(s*h-a*c)+n*(s*l-r*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const n=this.elements;return t.isVector3?(n[12]=t.x,n[13]=t.y,n[14]=t.z):(n[12]=t,n[13]=e,n[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=t[9],d=t[10],f=t[11],p=t[12],m=t[13],g=t[14],v=t[15],M=e*a-i*r,w=e*c-n*r,y=e*l-s*r,x=i*c-n*a,b=i*l-s*a,E=n*l-s*c,S=h*m-u*p,A=h*g-d*p,_=h*v-f*p,I=u*g-d*m,D=u*v-f*m,O=d*v-f*g,P=M*O-w*D+y*I+x*_-b*A+E*S;if(P===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const N=1/P;return t[0]=(a*O-c*D+l*I)*N,t[1]=(n*D-i*O-s*I)*N,t[2]=(m*E-g*b+v*x)*N,t[3]=(d*b-u*E-f*x)*N,t[4]=(c*_-r*O-l*A)*N,t[5]=(e*O-n*_+s*A)*N,t[6]=(g*y-p*E-v*w)*N,t[7]=(h*E-d*y+f*w)*N,t[8]=(r*D-a*_+l*S)*N,t[9]=(i*_-e*D-s*S)*N,t[10]=(p*b-m*y+v*M)*N,t[11]=(u*y-h*b-f*M)*N,t[12]=(a*A-r*I-c*S)*N,t[13]=(e*I-i*A+n*S)*N,t[14]=(m*w-p*x-g*M)*N,t[15]=(h*x-u*w+d*M)*N,this}scale(t){const e=this.elements,i=t.x,n=t.y,s=t.z;return e[0]*=i,e[4]*=n,e[8]*=s,e[1]*=i,e[5]*=n,e[9]*=s,e[2]*=i,e[6]*=n,e[10]*=s,e[3]*=i,e[7]*=n,e[11]*=s,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],n=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,n))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,a=t.y,c=t.z,l=s*r,h=s*a;return this.set(l*r+i,l*a-n*c,l*c+n*a,0,l*a+n*c,h*a+i,h*c-n*r,0,l*c-n*a,h*c+n*r,s*c*c+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,n,s,r){return this.set(1,i,s,0,t,1,r,0,e,n,1,0,0,0,0,1),this}compose(t,e,i){const n=this.elements,s=e._x,r=e._y,a=e._z,c=e._w,l=s+s,h=r+r,u=a+a,d=s*l,f=s*h,p=s*u,m=r*h,g=r*u,v=a*u,M=c*l,w=c*h,y=c*u,x=i.x,b=i.y,E=i.z;return n[0]=(1-(m+v))*x,n[1]=(f+y)*x,n[2]=(p-w)*x,n[3]=0,n[4]=(f-y)*b,n[5]=(1-(d+v))*b,n[6]=(g+M)*b,n[7]=0,n[8]=(p+w)*E,n[9]=(g-M)*E,n[10]=(1-(d+m))*E,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this}decompose(t,e,i){const n=this.elements;t.x=n[12],t.y=n[13],t.z=n[14];const s=this.determinantAffine();if(s===0)return i.set(1,1,1),e.identity(),this;let r=Ll.set(n[0],n[1],n[2]).length();const a=Ll.set(n[4],n[5],n[6]).length(),c=Ll.set(n[8],n[9],n[10]).length();s<0&&(r=-r),Ir.copy(this);const l=1/r,h=1/a,u=1/c;return Ir.elements[0]*=l,Ir.elements[1]*=l,Ir.elements[2]*=l,Ir.elements[4]*=h,Ir.elements[5]*=h,Ir.elements[6]*=h,Ir.elements[8]*=u,Ir.elements[9]*=u,Ir.elements[10]*=u,e.setFromRotationMatrix(Ir),i.x=r,i.y=a,i.z=c,this}makePerspective(t,e,i,n,s,r,a=Ca,c=!1){const l=this.elements,h=2*s/(e-t),u=2*s/(i-n),d=(e+t)/(e-t),f=(i+n)/(i-n);let p,m;if(c)p=s/(r-s),m=r*s/(r-s);else if(a===Ca)p=-(r+s)/(r-s),m=-2*r*s/(r-s);else if(a===lf)p=-r/(r-s),m=-r*s/(r-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,i,n,s,r,a=Ca,c=!1){const l=this.elements,h=2/(e-t),u=2/(i-n),d=-(e+t)/(e-t),f=-(i+n)/(i-n);let p,m;if(c)p=1/(r-s),m=r/(r-s);else if(a===Ca)p=-2/(r-s),m=-(r+s)/(r-s);else if(a===lf)p=-1/(r-s),m=-s/(r-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=0,l[12]=d,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<16;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const Ll=new T,Ir=new Gt,xR=new T(0,0,0),bR=new T(1,1,1),Oo=new T,Bf=new T,Js=new T,Iw=new Gt,Dw=new es;class Yr{constructor(t=0,e=0,i=0,n=Yr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=n}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,n=this._order){return this._x=t,this._y=e,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const n=t.elements,s=n[0],r=n[4],a=n[8],c=n[1],l=n[5],h=n[9],u=n[2],d=n[6],f=n[10];switch(e){case"XYZ":this._y=Math.asin(ge(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-r,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-ge(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(ge(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-ge(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(ge(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-ge(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-h,f),this._y=0);break;default:Ht("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return Iw.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Iw,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return Dw.setFromEuler(this),this.setFromQuaternion(Dw,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Yr.DEFAULT_ORDER="XYZ";class My{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return(this.mask&t.mask)!==0}isEnabled(t){return(this.mask&(1<<t|0))!==0}}let SR=0;const Cw=new T,kl=new es,Wa=new Gt,Hf=new T,Cu=new T,ER=new T,AR=new es,Ow=new T(1,0,0),Pw=new T(0,1,0),Nw=new T(0,0,1),Lw={type:"added"},_R={type:"removed"},Fl={type:"childadded",child:null},pg={type:"childremoved",child:null};class Bi extends _c{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:SR++}),this.uuid=Ar(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Bi.DEFAULT_UP.clone();const t=new T,e=new Yr,i=new es,n=new T(1,1,1);function s(){i.setFromEuler(e,!1)}function r(){e.setFromQuaternion(i,void 0,!1)}e._onChange(s),i._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new Gt},normalMatrix:{value:new de}}),this.matrix=new Gt,this.matrixWorld=new Gt,this.matrixAutoUpdate=Bi.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new My,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return kl.setFromAxisAngle(t,e),this.quaternion.multiply(kl),this}rotateOnWorldAxis(t,e){return kl.setFromAxisAngle(t,e),this.quaternion.premultiply(kl),this}rotateX(t){return this.rotateOnAxis(Ow,t)}rotateY(t){return this.rotateOnAxis(Pw,t)}rotateZ(t){return this.rotateOnAxis(Nw,t)}translateOnAxis(t,e){return Cw.copy(t).applyQuaternion(this.quaternion),this.position.add(Cw.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Ow,t)}translateY(t){return this.translateOnAxis(Pw,t)}translateZ(t){return this.translateOnAxis(Nw,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(Wa.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?Hf.copy(t):Hf.set(t,e,i);const n=this.parent;this.updateWorldMatrix(!0,!1),Cu.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Wa.lookAt(Cu,Hf,this.up):Wa.lookAt(Hf,Cu,this.up),this.quaternion.setFromRotationMatrix(Wa),n&&(Wa.extractRotation(n.matrixWorld),kl.setFromRotationMatrix(Wa),this.quaternion.premultiply(kl.invert()))}add(t){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return t===this?(le("Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Lw),Fl.child=t,this.dispatchEvent(Fl),Fl.child=null):le("Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const e=this.children.indexOf(t);return e!==-1&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(_R),pg.child=t,this.dispatchEvent(pg),pg.child=null),this}removeFromParent(){const t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),Wa.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),Wa.multiply(t.parent.matrixWorld)),t.applyMatrix4(Wa),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Lw),Fl.child=t,this.dispatchEvent(Fl),Fl.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,n=this.children.length;i<n;i++){const r=this.children[i].getObjectByProperty(t,e);if(r!==void 0)return r}}getObjectsByProperty(t,e,i=[]){this[t]===e&&i.push(this);const n=this.children;for(let s=0,r=n.length;s<r;s++)n[s].getObjectsByProperty(t,e,i);return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Cu,t,ER),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Cu,AR,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;e!==null&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const t=this.pivot;if(t!==null){const e=t.x,i=t.y,n=t.z,s=this.matrix.elements;s[12]+=e-s[0]*e-s[4]*i-s[8]*n,s[13]+=i-s[1]*e-s[5]*i-s[9]*n,s[14]+=n-s[2]*e-s[6]*i-s[10]*n}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].updateMatrixWorld(t)}updateWorldMatrix(t,e,i=!1){const n=this.parent;if(t===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),e===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0,i)}}toJSON(t){const e=t===void 0||typeof t=="string",i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),this.static!==!1&&(n.static=this.static),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.pivot!==null&&(n.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(a=>({...a})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(t),n.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(t)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(t.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){const u=c[l];s(t.shapes,u)}else s(t.shapes,c)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(t.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(s(t.materials,this.material[c]));n.material=a}else n.material=s(t.materials,this.material);if(this.children.length>0){n.children=[];for(let a=0;a<this.children.length;a++)n.children.push(this.children[a].toJSON(t).object)}if(this.animations.length>0){n.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];n.animations.push(s(t.animations,c))}}if(e){const a=r(t.geometries),c=r(t.materials),l=r(t.textures),h=r(t.images),u=r(t.shapes),d=r(t.skeletons),f=r(t.animations),p=r(t.nodes);a.length>0&&(i.geometries=a),c.length>0&&(i.materials=c),l.length>0&&(i.textures=l),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=n,i;function r(a){const c=[];for(const l in a){const h=a[l];delete h.metadata,c.push(h)}return c}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let i=0;i<t.children.length;i++){const n=t.children[i];this.add(n.clone())}return this}}Bi.DEFAULT_UP=new T(0,1,0);Bi.DEFAULT_MATRIX_AUTO_UPDATE=!0;Bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Ke extends Bi{constructor(){super(),this.isGroup=!0,this.type="Group"}}const TR={type:"move"};class mg{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Ke,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Ke,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new T,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new T),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Ke,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new T,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new T,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,i){let n=null,s=null,r=null;const a=this._targetRay,c=this._grip,l=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(l&&t.hand){r=!0;for(const m of t.hand.values()){const g=e.getJointPose(m,i),v=this._getHandJoint(l,m);g!==null&&(v.matrix.fromArray(g.transform.matrix),v.matrix.decompose(v.position,v.rotation,v.scale),v.matrixWorldNeedsUpdate=!0,v.jointRadius=g.radius),v.visible=g!==null}const h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;l.inputState.pinching&&d>f+p?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&d<=f-p&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else c!==null&&t.gripSpace&&(s=e.getPose(t.gripSpace,i),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1,c.eventsEnabled&&c.dispatchEvent({type:"gripUpdated",data:t,target:this})));a!==null&&(n=e.getPose(t.targetRaySpace,i),n===null&&s!==null&&(n=s),n!==null&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(TR)))}return a!==null&&(a.visible=n!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=r!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){const i=new Ke;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}const lA={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Po={h:0,s:0,l:0},Gf={h:0,s:0,l:0};function gg(o,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+(t-o)*6*e:e<1/2?t:e<2/3?o+(t-o)*6*(2/3-e):o}class rt{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(e===void 0&&i===void 0){const n=t;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Bn){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,He.colorSpaceToWorking(this,e),this}setRGB(t,e,i,n=He.workingColorSpace){return this.r=t,this.g=e,this.b=i,He.colorSpaceToWorking(this,n),this}setHSL(t,e,i,n=He.workingColorSpace){if(t=gy(t,1),e=ge(e,0,1),i=ge(i,0,1),e===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,r=2*i-s;this.r=gg(r,s,t+1/3),this.g=gg(r,s,t),this.b=gg(r,s,t-1/3)}return He.colorSpaceToWorking(this,n),this}setStyle(t,e=Bn){function i(s){s!==void 0&&parseFloat(s)<1&&Ht("Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(t)){let s;const r=n[1],a=n[2];switch(r){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,e);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,e);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,e);break;default:Ht("Color: Unknown color model "+t)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const s=n[1],r=s.length;if(r===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,e);if(r===6)return this.setHex(parseInt(s,16),e);Ht("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Bn){const i=lA[t.toLowerCase()];return i!==void 0?this.setHex(i,e):Ht("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=wo(t.r),this.g=wo(t.g),this.b=wo(t.b),this}copyLinearToSRGB(t){return this.r=jh(t.r),this.g=jh(t.g),this.b=jh(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Bn){return He.workingToColorSpace(ss.copy(this),t),Math.round(ge(ss.r*255,0,255))*65536+Math.round(ge(ss.g*255,0,255))*256+Math.round(ge(ss.b*255,0,255))}getHexString(t=Bn){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=He.workingColorSpace){He.workingToColorSpace(ss.copy(this),e);const i=ss.r,n=ss.g,s=ss.b,r=Math.max(i,n,s),a=Math.min(i,n,s);let c,l;const h=(a+r)/2;if(a===r)c=0,l=0;else{const u=r-a;switch(l=h<=.5?u/(r+a):u/(2-r-a),r){case i:c=(n-s)/u+(n<s?6:0);break;case n:c=(s-i)/u+2;break;case s:c=(i-n)/u+4;break}c/=6}return t.h=c,t.s=l,t.l=h,t}getRGB(t,e=He.workingColorSpace){return He.workingToColorSpace(ss.copy(this),e),t.r=ss.r,t.g=ss.g,t.b=ss.b,t}getStyle(t=Bn){He.workingToColorSpace(ss.copy(this),t);const e=ss.r,i=ss.g,n=ss.b;return t!==Bn?`color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(t,e,i){return this.getHSL(Po),this.setHSL(Po.h+t,Po.s+e,Po.l+i)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,i){return this.r=t.r+(e.r-t.r)*i,this.g=t.g+(e.g-t.g)*i,this.b=t.b+(e.b-t.b)*i,this}lerpHSL(t,e){this.getHSL(Po),t.getHSL(Gf);const i=pd(Po.h,Gf.h,e),n=pd(Po.s,Gf.s,e),s=pd(Po.l,Gf.l,e);return this.setHSL(i,n,s),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,i=this.g,n=this.b,s=t.elements;return this.r=s[0]*e+s[3]*i+s[6]*n,this.g=s[1]*e+s[4]*i+s[7]*n,this.b=s[2]*e+s[5]*i+s[8]*n,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const ss=new rt;rt.NAMES=lA;class yy{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new rt(t),this.near=e,this.far=i}clone(){return new yy(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class hr extends Bi{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Yr,this.environmentIntensity=1,this.environmentRotation=new Yr,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const Dr=new T,Xa=new T,vg=new T,$a=new T,Ul=new T,zl=new T,kw=new T,Mg=new T,yg=new T,wg=new T,xg=new Ie,bg=new Ie,Sg=new Ie;class Hn{constructor(t=new T,e=new T,i=new T){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,n){n.subVectors(i,e),Dr.subVectors(t,e),n.cross(Dr);const s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(t,e,i,n,s){Dr.subVectors(n,e),Xa.subVectors(i,e),vg.subVectors(t,e);const r=Dr.dot(Dr),a=Dr.dot(Xa),c=Dr.dot(vg),l=Xa.dot(Xa),h=Xa.dot(vg),u=r*l-a*a;if(u===0)return s.set(0,0,0),null;const d=1/u,f=(l*c-a*h)*d,p=(r*h-a*c)*d;return s.set(1-f-p,p,f)}static containsPoint(t,e,i,n){return this.getBarycoord(t,e,i,n,$a)===null?!1:$a.x>=0&&$a.y>=0&&$a.x+$a.y<=1}static getInterpolation(t,e,i,n,s,r,a,c){return this.getBarycoord(t,e,i,n,$a)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,$a.x),c.addScaledVector(r,$a.y),c.addScaledVector(a,$a.z),c)}static getInterpolatedAttribute(t,e,i,n,s,r){return xg.setScalar(0),bg.setScalar(0),Sg.setScalar(0),xg.fromBufferAttribute(t,e),bg.fromBufferAttribute(t,i),Sg.fromBufferAttribute(t,n),r.setScalar(0),r.addScaledVector(xg,s.x),r.addScaledVector(bg,s.y),r.addScaledVector(Sg,s.z),r}static isFrontFacing(t,e,i,n){return Dr.subVectors(i,e),Xa.subVectors(t,e),Dr.cross(Xa).dot(n)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this}setFromAttributeAndIndices(t,e,i,n){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,n),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Dr.subVectors(this.c,this.b),Xa.subVectors(this.a,this.b),Dr.cross(Xa).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Hn.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Hn.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,n,s){return Hn.getInterpolation(t,this.a,this.b,this.c,e,i,n,s)}containsPoint(t){return Hn.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Hn.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,n=this.b,s=this.c;let r,a;Ul.subVectors(n,i),zl.subVectors(s,i),Mg.subVectors(t,i);const c=Ul.dot(Mg),l=zl.dot(Mg);if(c<=0&&l<=0)return e.copy(i);yg.subVectors(t,n);const h=Ul.dot(yg),u=zl.dot(yg);if(h>=0&&u<=h)return e.copy(n);const d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return r=c/(c-h),e.copy(i).addScaledVector(Ul,r);wg.subVectors(t,s);const f=Ul.dot(wg),p=zl.dot(wg);if(p>=0&&f<=p)return e.copy(s);const m=f*l-c*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(zl,a);const g=h*p-f*u;if(g<=0&&u-h>=0&&f-p>=0)return kw.subVectors(s,n),a=(u-h)/(u-h+(f-p)),e.copy(n).addScaledVector(kw,a);const v=1/(g+m+d);return r=m*v,a=d*v,e.copy(i).addScaledVector(Ul,r).addScaledVector(zl,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class Je{constructor(t=new T(1/0,1/0,1/0),e=new T(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(Cr.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(Cr.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=Cr.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const i=t.geometry;if(i!==void 0){const s=i.getAttribute("position");if(e===!0&&s!==void 0&&t.isInstancedMesh!==!0)for(let r=0,a=s.count;r<a;r++)t.isMesh===!0?t.getVertexPosition(r,Cr):Cr.fromBufferAttribute(s,r),Cr.applyMatrix4(t.matrixWorld),this.expandByPoint(Cr);else t.boundingBox!==void 0?(t.boundingBox===null&&t.computeBoundingBox(),Vf.copy(t.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Vf.copy(i.boundingBox)),Vf.applyMatrix4(t.matrixWorld),this.union(Vf)}const n=t.children;for(let s=0,r=n.length;s<r;s++)this.expandByObject(n[s],e);return this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,Cr),Cr.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Ou),Wf.subVectors(this.max,Ou),Bl.subVectors(t.a,Ou),Hl.subVectors(t.b,Ou),Gl.subVectors(t.c,Ou),No.subVectors(Hl,Bl),Lo.subVectors(Gl,Hl),Ic.subVectors(Bl,Gl);let e=[0,-No.z,No.y,0,-Lo.z,Lo.y,0,-Ic.z,Ic.y,No.z,0,-No.x,Lo.z,0,-Lo.x,Ic.z,0,-Ic.x,-No.y,No.x,0,-Lo.y,Lo.x,0,-Ic.y,Ic.x,0];return!Eg(e,Bl,Hl,Gl,Wf)||(e=[1,0,0,0,1,0,0,0,1],!Eg(e,Bl,Hl,Gl,Wf))?!1:(Xf.crossVectors(No,Lo),e=[Xf.x,Xf.y,Xf.z],Eg(e,Bl,Hl,Gl,Wf))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Cr).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(Cr).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Ya[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Ya[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Ya[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Ya[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Ya[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Ya[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Ya[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Ya[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Ya),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Ya=[new T,new T,new T,new T,new T,new T,new T,new T],Cr=new T,Vf=new Je,Bl=new T,Hl=new T,Gl=new T,No=new T,Lo=new T,Ic=new T,Ou=new T,Wf=new T,Xf=new T,Dc=new T;function Eg(o,t,e,i,n){for(let s=0,r=o.length-3;s<=r;s+=3){Dc.fromArray(o,s);const a=n.x*Math.abs(Dc.x)+n.y*Math.abs(Dc.y)+n.z*Math.abs(Dc.z),c=t.dot(Dc),l=e.dot(Dc),h=i.dot(Dc);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}const oo=RR();function RR(){const o=new ArrayBuffer(4),t=new Float32Array(o),e=new Uint32Array(o),i=new Uint32Array(512),n=new Uint32Array(512);for(let c=0;c<256;++c){const l=c-127;l<-27?(i[c]=0,i[c|256]=32768,n[c]=24,n[c|256]=24):l<-14?(i[c]=1024>>-l-14,i[c|256]=1024>>-l-14|32768,n[c]=-l-1,n[c|256]=-l-1):l<=15?(i[c]=l+15<<10,i[c|256]=l+15<<10|32768,n[c]=13,n[c|256]=13):l<128?(i[c]=31744,i[c|256]=64512,n[c]=24,n[c|256]=24):(i[c]=31744,i[c|256]=64512,n[c]=13,n[c|256]=13)}const s=new Uint32Array(2048),r=new Uint32Array(64),a=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,s[c]=l|h}for(let c=1024;c<2048;++c)s[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)r[c]=c<<23;r[31]=1199570944,r[32]=2147483648;for(let c=33;c<63;++c)r[c]=2147483648+(c-32<<23);r[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(a[c]=1024);return{floatView:t,uint32View:e,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:r,offsetTable:a}}function IR(o){Math.abs(o)>65504&&Ht("DataUtils.toHalfFloat(): Value out of range."),o=ge(o,-65504,65504),oo.floatView[0]=o;const t=oo.uint32View[0],e=t>>23&511;return oo.baseTable[e]+((t&8388607)>>oo.shiftTable[e])}function DR(o){const t=o>>10;return oo.uint32View[0]=oo.mantissaTable[oo.offsetTable[t]+(o&1023)]+oo.exponentTable[t],oo.floatView[0]}class Gn{static toHalfFloat(t){return IR(t)}static fromHalfFloat(t){return DR(t)}}const dn=new T,$f=new tt;let CR=0;class we extends _c{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:CR++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=i,this.usage=jv,this.updateRanges=[],this.gpuType=ts,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let n=0,s=this.itemSize;n<s;n++)this.array[t+n]=e.array[i+n];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(this.itemSize===2)for(let e=0,i=this.count;e<i;e++)$f.fromBufferAttribute(this,e),$f.applyMatrix3(t),this.setXY(e,$f.x,$f.y);else if(this.itemSize===3)for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.applyMatrix3(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.applyMatrix4(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.applyNormalMatrix(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)dn.fromBufferAttribute(this,e),dn.transformDirection(t),this.setXYZ(e,dn.x,dn.y,dn.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=Gr(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=di(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=Gr(e,this.array)),e}setX(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=Gr(e,this.array)),e}setY(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=Gr(e,this.array)),e}setZ(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=Gr(e,this.array)),e}setW(t,e){return this.normalized&&(e=di(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=di(e,this.array),i=di(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,n){return t*=this.itemSize,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t*=this.itemSize,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array),s=di(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this.array[t+3]=s,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(t.name=this.name),this.usage!==jv&&(t.usage=this.usage),t}dispose(){this.dispatchEvent({type:"dispose"})}}class hA extends we{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class wy extends we{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class pe extends we{constructor(t,e,i){super(new Float32Array(t),e,i)}}const OR=new Je,Pu=new T,Ag=new T;class Tr{constructor(t=new T,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;e!==void 0?i.copy(e):OR.setFromPoints(t).getCenter(i);let n=0;for(let s=0,r=t.length;s<r;s++)n=Math.max(n,i.distanceToSquared(t[s]));return this.radius=Math.sqrt(n),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Pu.subVectors(t,this.center);const e=Pu.lengthSq();if(e>this.radius*this.radius){const i=Math.sqrt(e),n=(i-this.radius)*.5;this.center.addScaledVector(Pu,n/i),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Ag.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Pu.copy(t.center).add(Ag)),this.expandByPoint(Pu.copy(t.center).sub(Ag))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let PR=0;const fr=new Gt,_g=new Bi,Vl=new T,js=new Je,Nu=new Je,Nn=new T;class be extends _c{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:PR++}),this.uuid=Ar(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(q4(t)?wy:hA)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new de().getNormalMatrix(t);i.applyNormalMatrix(s),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(t),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return fr.makeRotationFromQuaternion(t),this.applyMatrix4(fr),this}rotateX(t){return fr.makeRotationX(t),this.applyMatrix4(fr),this}rotateY(t){return fr.makeRotationY(t),this.applyMatrix4(fr),this}rotateZ(t){return fr.makeRotationZ(t),this.applyMatrix4(fr),this}translate(t,e,i){return fr.makeTranslation(t,e,i),this.applyMatrix4(fr),this}scale(t,e,i){return fr.makeScale(t,e,i),this.applyMatrix4(fr),this}lookAt(t){return _g.lookAt(t),_g.updateMatrix(),this.applyMatrix4(_g.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Vl).negate(),this.translate(Vl.x,Vl.y,Vl.z),this}setFromPoints(t){const e=this.getAttribute("position");if(e===void 0){const i=[];for(let n=0,s=t.length;n<s;n++){const r=t[n];i.push(r.x,r.y,r.z||0)}this.setAttribute("position",new pe(i,3))}else{const i=Math.min(t.length,e.count);for(let n=0;n<i;n++){const s=t[n];e.setXYZ(n,s.x,s.y,s.z||0)}t.length>e.count&&Ht("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Je);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){le("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new T(-1/0,-1/0,-1/0),new T(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let i=0,n=e.length;i<n;i++){const s=e[i];js.setFromBufferAttribute(s),this.morphTargetsRelative?(Nn.addVectors(this.boundingBox.min,js.min),this.boundingBox.expandByPoint(Nn),Nn.addVectors(this.boundingBox.max,js.max),this.boundingBox.expandByPoint(Nn)):(this.boundingBox.expandByPoint(js.min),this.boundingBox.expandByPoint(js.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&le('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Tr);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){le("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new T,1/0);return}if(t){const i=this.boundingSphere.center;if(js.setFromBufferAttribute(t),e)for(let s=0,r=e.length;s<r;s++){const a=e[s];Nu.setFromBufferAttribute(a),this.morphTargetsRelative?(Nn.addVectors(js.min,Nu.min),js.expandByPoint(Nn),Nn.addVectors(js.max,Nu.max),js.expandByPoint(Nn)):(js.expandByPoint(Nu.min),js.expandByPoint(Nu.max))}js.getCenter(i);let n=0;for(let s=0,r=t.count;s<r;s++)Nn.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(Nn));if(e)for(let s=0,r=e.length;s<r;s++){const a=e[s],c=this.morphTargetsRelative;for(let l=0,h=a.count;l<h;l++)Nn.fromBufferAttribute(a,l),c&&(Vl.fromBufferAttribute(t,l),Nn.add(Vl)),n=Math.max(n,i.distanceToSquared(Nn))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&le('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(t===null||e.position===void 0||e.normal===void 0||e.uv===void 0){le("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.position,n=e.normal,s=e.uv;let r=this.getAttribute("tangent");(r===void 0||r.count!==i.count)&&(r=new we(new Float32Array(4*i.count),4),this.setAttribute("tangent",r));const a=[],c=[];for(let S=0;S<i.count;S++)a[S]=new T,c[S]=new T;const l=new T,h=new T,u=new T,d=new tt,f=new tt,p=new tt,m=new T,g=new T;function v(S,A,_){l.fromBufferAttribute(i,S),h.fromBufferAttribute(i,A),u.fromBufferAttribute(i,_),d.fromBufferAttribute(s,S),f.fromBufferAttribute(s,A),p.fromBufferAttribute(s,_),h.sub(l),u.sub(l),f.sub(d),p.sub(d);const I=1/(f.x*p.y-p.x*f.y);isFinite(I)&&(m.copy(h).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(I),g.copy(u).multiplyScalar(f.x).addScaledVector(h,-p.x).multiplyScalar(I),a[S].add(m),a[A].add(m),a[_].add(m),c[S].add(g),c[A].add(g),c[_].add(g))}let M=this.groups;M.length===0&&(M=[{start:0,count:t.count}]);for(let S=0,A=M.length;S<A;++S){const _=M[S],I=_.start,D=_.count;for(let O=I,P=I+D;O<P;O+=3)v(t.getX(O+0),t.getX(O+1),t.getX(O+2))}const w=new T,y=new T,x=new T,b=new T;function E(S){x.fromBufferAttribute(n,S),b.copy(x);const A=a[S];w.copy(A),w.sub(x.multiplyScalar(x.dot(A))).normalize(),y.crossVectors(b,A);const I=y.dot(c[S])<0?-1:1;r.setXYZW(S,w.x,w.y,w.z,I)}for(let S=0,A=M.length;S<A;++S){const _=M[S],I=_.start,D=_.count;for(let O=I,P=I+D;O<P;O+=3)E(t.getX(O+0)),E(t.getX(O+1)),E(t.getX(O+2))}this._transformed=!0}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(e!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==e.count)i=new we(new Float32Array(e.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);const n=new T,s=new T,r=new T,a=new T,c=new T,l=new T,h=new T,u=new T;if(t)for(let d=0,f=t.count;d<f;d+=3){const p=t.getX(d+0),m=t.getX(d+1),g=t.getX(d+2);n.fromBufferAttribute(e,p),s.fromBufferAttribute(e,m),r.fromBufferAttribute(e,g),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),a.fromBufferAttribute(i,p),c.fromBufferAttribute(i,m),l.fromBufferAttribute(i,g),a.add(h),c.add(h),l.add(h),i.setXYZ(p,a.x,a.y,a.z),i.setXYZ(m,c.x,c.y,c.z),i.setXYZ(g,l.x,l.y,l.z)}else for(let d=0,f=e.count;d<f;d+=3)n.fromBufferAttribute(e,d+0),s.fromBufferAttribute(e,d+1),r.fromBufferAttribute(e,d+2),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)Nn.fromBufferAttribute(t,e),Nn.normalize(),t.setXYZ(e,Nn.x,Nn.y,Nn.z)}toNonIndexed(){function t(a,c){const l=a.array,h=a.itemSize,u=a.normalized,d=new l.constructor(c.length*h);let f=0,p=0;for(let m=0,g=c.length;m<g;m++){a.isInterleavedBufferAttribute?f=c[m]*a.data.stride+a.offset:f=c[m]*h;for(let v=0;v<h;v++)d[p++]=l[f++]}return new we(d,h,u)}if(this.index===null)return Ht("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new be,i=this.index.array,n=this.attributes;for(const a in n){const c=n[a],l=t(c,i);e.setAttribute(a,l)}const s=this.morphAttributes;for(const a in s){const c=[],l=s[a];for(let h=0,u=l.length;h<u;h++){const d=l[h],f=t(d,i);c.push(f)}e.morphAttributes[a]=c}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,c=r.length;a<c;a++){const l=r[a];e.addGroup(l.start,l.count,l.materialIndex)}return e}toJSON(){const t={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(t[l]=c[l]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const c in i){const l=i[c];t.data.attributes[c]=l.toJSON(t.data)}const n={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){const f=l[u];h.push(f.toJSON(t.data))}h.length>0&&(n[c]=h,s=!0)}s&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;i!==null&&this.setIndex(i.clone());const n=t.attributes;for(const l in n){const h=n[l];this.setAttribute(l,h.clone(e))}const s=t.morphAttributes;for(const l in s){const h=[],u=s[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(e));this.morphAttributes[l]=h}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let l=0,h=r.length;l<h;l++){const u=r[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=t.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=t.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this._transformed=t._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class uA{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=t!==void 0?t.length/e:0,this.usage=jv,this.updateRanges=[],this.version=0,this.uuid=Ar()}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let n=0,s=this.stride;n<s;n++)this.array[t+n]=e.array[i+n];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ar()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(e,this.stride);return i.setUsage(this.usage),i}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ar()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Ms=new T;class $0{constructor(t,e,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=t,this.itemSize=e,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,i=this.data.count;e<i;e++)Ms.fromBufferAttribute(this,e),Ms.applyMatrix4(t),this.setXYZ(e,Ms.x,Ms.y,Ms.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)Ms.fromBufferAttribute(this,e),Ms.applyNormalMatrix(t),this.setXYZ(e,Ms.x,Ms.y,Ms.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)Ms.fromBufferAttribute(this,e),Ms.transformDirection(t),this.setXYZ(e,Ms.x,Ms.y,Ms.z);return this}getComponent(t,e){let i=this.array[t*this.data.stride+this.offset+e];return this.normalized&&(i=Gr(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=di(i,this.array)),this.data.array[t*this.data.stride+this.offset+e]=i,this}setX(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.normalized&&(e=di(e,this.array)),this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){let e=this.data.array[t*this.data.stride+this.offset];return this.normalized&&(e=Gr(e,this.array)),e}getY(t){let e=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(e=Gr(e,this.array)),e}getZ(t){let e=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(e=Gr(e,this.array)),e}getW(t){let e=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(e=Gr(e,this.array)),e}setXY(t,e,i){return t=t*this.data.stride+this.offset,this.normalized&&(e=di(e,this.array),i=di(i,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this}setXYZ(t,e,i,n){return t=t*this.data.stride+this.offset,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t=t*this.data.stride+this.offset,this.normalized&&(e=di(e,this.array),i=di(i,this.array),n=di(n,this.array),s=di(s,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this.data.array[t+3]=s,this}clone(t){if(t===void 0){X0("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return new we(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new $0(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(t===void 0){X0("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let NR=0;class Ga extends _c{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:NR++}),this.uuid=Ar(),this.name="",this.type="Material",this.blending=Mc,this.side=Ba,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=k0,this.blendDst=af,this.blendEquation=ao,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new rt(0,0,0),this.blendAlpha=0,this.depthFunc=fu,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Sw,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Pl,this.stencilZFail=Pl,this.stencilZPass=Pl,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(const e in t){const i=t[e];if(i===void 0){Ht(`Material: parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Ht(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector2&&i&&i.isVector2||n&&n.isEuler&&i&&i.isEuler||n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Mc&&(i.blending=this.blending),this.side!==Ba&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==k0&&(i.blendSrc=this.blendSrc),this.blendDst!==af&&(i.blendDst=this.blendDst),this.blendEquation!==ao&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==fu&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Sw&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Pl&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Pl&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Pl&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(s){const r=[];for(const a in s){const c=s[a];delete c.metadata,r.push(c)}return r}if(e){const s=n(t.textures),r=n(t.images);s.length>0&&(i.textures=s),r.length>0&&(i.images=r)}return i}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new rt().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let i=t.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new tt().fromArray(i)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new tt().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(e!==null){const n=e.length;i=new Array(n);for(let s=0;s!==n;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}}class c0 extends Ga{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new rt(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}let Wl;const Lu=new T,Xl=new T,$l=new T,Yl=new tt,ku=new tt,dA=new Gt,Yf=new T,Fu=new T,Kf=new T,Fw=new tt,Tg=new tt,Uw=new tt;class Uu extends Bi{constructor(t=new c0){if(super(),this.isSprite=!0,this.type="Sprite",Wl===void 0){Wl=new be;const e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new uA(e,5);Wl.setIndex([0,1,2,0,2,3]),Wl.setAttribute("position",new $0(i,3,0,!1)),Wl.setAttribute("uv",new $0(i,2,3,!1))}this.geometry=Wl,this.material=t,this.center=new tt(.5,.5),this.count=1}raycast(t,e){t.camera===null&&le('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Xl.setFromMatrixScale(this.matrixWorld),dA.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),$l.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Xl.multiplyScalar(-$l.z);const i=this.material.rotation;let n,s;i!==0&&(s=Math.cos(i),n=Math.sin(i));const r=this.center;qf(Yf.set(-.5,-.5,0),$l,r,Xl,n,s),qf(Fu.set(.5,-.5,0),$l,r,Xl,n,s),qf(Kf.set(.5,.5,0),$l,r,Xl,n,s),Fw.set(0,0),Tg.set(1,0),Uw.set(1,1);let a=t.ray.intersectTriangle(Yf,Fu,Kf,!1,Lu);if(a===null&&(qf(Fu.set(-.5,.5,0),$l,r,Xl,n,s),Tg.set(0,1),a=t.ray.intersectTriangle(Yf,Kf,Fu,!1,Lu),a===null))return;const c=t.ray.origin.distanceTo(Lu);c<t.near||c>t.far||e.push({distance:c,point:Lu.clone(),uv:Hn.getInterpolation(Lu,Yf,Fu,Kf,Fw,Tg,Uw,new tt),face:null,object:this})}copy(t,e){return super.copy(t,e),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}}function qf(o,t,e,i,n,s){Yl.subVectors(o,e).addScalar(.5).multiply(i),n!==void 0?(ku.x=s*Yl.x-n*Yl.y,ku.y=n*Yl.x+s*Yl.y):ku.copy(Yl),o.copy(t),o.x+=ku.x,o.y+=ku.y,o.applyMatrix4(dA)}const Ka=new T,Rg=new T,Zf=new T,ko=new T,Ig=new T,Jf=new T,Dg=new T;class El{constructor(t=new T,e=new T(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Ka)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Ka.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Ka.copy(this.origin).addScaledVector(this.direction,e),Ka.distanceToSquared(t))}distanceSqToSegment(t,e,i,n){Rg.copy(t).add(e).multiplyScalar(.5),Zf.copy(e).sub(t).normalize(),ko.copy(this.origin).sub(Rg);const s=t.distanceTo(e)*.5,r=-this.direction.dot(Zf),a=ko.dot(this.direction),c=-ko.dot(Zf),l=ko.lengthSq(),h=Math.abs(1-r*r);let u,d,f,p;if(h>0)if(u=r*c-a,d=r*a-c,p=s*h,u>=0)if(d>=-p)if(d<=p){const m=1/h;u*=m,d*=m,f=u*(u+r*d+2*a)+d*(r*u+d+2*c)+l}else d=s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d=-s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d<=-p?(u=Math.max(0,-(-r*s+a)),d=u>0?-s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l):d<=p?(u=0,d=Math.min(Math.max(-s,-c),s),f=d*(d+2*c)+l):(u=Math.max(0,-(r*s+a)),d=u>0?s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l);else d=r>0?-s:s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(Rg).addScaledVector(Zf,d),f}intersectSphere(t,e){Ka.subVectors(t.center,this.origin);const i=Ka.dot(this.direction),n=Ka.dot(Ka)-i*i,s=t.radius*t.radius;if(n>s)return null;const r=Math.sqrt(s-n),a=i-r,c=i+r;return c<0?null:a<0?this.at(c,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return i===null?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,n,s,r,a,c;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(i=(t.min.x-d.x)*l,n=(t.max.x-d.x)*l):(i=(t.max.x-d.x)*l,n=(t.min.x-d.x)*l),h>=0?(s=(t.min.y-d.y)*h,r=(t.max.y-d.y)*h):(s=(t.max.y-d.y)*h,r=(t.min.y-d.y)*h),i>r||s>n||((s>i||isNaN(i))&&(i=s),(r<n||isNaN(n))&&(n=r),u>=0?(a=(t.min.z-d.z)*u,c=(t.max.z-d.z)*u):(a=(t.max.z-d.z)*u,c=(t.min.z-d.z)*u),i>c||a>n)||((a>i||i!==i)&&(i=a),(c<n||n!==n)&&(n=c),n<0)?null:this.at(i>=0?i:n,e)}intersectsBox(t){return this.intersectBox(t,Ka)!==null}intersectTriangle(t,e,i,n,s){Ig.subVectors(e,t),Jf.subVectors(i,t),Dg.crossVectors(Ig,Jf);let r=this.direction.dot(Dg),a;if(r>0){if(n)return null;a=1}else if(r<0)a=-1,r=-r;else return null;ko.subVectors(this.origin,t);const c=a*this.direction.dot(Jf.crossVectors(ko,Jf));if(c<0)return null;const l=a*this.direction.dot(Ig.cross(ko));if(l<0||c+l>r)return null;const h=-a*ko.dot(Dg);return h<0?null:this.at(h/r,s)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Is extends Ga{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new rt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yr,this.combine=ay,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const zw=new Gt,Cc=new El,jf=new Tr,Bw=new T,Qf=new T,tp=new T,ep=new T,Cg=new T,ip=new T,Hw=new T,np=new T;class yt extends Bi{constructor(t=new be,e=new Is){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}getVertexPosition(t,e){const i=this.geometry,n=i.attributes.position,s=i.morphAttributes.position,r=i.morphTargetsRelative;e.fromBufferAttribute(n,t);const a=this.morphTargetInfluences;if(s&&a){ip.set(0,0,0);for(let c=0,l=s.length;c<l;c++){const h=a[c],u=s[c];h!==0&&(Cg.fromBufferAttribute(u,t),r?ip.addScaledVector(Cg,h):ip.addScaledVector(Cg.sub(e),h))}e.add(ip)}return e}raycast(t,e){const i=this.geometry,n=this.material,s=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),jf.copy(i.boundingSphere),jf.applyMatrix4(s),Cc.copy(t.ray).recast(t.near),!(jf.containsPoint(Cc.origin)===!1&&(Cc.intersectSphere(jf,Bw)===null||Cc.origin.distanceToSquared(Bw)>(t.far-t.near)**2))&&(zw.copy(s).invert(),Cc.copy(t.ray).applyMatrix4(zw),!(i.boundingBox!==null&&Cc.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(t,e,Cc)))}_computeIntersections(t,e,i){let n;const s=this.geometry,r=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,f=s.drawRange;if(a!==null)if(Array.isArray(r))for(let p=0,m=d.length;p<m;p++){const g=d[p],v=r[g.materialIndex],M=Math.max(g.start,f.start),w=Math.min(a.count,Math.min(g.start+g.count,f.start+f.count));for(let y=M,x=w;y<x;y+=3){const b=a.getX(y),E=a.getX(y+1),S=a.getX(y+2);n=sp(this,v,t,i,l,h,u,b,E,S),n&&(n.faceIndex=Math.floor(y/3),n.face.materialIndex=g.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),m=Math.min(a.count,f.start+f.count);for(let g=p,v=m;g<v;g+=3){const M=a.getX(g),w=a.getX(g+1),y=a.getX(g+2);n=sp(this,r,t,i,l,h,u,M,w,y),n&&(n.faceIndex=Math.floor(g/3),e.push(n))}}else if(c!==void 0)if(Array.isArray(r))for(let p=0,m=d.length;p<m;p++){const g=d[p],v=r[g.materialIndex],M=Math.max(g.start,f.start),w=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let y=M,x=w;y<x;y+=3){const b=y,E=y+1,S=y+2;n=sp(this,v,t,i,l,h,u,b,E,S),n&&(n.faceIndex=Math.floor(y/3),n.face.materialIndex=g.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),m=Math.min(c.count,f.start+f.count);for(let g=p,v=m;g<v;g+=3){const M=g,w=g+1,y=g+2;n=sp(this,r,t,i,l,h,u,M,w,y),n&&(n.faceIndex=Math.floor(g/3),e.push(n))}}}}function LR(o,t,e,i,n,s,r,a){let c;if(t.side===zi?c=i.intersectTriangle(r,s,n,!0,a):c=i.intersectTriangle(n,s,r,t.side===Ba,a),c===null)return null;np.copy(a),np.applyMatrix4(o.matrixWorld);const l=e.ray.origin.distanceTo(np);return l<e.near||l>e.far?null:{distance:l,point:np.clone(),object:o}}function sp(o,t,e,i,n,s,r,a,c,l){o.getVertexPosition(a,Qf),o.getVertexPosition(c,tp),o.getVertexPosition(l,ep);const h=LR(o,t,e,i,Qf,tp,ep,Hw);if(h){const u=new T;Hn.getBarycoord(Hw,Qf,tp,ep,u),n&&(h.uv=Hn.getInterpolatedAttribute(n,a,c,l,u,new tt)),s&&(h.uv1=Hn.getInterpolatedAttribute(s,a,c,l,u,new tt)),r&&(h.normal=Hn.getInterpolatedAttribute(r,a,c,l,u,new T),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const d={a,b:c,c:l,normal:new T,materialIndex:0};Hn.getNormal(Qf,tp,ep,d.normal),h.face=d,h.barycoord=u}return h}const zu=new Ie,Gw=new Ie,Vw=new Ie,kR=new Ie,Ww=new Gt,rp=new T,Og=new Tr,Xw=new Gt,Pg=new El;class ik extends yt{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=xw,this.bindMatrix=new Gt,this.bindMatrixInverse=new Gt,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;this.boundingBox===null&&(this.boundingBox=new Je),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,rp),this.boundingBox.expandByPoint(rp)}computeBoundingSphere(){const t=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Tr),this.boundingSphere.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,rp),this.boundingSphere.expandByPoint(rp)}copy(t,e){return super.copy(t,e),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}raycast(t,e){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Og.copy(this.boundingSphere),Og.applyMatrix4(n),t.ray.intersectsSphere(Og)!==!1&&(Xw.copy(n).invert(),Pg.copy(t.ray).applyMatrix4(Xw),!(this.boundingBox!==null&&Pg.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(t,e,Pg)))}getVertexPosition(t,e){return super.getVertexPosition(t,e),this.applyBoneTransform(t,e),e}bind(t,e){this.skeleton=t,e===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new Ie,e=this.geometry.attributes.skinWeight;for(let i=0,n=e.count;i<n;i++){t.fromBufferAttribute(e,i);const s=1/t.manhattanLength();s!==1/0?t.multiplyScalar(s):t.set(1,0,0,0),e.setXYZW(i,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.bindMode===xw?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===k4?this.bindMatrixInverse.copy(this.bindMatrix).invert():Ht("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(t,e){const i=this.skeleton,n=this.geometry;Gw.fromBufferAttribute(n.attributes.skinIndex,t),Vw.fromBufferAttribute(n.attributes.skinWeight,t),e.isVector4?(zu.copy(e),e.set(0,0,0,0)):(zu.set(...e,1),e.set(0,0,0)),zu.applyMatrix4(this.bindMatrix);for(let s=0;s<4;s++){const r=Vw.getComponent(s);if(r!==0){const a=Gw.getComponent(s);Ww.multiplyMatrices(i.bones[a].matrixWorld,i.boneInverses[a]),e.addScaledVector(kR.copy(zu).applyMatrix4(Ww),r)}}return e.isVector4&&(e.w=zu.w),e.applyMatrix4(this.bindMatrixInverse)}}class FR extends Bi{constructor(){super(),this.isBone=!0,this.type="Bone"}}class Ds extends Wn{constructor(t=null,e=1,i=1,n,s,r,a,c,l=si,h=si,u,d){super(null,r,a,c,l,h,n,s,u,d),this.isDataTexture=!0,this.image={data:t,width:e,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const $w=new Gt,UR=new Gt;class fA{constructor(t=[],e=[]){this.uuid=Ar(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(t.length*16),e.length===0)this.calculateInverses();else if(t.length!==e.length){Ht("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new Gt)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const i=new Gt;this.bones[t]&&i.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&i.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const t=this.bones,e=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,r=t.length;s<r;s++){const a=t[s]?t[s].matrixWorld:UR;$w.multiplyMatrices(a,e[s]),$w.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new fA(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(this.bones.length*4);t=Math.ceil(t/4)*4,t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const i=new Ds(e,t,t,tn,ts);return i.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=i,this}getBoneByName(t){for(let e=0,i=this.bones.length;e<i;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let i=0,n=t.bones.length;i<n;i++){const s=t.bones[i];let r=e[s];r===void 0&&(Ht("Skeleton: No bone found with UUID:",s),r=new FR),this.bones.push(r),this.boneInverses.push(new Gt().fromArray(t.boneInverses[i]))}return this.init(),this}toJSON(){const t={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,i=this.boneInverses;for(let n=0,s=e.length;n<s;n++){const r=e[n];t.bones.push(r.uuid);const a=i[n];t.boneInverses.push(a.toArray())}return t}}class Yw extends we{constructor(t,e,i,n=1){super(t,e,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}const Kl=new Gt,Kw=new Gt,ap=[],qw=new Je,zR=new Gt,Bu=new yt,Hu=new Tr;class nk extends yt{constructor(t,e,i){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new Yw(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,zR)}computeBoundingBox(){const t=this.geometry,e=this.count;this.boundingBox===null&&(this.boundingBox=new Je),t.boundingBox===null&&t.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,Kl),qw.copy(t.boundingBox).applyMatrix4(Kl),this.boundingBox.union(qw)}computeBoundingSphere(){const t=this.geometry,e=this.count;this.boundingSphere===null&&(this.boundingSphere=new Tr),t.boundingSphere===null&&t.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,Kl),Hu.copy(t.boundingSphere).applyMatrix4(Kl),this.boundingSphere.union(Hu)}copy(t,e){return super.copy(t,e),this.instanceMatrix.copy(t.instanceMatrix),t.morphTexture!==null&&(this.morphTexture=t.morphTexture.clone()),t.instanceColor!==null&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}getColorAt(t,e){return this.instanceColor===null?e.setRGB(1,1,1):e.fromArray(this.instanceColor.array,t*3)}getMatrixAt(t,e){return e.fromArray(this.instanceMatrix.array,t*16)}getMorphAt(t,e){const i=e.morphTargetInfluences,n=this.morphTexture.source.data.data,s=i.length+1,r=t*s+1;for(let a=0;a<i.length;a++)i[a]=n[r+a]}raycast(t,e){const i=this.matrixWorld,n=this.count;if(Bu.geometry=this.geometry,Bu.material=this.material,Bu.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Hu.copy(this.boundingSphere),Hu.applyMatrix4(i),t.ray.intersectsSphere(Hu)!==!1))for(let s=0;s<n;s++){this.getMatrixAt(s,Kl),Kw.multiplyMatrices(i,Kl),Bu.matrixWorld=Kw,Bu.raycast(t,ap);for(let r=0,a=ap.length;r<a;r++){const c=ap[r];c.instanceId=s,c.object=this,e.push(c)}ap.length=0}}setColorAt(t,e){return this.instanceColor===null&&(this.instanceColor=new Yw(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),e.toArray(this.instanceColor.array,t*3),this}setMatrixAt(t,e){return e.toArray(this.instanceMatrix.array,t*16),this}setMorphAt(t,e){const i=e.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new Ds(new Float32Array(n*this.count),n,this.count,mu,ts));const s=this.morphTexture.source.data.data;let r=0;for(let l=0;l<i.length;l++)r+=i[l];const a=this.geometry.morphTargetsRelative?1:1-r,c=n*t;return s[c]=a,s.set(i,c+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const Ng=new T,BR=new T,HR=new de;class Hr{constructor(t=new T(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,n){return this.normal.set(t,e,i),this.constant=n,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const n=Ng.subVectors(i,e).cross(BR.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(n,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e,i=!0){const n=t.delta(Ng),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/s;return i===!0&&(r<0||r>1)?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||HR.getNormalMatrix(t),n=this.coplanarPoint(Ng).applyMatrix4(t),s=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(s),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Oc=new Tr,GR=new tt(.5,.5),op=new T;class Cm{constructor(t=new Hr,e=new Hr,i=new Hr,n=new Hr,s=new Hr,r=new Hr){this.planes=[t,e,i,n,s,r]}set(t,e,i,n,s,r){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(n),a[4].copy(s),a[5].copy(r),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=Ca,i=!1){const n=this.planes,s=t.elements,r=s[0],a=s[1],c=s[2],l=s[3],h=s[4],u=s[5],d=s[6],f=s[7],p=s[8],m=s[9],g=s[10],v=s[11],M=s[12],w=s[13],y=s[14],x=s[15];if(n[0].setComponents(l-r,f-h,v-p,x-M).normalize(),n[1].setComponents(l+r,f+h,v+p,x+M).normalize(),n[2].setComponents(l+a,f+u,v+m,x+w).normalize(),n[3].setComponents(l-a,f-u,v-m,x-w).normalize(),i)n[4].setComponents(c,d,g,y).normalize(),n[5].setComponents(l-c,f-d,v-g,x-y).normalize();else if(n[4].setComponents(l-c,f-d,v-g,x-y).normalize(),e===Ca)n[5].setComponents(l+c,f+d,v+g,x+y).normalize();else if(e===lf)n[5].setComponents(c,d,g,y).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),Oc.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Oc.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(Oc)}intersectsSprite(t){Oc.center.set(0,0,0);const e=GR.distanceTo(t.center);return Oc.radius=.7071067811865476+e,Oc.applyMatrix4(t.matrixWorld),this.intersectsSphere(Oc)}intersectsSphere(t){const e=this.planes,i=t.center,n=-t.radius;for(let s=0;s<6;s++)if(e[s].distanceToPoint(i)<n)return!1;return!0}intersectsBox(t){const e=this.planes;for(let i=0;i<6;i++){const n=e[i];if(op.x=n.normal.x>0?t.max.x:t.min.x,op.y=n.normal.y>0?t.max.y:t.min.y,op.z=n.normal.z>0?t.max.z:t.min.z,n.distanceToPoint(op)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class VR extends Ga{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new rt(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}}const Y0=new T,K0=new T,Zw=new Gt,Gu=new El,cp=new Tr,Lg=new T,Jw=new T;class pA extends Bi{constructor(t=new be,e=new VR){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[0];for(let n=1,s=e.count;n<s;n++)Y0.fromBufferAttribute(e,n-1),K0.fromBufferAttribute(e,n),i[n]=i[n-1],i[n]+=Y0.distanceTo(K0);t.setAttribute("lineDistance",new pe(i,1))}else Ht("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Line.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),cp.copy(i.boundingSphere),cp.applyMatrix4(n),cp.radius+=s,t.ray.intersectsSphere(cp)===!1)return;Zw.copy(n).invert(),Gu.copy(t.ray).applyMatrix4(Zw);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,h=i.index,d=i.attributes.position;if(h!==null){const f=Math.max(0,r.start),p=Math.min(h.count,r.start+r.count);for(let m=f,g=p-1;m<g;m+=l){const v=h.getX(m),M=h.getX(m+1),w=lp(this,t,Gu,c,v,M,m);w&&e.push(w)}if(this.isLineLoop){const m=h.getX(p-1),g=h.getX(f),v=lp(this,t,Gu,c,m,g,p-1);v&&e.push(v)}}else{const f=Math.max(0,r.start),p=Math.min(d.count,r.start+r.count);for(let m=f,g=p-1;m<g;m+=l){const v=lp(this,t,Gu,c,m,m+1,m);v&&e.push(v)}if(this.isLineLoop){const m=lp(this,t,Gu,c,p-1,f,p-1);m&&e.push(m)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function lp(o,t,e,i,n,s,r){const a=o.geometry.attributes.position;if(Y0.fromBufferAttribute(a,n),K0.fromBufferAttribute(a,s),e.distanceSqToSegment(Y0,K0,Lg,Jw)>i)return;Lg.applyMatrix4(o.matrixWorld);const l=t.ray.origin.distanceTo(Lg);if(!(l<t.near||l>t.far))return{distance:l,point:Jw.clone().applyMatrix4(o.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:o}}const jw=new T,Qw=new T;class sk extends pA{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[];for(let n=0,s=e.count;n<s;n+=2)jw.fromBufferAttribute(e,n),Qw.fromBufferAttribute(e,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+jw.distanceTo(Qw);t.setAttribute("lineDistance",new pe(i,1))}else Ht("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class rk extends pA{constructor(t,e){super(t,e),this.isLineLoop=!0,this.type="LineLoop"}}class Qv extends Ga{constructor(t){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new rt(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const tx=new Gt,tM=new El,hp=new Tr,up=new T;class ir extends Bi{constructor(t=new be,e=new Qv){super(),this.isPoints=!0,this.type="Points",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Points.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),hp.copy(i.boundingSphere),hp.applyMatrix4(n),hp.radius+=s,t.ray.intersectsSphere(hp)===!1)return;tx.copy(n).invert(),tM.copy(t.ray).applyMatrix4(tx);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=i.index,u=i.attributes.position;if(l!==null){const d=Math.max(0,r.start),f=Math.min(l.count,r.start+r.count);for(let p=d,m=f;p<m;p++){const g=l.getX(p);up.fromBufferAttribute(u,g),ex(up,g,c,n,t,e,this)}}else{const d=Math.max(0,r.start),f=Math.min(u.count,r.start+r.count);for(let p=d,m=f;p<m;p++)up.fromBufferAttribute(u,p),ex(up,p,c,n,t,e,this)}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function ex(o,t,e,i,n,s,r){const a=tM.distanceSqToPoint(o);if(a<e){const c=new T;tM.closestPointToPoint(o,c),c.applyMatrix4(i);const l=n.ray.origin.distanceTo(c);if(l<n.near||l>n.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:r})}}class ak extends Wn{constructor(t,e,i,n,s=Me,r=Me,a,c,l){super(t,e,i,n,s,r,a,c,l),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const h=this;function u(){h.needsUpdate=!0,h._requestVideoFrameCallbackId=t.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in t&&(this._requestVideoFrameCallbackId=t.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;"requestVideoFrameCallback"in t===!1&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class mA extends Wn{constructor(t=[],e=wl,i,n,s,r,a,c,l,h){super(t,e,i,n,s,r,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class Tc extends Wn{constructor(t,e,i,n,s,r,a,c,l){super(t,e,i,n,s,r,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Sc extends Wn{constructor(t,e,i=_r,n,s,r,a=si,c=si,l,h=So,u=1){if(h!==So&&h!==tl)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:t,height:e,depth:u};super(d,n,s,r,a,c,h,i,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new vy(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class WR extends Sc{constructor(t,e=_r,i=wl,n,s,r=si,a=si,c,l=So){const h={width:t,height:t,depth:1},u=[h,h,h,h,h,h];super(t,t,e,i,n,s,r,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class gA extends Wn{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class en extends be{constructor(t=1,e=1,i=1,n=1,s=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:n,heightSegments:s,depthSegments:r};const a=this;n=Math.floor(n),s=Math.floor(s),r=Math.floor(r);const c=[],l=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,i,e,t,r,s,0),p("z","y","x",1,-1,i,e,-t,r,s,1),p("x","z","y",1,1,t,i,e,n,r,2),p("x","z","y",1,-1,t,i,-e,n,r,3),p("x","y","z",1,-1,t,e,i,n,s,4),p("x","y","z",-1,-1,t,e,-i,n,s,5),this.setIndex(c),this.setAttribute("position",new pe(l,3)),this.setAttribute("normal",new pe(h,3)),this.setAttribute("uv",new pe(u,2));function p(m,g,v,M,w,y,x,b,E,S,A){const _=y/E,I=x/S,D=y/2,O=x/2,P=b/2,N=E+1,k=S+1;let B=0,W=0;const Q=new T;for(let Z=0;Z<k;Z++){const nt=Z*I-O;for(let ot=0;ot<N;ot++){const Ut=ot*_-D;Q[m]=Ut*M,Q[g]=nt*w,Q[v]=P,l.push(Q.x,Q.y,Q.z),Q[m]=0,Q[g]=0,Q[v]=b>0?1:-1,h.push(Q.x,Q.y,Q.z),u.push(ot/E),u.push(1-Z/S),B+=1}}for(let Z=0;Z<S;Z++)for(let nt=0;nt<E;nt++){const ot=d+nt+N*Z,Ut=d+nt+N*(Z+1),Zt=d+(nt+1)+N*(Z+1),jt=d+(nt+1)+N*Z;c.push(ot,Ut,jt),c.push(Ut,Zt,jt),W+=6}a.addGroup(f,W,A),f+=W,d+=B}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new en(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}class xy extends be{constructor(t=1,e=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:i,thetaLength:n},e=Math.max(3,e);const s=[],r=[],a=[],c=[],l=new T,h=new tt;r.push(0,0,0),a.push(0,0,1),c.push(.5,.5);for(let u=0,d=3;u<=e;u++,d+=3){const f=i+u/e*n;l.x=t*Math.cos(f),l.y=t*Math.sin(f),r.push(l.x,l.y,l.z),a.push(0,0,1),h.x=(r[d]/t+1)/2,h.y=(r[d+1]/t+1)/2,c.push(h.x,h.y)}for(let u=1;u<=e;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new pe(r,3)),this.setAttribute("normal",new pe(a,3)),this.setAttribute("uv",new pe(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new xy(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class gs extends be{constructor(t=1,e=1,i=1,n=32,s=1,r=!1,a=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:i,radialSegments:n,heightSegments:s,openEnded:r,thetaStart:a,thetaLength:c};const l=this;n=Math.floor(n),s=Math.floor(s);const h=[],u=[],d=[],f=[];let p=0;const m=[],g=i/2;let v=0;M(),r===!1&&(t>0&&w(!0),e>0&&w(!1)),this.setIndex(h),this.setAttribute("position",new pe(u,3)),this.setAttribute("normal",new pe(d,3)),this.setAttribute("uv",new pe(f,2));function M(){const y=new T,x=new T;let b=0;const E=(e-t)/i;for(let S=0;S<=s;S++){const A=[],_=S/s,I=_*(e-t)+t;for(let D=0;D<=n;D++){const O=D/n,P=O*c+a,N=Math.sin(P),k=Math.cos(P);x.x=I*N,x.y=-_*i+g,x.z=I*k,u.push(x.x,x.y,x.z),y.set(N,E,k).normalize(),d.push(y.x,y.y,y.z),f.push(O,1-_),A.push(p++)}m.push(A)}for(let S=0;S<n;S++)for(let A=0;A<s;A++){const _=m[A][S],I=m[A+1][S],D=m[A+1][S+1],O=m[A][S+1];(t>0||A!==0)&&(h.push(_,I,O),b+=3),(e>0||A!==s-1)&&(h.push(I,D,O),b+=3)}l.addGroup(v,b,0),v+=b}function w(y){const x=p,b=new tt,E=new T;let S=0;const A=y===!0?t:e,_=y===!0?1:-1;for(let D=1;D<=n;D++)u.push(0,g*_,0),d.push(0,_,0),f.push(.5,.5),p++;const I=p;for(let D=0;D<=n;D++){const P=D/n*c+a,N=Math.cos(P),k=Math.sin(P);E.x=A*k,E.y=g*_,E.z=A*N,u.push(E.x,E.y,E.z),d.push(0,_,0),b.x=N*.5+.5,b.y=k*.5*_+.5,f.push(b.x,b.y),p++}for(let D=0;D<n;D++){const O=x+D,P=I+D;y===!0?h.push(P,P+1,O):h.push(P+1,P,O),S+=3}l.addGroup(v,S,y===!0?1:2),v+=S}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new gs(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class bu extends gs{constructor(t=1,e=1,i=32,n=1,s=!1,r=0,a=Math.PI*2){super(0,t,e,i,n,s,r,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:r,thetaLength:a}}static fromJSON(t){return new bu(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class Va{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Ht("Curve: .getPoint() not implemented.")}getPointAt(t,e){const i=this.getUtoTmapping(t);return this.getPoint(i,e)}getPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return e}getSpacedPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPointAt(i/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let i,n=this.getPoint(0),s=0;e.push(0);for(let r=1;r<=t;r++)i=this.getPoint(r/t),s+=i.distanceTo(n),e.push(s),n=i;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e=null){const i=this.getLengths();let n=0;const s=i.length;let r;e?r=e:r=t*i[s-1];let a=0,c=s-1,l;for(;a<=c;)if(n=Math.floor(a+(c-a)/2),l=i[n]-r,l<0)a=n+1;else if(l>0)c=n-1;else{c=n;break}if(n=c,i[n]===r)return n/(s-1);const h=i[n],d=i[n+1]-h,f=(r-h)/d;return(n+f)/(s-1)}getTangent(t,e){let n=t-1e-4,s=t+1e-4;n<0&&(n=0),s>1&&(s=1);const r=this.getPoint(n),a=this.getPoint(s),c=e||(r.isVector2?new tt:new T);return c.copy(a).sub(r).normalize(),c}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e=!1){const i=new T,n=[],s=[],r=[],a=new T,c=new Gt;for(let f=0;f<=t;f++){const p=f/t;n[f]=this.getTangentAt(p,new T)}s[0]=new T,r[0]=new T;let l=Number.MAX_VALUE;const h=Math.abs(n[0].x),u=Math.abs(n[0].y),d=Math.abs(n[0].z);h<=l&&(l=h,i.set(1,0,0)),u<=l&&(l=u,i.set(0,1,0)),d<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),s[0].crossVectors(n[0],a),r[0].crossVectors(n[0],s[0]);for(let f=1;f<=t;f++){if(s[f]=s[f-1].clone(),r[f]=r[f-1].clone(),a.crossVectors(n[f-1],n[f]),a.length()>Number.EPSILON){a.normalize();const p=Math.acos(ge(n[f-1].dot(n[f]),-1,1));s[f].applyMatrix4(c.makeRotationAxis(a,p))}r[f].crossVectors(n[f],s[f])}if(e===!0){let f=Math.acos(ge(s[0].dot(s[t]),-1,1));f/=t,n[0].dot(a.crossVectors(s[0],s[t]))>0&&(f=-f);for(let p=1;p<=t;p++)s[p].applyMatrix4(c.makeRotationAxis(n[p],f*p)),r[p].crossVectors(n[p],s[p])}return{tangents:n,normals:s,binormals:r}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class by extends Va{constructor(t=0,e=0,i=1,n=1,s=0,r=Math.PI*2,a=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=s,this.aEndAngle=r,this.aClockwise=a,this.aRotation=c}getPoint(t,e=new tt){const i=e,n=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const r=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=n;for(;s>n;)s-=n;s<Number.EPSILON&&(r?s=0:s=n),this.aClockwise===!0&&!r&&(s===n?s=-n:s=s-n);const a=this.aStartAngle+t*s;let c=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){const h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=c-this.aX,f=l-this.aY;c=d*h-f*u+this.aX,l=d*u+f*h+this.aY}return i.set(c,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}class XR extends by{constructor(t,e,i,n,s,r){super(t,e,i,i,n,s,r),this.isArcCurve=!0,this.type="ArcCurve"}}function Sy(){let o=0,t=0,e=0,i=0;function n(s,r,a,c){o=s,t=a,e=-3*s+3*r-2*a-c,i=2*s-2*r+a+c}return{initCatmullRom:function(s,r,a,c,l){n(r,a,l*(a-s),l*(c-r))},initNonuniformCatmullRom:function(s,r,a,c,l,h,u){let d=(r-s)/l-(a-s)/(l+h)+(a-r)/h,f=(a-r)/h-(c-r)/(h+u)+(c-a)/u;d*=h,f*=h,n(r,a,d,f)},calc:function(s){const r=s*s,a=r*s;return o+t*s+e*r+i*a}}}const ix=new T,nx=new T,kg=new Sy,Fg=new Sy,Ug=new Sy;class $R extends Va{constructor(t=[],e=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=i,this.tension=n}getPoint(t,e=new T){const i=e,n=this.points,s=n.length,r=(s-(this.closed?0:1))*t;let a=Math.floor(r),c=r-a;this.closed?a+=a>0?0:(Math.floor(Math.abs(a)/s)+1)*s:c===0&&a===s-1&&(a=s-2,c=1);let l,h;this.closed||a>0?l=n[(a-1)%s]:(nx.subVectors(n[0],n[1]).add(n[0]),l=nx);const u=n[a%s],d=n[(a+1)%s];if(this.closed||a+2<s?h=n[(a+2)%s]:(ix.subVectors(n[s-1],n[s-2]).add(n[s-1]),h=ix),this.curveType==="centripetal"||this.curveType==="chordal"){const f=this.curveType==="chordal"?.5:.25;let p=Math.pow(l.distanceToSquared(u),f),m=Math.pow(u.distanceToSquared(d),f),g=Math.pow(d.distanceToSquared(h),f);m<1e-4&&(m=1),p<1e-4&&(p=m),g<1e-4&&(g=m),kg.initNonuniformCatmullRom(l.x,u.x,d.x,h.x,p,m,g),Fg.initNonuniformCatmullRom(l.y,u.y,d.y,h.y,p,m,g),Ug.initNonuniformCatmullRom(l.z,u.z,d.z,h.z,p,m,g)}else this.curveType==="catmullrom"&&(kg.initCatmullRom(l.x,u.x,d.x,h.x,this.tension),Fg.initCatmullRom(l.y,u.y,d.y,h.y,this.tension),Ug.initCatmullRom(l.z,u.z,d.z,h.z,this.tension));return i.set(kg.calc(c),Fg.calc(c),Ug.calc(c)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new T().fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function sx(o,t,e,i,n){const s=(i-t)*.5,r=(n-e)*.5,a=o*o,c=o*a;return(2*e-2*i+s+r)*c+(-3*e+3*i-2*s-r)*a+s*o+e}function YR(o,t){const e=1-o;return e*e*t}function KR(o,t){return 2*(1-o)*o*t}function qR(o,t){return o*o*t}function md(o,t,e,i){return YR(o,t)+KR(o,e)+qR(o,i)}function ZR(o,t){const e=1-o;return e*e*e*t}function JR(o,t){const e=1-o;return 3*e*e*o*t}function jR(o,t){return 3*(1-o)*o*o*t}function QR(o,t){return o*o*o*t}function gd(o,t,e,i,n){return ZR(o,t)+JR(o,e)+jR(o,i)+QR(o,n)}class vA extends Va{constructor(t=new tt,e=new tt,i=new tt,n=new tt){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new tt){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(gd(t,n.x,s.x,r.x,a.x),gd(t,n.y,s.y,r.y,a.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class tI extends Va{constructor(t=new T,e=new T,i=new T,n=new T){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new T){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(gd(t,n.x,s.x,r.x,a.x),gd(t,n.y,s.y,r.y,a.y),gd(t,n.z,s.z,r.z,a.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class MA extends Va{constructor(t=new tt,e=new tt){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new tt){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new tt){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class eI extends Va{constructor(t=new T,e=new T){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=t,this.v2=e}getPoint(t,e=new T){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new T){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class yA extends Va{constructor(t=new tt,e=new tt,i=new tt){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new tt){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(md(t,n.x,s.x,r.x),md(t,n.y,s.y,r.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class iI extends Va{constructor(t=new T,e=new T,i=new T){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new T){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(md(t,n.x,s.x,r.x),md(t,n.y,s.y,r.y),md(t,n.z,s.z,r.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class wA extends Va{constructor(t=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=t}getPoint(t,e=new tt){const i=e,n=this.points,s=(n.length-1)*t,r=Math.floor(s),a=s-r,c=n[r===0?r:r-1],l=n[r],h=n[r>n.length-2?n.length-1:r+1],u=n[r>n.length-3?n.length-1:r+2];return i.set(sx(a,c.x,l.x,h.x,u.x),sx(a,c.y,l.y,h.y,u.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new tt().fromArray(n))}return this}}var rx=Object.freeze({__proto__:null,ArcCurve:XR,CatmullRomCurve3:$R,CubicBezierCurve:vA,CubicBezierCurve3:tI,EllipseCurve:by,LineCurve:MA,LineCurve3:eI,QuadraticBezierCurve:yA,QuadraticBezierCurve3:iI,SplineCurve:wA});class nI extends Va{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);if(!t.equals(e)){const i=t.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new rx[i](e,t))}return this}getPoint(t,e){const i=t*this.getLength(),n=this.getCurveLengths();let s=0;for(;s<n.length;){if(n[s]>=i){const r=n[s]-i,a=this.curves[s],c=a.getLength(),l=c===0?0:1-r/c;return a.getPointAt(l,e)}s++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,n=this.curves.length;i<n;i++)e+=this.curves[i].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let i;for(let n=0,s=this.curves;n<s.length;n++){const r=s[n],a=r.isEllipseCurve?t*2:r.isLineCurve||r.isLineCurve3?1:r.isSplineCurve?t*r.points.length:t,c=r.getPoints(a);for(let l=0;l<c.length;l++){const h=c[l];i&&i.equals(h)||(e.push(h),i=h)}}return this.autoClose&&e.length>1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,i=this.curves.length;e<i;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(new rx[n.type]().fromJSON(n))}return this}}class ax extends nI{constructor(t){super(),this.type="Path",this.currentPoint=new tt,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,i=t.length;e<i;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const i=new MA(this.currentPoint.clone(),new tt(t,e));return this.curves.push(i),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,i,n){const s=new yA(this.currentPoint.clone(),new tt(t,e),new tt(i,n));return this.curves.push(s),this.currentPoint.set(i,n),this}bezierCurveTo(t,e,i,n,s,r){const a=new vA(this.currentPoint.clone(),new tt(t,e),new tt(i,n),new tt(s,r));return this.curves.push(a),this.currentPoint.set(s,r),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),i=new wA(e);return this.curves.push(i),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,i,n,s,r){const a=this.currentPoint.x,c=this.currentPoint.y;return this.absarc(t+a,e+c,i,n,s,r),this}absarc(t,e,i,n,s,r){return this.absellipse(t,e,i,i,n,s,r),this}ellipse(t,e,i,n,s,r,a,c){const l=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(t+l,e+h,i,n,s,r,a,c),this}absellipse(t,e,i,n,s,r,a,c){const l=new by(t,e,i,n,s,r,a,c);if(this.curves.length>0){const u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);const h=l.getPoint(1);return this.currentPoint.copy(h),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class eM extends ax{constructor(t){super(t),this.uuid=Ar(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,n=this.holes.length;i<n;i++)e[i]=this.holes[i].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,i=this.holes.length;e<i;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(new ax().fromJSON(n))}return this}}function sI(o,t,e=2){const i=t&&t.length,n=i?t[0]*e:o.length;let s=xA(o,0,n,e,!0);const r=[];if(!s||s.next===s.prev)return r;let a,c,l;if(i&&(s=lI(o,t,s,e)),o.length>80*e){a=o[0],c=o[1];let h=a,u=c;for(let d=e;d<n;d+=e){const f=o[d],p=o[d+1];f<a&&(a=f),p<c&&(c=p),f>h&&(h=f),p>u&&(u=p)}l=Math.max(h-a,u-c),l=l!==0?32767/l:0}return uf(s,r,e,a,c,l,0),r}function xA(o,t,e,i,n){let s;if(n===wI(o,t,e,i)>0)for(let r=t;r<e;r+=i)s=ox(r/i|0,o[r],o[r+1],s);else for(let r=e-i;r>=t;r-=i)s=ox(r/i|0,o[r],o[r+1],s);return s&&vu(s,s.next)&&(ff(s),s=s.next),s}function bl(o,t){if(!o)return o;t||(t=o);let e=o,i;do if(i=!1,!e.steiner&&(vu(e,e.next)||Xi(e.prev,e,e.next)===0)){if(ff(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function uf(o,t,e,i,n,s,r){if(!o)return;!r&&s&&pI(o,i,n,s);let a=o;for(;o.prev!==o.next;){const c=o.prev,l=o.next;if(s?aI(o,i,n,s):rI(o)){t.push(c.i,o.i,l.i),ff(o),o=l.next,a=l.next;continue}if(o=l,o===a){r?r===1?(o=oI(bl(o),t),uf(o,t,e,i,n,s,2)):r===2&&cI(o,t,e,i,n,s):uf(bl(o),t,e,i,n,s,1);break}}}function rI(o){const t=o.prev,e=o,i=o.next;if(Xi(t,e,i)>=0)return!1;const n=t.x,s=e.x,r=i.x,a=t.y,c=e.y,l=i.y,h=Math.min(n,s,r),u=Math.min(a,c,l),d=Math.max(n,s,r),f=Math.max(a,c,l);let p=i.next;for(;p!==t;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&ld(n,a,s,c,r,l,p.x,p.y)&&Xi(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function aI(o,t,e,i){const n=o.prev,s=o,r=o.next;if(Xi(n,s,r)>=0)return!1;const a=n.x,c=s.x,l=r.x,h=n.y,u=s.y,d=r.y,f=Math.min(a,c,l),p=Math.min(h,u,d),m=Math.max(a,c,l),g=Math.max(h,u,d),v=iM(f,p,t,e,i),M=iM(m,g,t,e,i);let w=o.prevZ,y=o.nextZ;for(;w&&w.z>=v&&y&&y.z<=M;){if(w.x>=f&&w.x<=m&&w.y>=p&&w.y<=g&&w!==n&&w!==r&&ld(a,h,c,u,l,d,w.x,w.y)&&Xi(w.prev,w,w.next)>=0||(w=w.prevZ,y.x>=f&&y.x<=m&&y.y>=p&&y.y<=g&&y!==n&&y!==r&&ld(a,h,c,u,l,d,y.x,y.y)&&Xi(y.prev,y,y.next)>=0))return!1;y=y.nextZ}for(;w&&w.z>=v;){if(w.x>=f&&w.x<=m&&w.y>=p&&w.y<=g&&w!==n&&w!==r&&ld(a,h,c,u,l,d,w.x,w.y)&&Xi(w.prev,w,w.next)>=0)return!1;w=w.prevZ}for(;y&&y.z<=M;){if(y.x>=f&&y.x<=m&&y.y>=p&&y.y<=g&&y!==n&&y!==r&&ld(a,h,c,u,l,d,y.x,y.y)&&Xi(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function oI(o,t){let e=o;do{const i=e.prev,n=e.next.next;!vu(i,n)&&SA(i,e,e.next,n)&&df(i,n)&&df(n,i)&&(t.push(i.i,e.i,n.i),ff(e),ff(e.next),e=o=n),e=e.next}while(e!==o);return bl(e)}function cI(o,t,e,i,n,s){let r=o;do{let a=r.next.next;for(;a!==r.prev;){if(r.i!==a.i&&vI(r,a)){let c=EA(r,a);r=bl(r,r.next),c=bl(c,c.next),uf(r,t,e,i,n,s,0),uf(c,t,e,i,n,s,0);return}a=a.next}r=r.next}while(r!==o)}function lI(o,t,e,i){const n=[];for(let s=0,r=t.length;s<r;s++){const a=t[s]*i,c=s<r-1?t[s+1]*i:o.length,l=xA(o,a,c,i,!1);l===l.next&&(l.steiner=!0),n.push(gI(l))}n.sort(hI);for(let s=0;s<n.length;s++)e=uI(n[s],e);return e}function hI(o,t){let e=o.x-t.x;if(e===0&&(e=o.y-t.y,e===0)){const i=(o.next.y-o.y)/(o.next.x-o.x),n=(t.next.y-t.y)/(t.next.x-t.x);e=i-n}return e}function uI(o,t){const e=dI(o,t);if(!e)return t;const i=EA(e,o);return bl(i,i.next),bl(e,e.next)}function dI(o,t){let e=t;const i=o.x,n=o.y;let s=-1/0,r;if(vu(o,e))return e;do{if(vu(o,e.next))return e.next;if(n<=e.y&&n>=e.next.y&&e.next.y!==e.y){const u=e.x+(n-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=i&&u>s&&(s=u,r=e.x<e.next.x?e:e.next,u===i))return r}e=e.next}while(e!==t);if(!r)return null;const a=r,c=r.x,l=r.y;let h=1/0;e=r;do{if(i>=e.x&&e.x>=c&&i!==e.x&&bA(n<l?i:s,n,c,l,n<l?s:i,n,e.x,e.y)){const u=Math.abs(n-e.y)/(i-e.x);df(e,o)&&(u<h||u===h&&(e.x>r.x||e.x===r.x&&fI(r,e)))&&(r=e,h=u)}e=e.next}while(e!==a);return r}function fI(o,t){return Xi(o.prev,o,t.prev)<0&&Xi(t.next,o,o.next)<0}function pI(o,t,e,i){let n=o;do n.z===0&&(n.z=iM(n.x,n.y,t,e,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==o);n.prevZ.nextZ=null,n.prevZ=null,mI(n)}function mI(o){let t,e=1;do{let i=o,n;o=null;let s=null;for(t=0;i;){t++;let r=i,a=0;for(let l=0;l<e&&(a++,r=r.nextZ,!!r);l++);let c=e;for(;a>0||c>0&&r;)a!==0&&(c===0||!r||i.z<=r.z)?(n=i,i=i.nextZ,a--):(n=r,r=r.nextZ,c--),s?s.nextZ=n:o=n,n.prevZ=s,s=n;i=r}s.nextZ=null,e*=2}while(t>1);return o}function iM(o,t,e,i,n){return o=(o-e)*n|0,t=(t-i)*n|0,o=(o|o<<8)&16711935,o=(o|o<<4)&252645135,o=(o|o<<2)&858993459,o=(o|o<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,o|t<<1}function gI(o){let t=o,e=o;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==o);return e}function bA(o,t,e,i,n,s,r,a){return(n-r)*(t-a)>=(o-r)*(s-a)&&(o-r)*(i-a)>=(e-r)*(t-a)&&(e-r)*(s-a)>=(n-r)*(i-a)}function ld(o,t,e,i,n,s,r,a){return!(o===r&&t===a)&&bA(o,t,e,i,n,s,r,a)}function vI(o,t){return o.next.i!==t.i&&o.prev.i!==t.i&&!MI(o,t)&&(df(o,t)&&df(t,o)&&yI(o,t)&&(Xi(o.prev,o,t.prev)||Xi(o,t.prev,t))||vu(o,t)&&Xi(o.prev,o,o.next)>0&&Xi(t.prev,t,t.next)>0)}function Xi(o,t,e){return(t.y-o.y)*(e.x-t.x)-(t.x-o.x)*(e.y-t.y)}function vu(o,t){return o.x===t.x&&o.y===t.y}function SA(o,t,e,i){const n=fp(Xi(o,t,e)),s=fp(Xi(o,t,i)),r=fp(Xi(e,i,o)),a=fp(Xi(e,i,t));return!!(n!==s&&r!==a||n===0&&dp(o,e,t)||s===0&&dp(o,i,t)||r===0&&dp(e,o,i)||a===0&&dp(e,t,i))}function dp(o,t,e){return t.x<=Math.max(o.x,e.x)&&t.x>=Math.min(o.x,e.x)&&t.y<=Math.max(o.y,e.y)&&t.y>=Math.min(o.y,e.y)}function fp(o){return o>0?1:o<0?-1:0}function MI(o,t){let e=o;do{if(e.i!==o.i&&e.next.i!==o.i&&e.i!==t.i&&e.next.i!==t.i&&SA(e,e.next,o,t))return!0;e=e.next}while(e!==o);return!1}function df(o,t){return Xi(o.prev,o,o.next)<0?Xi(o,t,o.next)>=0&&Xi(o,o.prev,t)>=0:Xi(o,t,o.prev)<0||Xi(o,o.next,t)<0}function yI(o,t){let e=o,i=!1;const n=(o.x+t.x)/2,s=(o.y+t.y)/2;do e.y>s!=e.next.y>s&&e.next.y!==e.y&&n<(e.next.x-e.x)*(s-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==o);return i}function EA(o,t){const e=nM(o.i,o.x,o.y),i=nM(t.i,t.x,t.y),n=o.next,s=t.prev;return o.next=t,t.prev=o,e.next=n,n.prev=e,i.next=e,e.prev=i,s.next=i,i.prev=s,i}function ox(o,t,e,i){const n=nM(o,t,e);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function ff(o){o.next.prev=o.prev,o.prev.next=o.next,o.prevZ&&(o.prevZ.nextZ=o.nextZ),o.nextZ&&(o.nextZ.prevZ=o.prevZ)}function nM(o,t,e){return{i:o,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function wI(o,t,e,i){let n=0;for(let s=t,r=e-i;s<e;s+=i)n+=(o[r]-o[s])*(o[s+1]+o[r+1]),r=s;return n}class xI{static triangulate(t,e,i=2){return sI(t,e,i)}}class vd{static area(t){const e=t.length;let i=0;for(let n=e-1,s=0;s<e;n=s++)i+=t[n].x*t[s].y-t[s].x*t[n].y;return i*.5}static isClockWise(t){return vd.area(t)<0}static triangulateShape(t,e){const i=[],n=[],s=[];cx(t),lx(i,t);let r=t.length;e.forEach(cx);for(let c=0;c<e.length;c++)n.push(r),r+=e[c].length,lx(i,e[c]);const a=xI.triangulate(i,n);for(let c=0;c<a.length;c+=3)s.push(a.slice(c,c+3));return s}}function cx(o){const t=o.length;t>2&&o[t-1].equals(o[0])&&o.pop()}function lx(o,t){for(let e=0;e<t.length;e++)o.push(t[e].x),o.push(t[e].y)}class Om extends be{constructor(t=[new tt(0,-.5),new tt(.5,0),new tt(0,.5)],e=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:i,phiLength:n},e=Math.floor(e),n=ge(n,0,Math.PI*2);const s=[],r=[],a=[],c=[],l=[],h=1/e,u=new T,d=new tt,f=new T,p=new T,m=new T;let g=0,v=0;for(let M=0;M<=t.length-1;M++)switch(M){case 0:g=t[M+1].x-t[M].x,v=t[M+1].y-t[M].y,f.x=v*1,f.y=-g,f.z=v*0,m.copy(f),f.normalize(),c.push(f.x,f.y,f.z);break;case t.length-1:c.push(m.x,m.y,m.z);break;default:g=t[M+1].x-t[M].x,v=t[M+1].y-t[M].y,f.x=v*1,f.y=-g,f.z=v*0,p.copy(f),f.x+=m.x,f.y+=m.y,f.z+=m.z,f.normalize(),c.push(f.x,f.y,f.z),m.copy(p)}for(let M=0;M<=e;M++){const w=i+M*h*n,y=Math.sin(w),x=Math.cos(w);for(let b=0;b<=t.length-1;b++){u.x=t[b].x*y,u.y=t[b].y,u.z=t[b].x*x,r.push(u.x,u.y,u.z),d.x=M/e,d.y=b/(t.length-1),a.push(d.x,d.y);const E=c[3*b+0]*y,S=c[3*b+1],A=c[3*b+0]*x;l.push(E,S,A)}}for(let M=0;M<e;M++)for(let w=0;w<t.length-1;w++){const y=w+M*t.length,x=y,b=y+t.length,E=y+t.length+1,S=y+1;s.push(x,b,S),s.push(E,S,b)}this.setIndex(s),this.setAttribute("position",new pe(r,3)),this.setAttribute("uv",new pe(a,2)),this.setAttribute("normal",new pe(l,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Om(t.points,t.segments,t.phiStart,t.phiLength)}}class vs extends be{constructor(t=1,e=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};const s=t/2,r=e/2,a=Math.floor(i),c=Math.floor(n),l=a+1,h=c+1,u=t/a,d=e/c,f=[],p=[],m=[],g=[];for(let v=0;v<h;v++){const M=v*d-r;for(let w=0;w<l;w++){const y=w*u-s;p.push(y,-M,0),m.push(0,0,1),g.push(w/a),g.push(1-v/c)}}for(let v=0;v<c;v++)for(let M=0;M<a;M++){const w=M+l*v,y=M+l*(v+1),x=M+1+l*(v+1),b=M+1+l*v;f.push(w,y,b),f.push(y,x,b)}this.setIndex(f),this.setAttribute("position",new pe(p,3)),this.setAttribute("normal",new pe(m,3)),this.setAttribute("uv",new pe(g,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new vs(t.width,t.height,t.widthSegments,t.heightSegments)}}class Ey extends be{constructor(t=new eM([new tt(0,.5),new tt(-.5,-.5),new tt(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const i=[],n=[],s=[],r=[];let a=0,c=0;if(Array.isArray(t)===!1)l(t);else for(let h=0;h<t.length;h++)l(t[h]),this.addGroup(a,c,h),a+=c,c=0;this.setIndex(i),this.setAttribute("position",new pe(n,3)),this.setAttribute("normal",new pe(s,3)),this.setAttribute("uv",new pe(r,2));function l(h){const u=n.length/3,d=h.extractPoints(e);let f=d.shape;const p=d.holes;vd.isClockWise(f)===!1&&(f=f.reverse());for(let g=0,v=p.length;g<v;g++){const M=p[g];vd.isClockWise(M)===!0&&(p[g]=M.reverse())}const m=vd.triangulateShape(f,p);for(let g=0,v=p.length;g<v;g++){const M=p[g];f=f.concat(M)}for(let g=0,v=f.length;g<v;g++){const M=f[g];n.push(M.x,M.y,0),s.push(0,0,1),r.push(M.x,M.y)}for(let g=0,v=m.length;g<v;g++){const M=m[g],w=M[0]+u,y=M[1]+u,x=M[2]+u;i.push(w,y,x),c+=3}}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON(),e=this.parameters.shapes;return bI(e,t)}static fromJSON(t,e){const i=[];for(let n=0,s=t.shapes.length;n<s;n++){const r=e[t.shapes[n]];i.push(r)}return new Ey(i,t.curveSegments)}}function bI(o,t){if(t.shapes=[],Array.isArray(o))for(let e=0,i=o.length;e<i;e++){const n=o[e];t.shapes.push(n.uuid)}else t.shapes.push(o.uuid);return t}class hn extends be{constructor(t=1,e=32,i=16,n=0,s=Math.PI*2,r=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:s,thetaStart:r,thetaLength:a},e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));const c=Math.min(r+a,Math.PI);let l=0;const h=[],u=new T,d=new T,f=[],p=[],m=[],g=[];for(let v=0;v<=i;v++){const M=[],w=v/i,y=r+w*a,x=t*Math.cos(y),b=Math.sqrt(t*t-x*x);let E=0;v===0&&r===0?E=.5/e:v===i&&c===Math.PI&&(E=-.5/e);for(let S=0;S<=e;S++){const A=S/e,_=n+A*s;u.x=-b*Math.cos(_),u.y=x,u.z=b*Math.sin(_),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),g.push(A+E,1-w),M.push(l++)}h.push(M)}for(let v=0;v<i;v++)for(let M=0;M<e;M++){const w=h[v][M+1],y=h[v][M],x=h[v+1][M],b=h[v+1][M+1];(v!==0||r>0)&&f.push(w,y,b),(v!==i-1||c<Math.PI)&&f.push(y,x,b)}this.setIndex(f),this.setAttribute("position",new pe(p,3)),this.setAttribute("normal",new pe(m,3)),this.setAttribute("uv",new pe(g,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new hn(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class Ay extends be{constructor(t=1,e=.4,i=12,n=48,s=Math.PI*2,r=0,a=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:s,thetaStart:r,thetaLength:a},i=Math.floor(i),n=Math.floor(n);const c=[],l=[],h=[],u=[],d=new T,f=new T,p=new T;for(let m=0;m<=i;m++){const g=r+m/i*a;for(let v=0;v<=n;v++){const M=v/n*s;f.x=(t+e*Math.cos(g))*Math.cos(M),f.y=(t+e*Math.cos(g))*Math.sin(M),f.z=e*Math.sin(g),l.push(f.x,f.y,f.z),d.x=t*Math.cos(M),d.y=t*Math.sin(M),p.subVectors(f,d).normalize(),h.push(p.x,p.y,p.z),u.push(v/n),u.push(m/i)}}for(let m=1;m<=i;m++)for(let g=1;g<=n;g++){const v=(n+1)*m+g-1,M=(n+1)*(m-1)+g-1,w=(n+1)*(m-1)+g,y=(n+1)*m+g;c.push(v,M,y),c.push(M,w,y)}this.setIndex(c),this.setAttribute("position",new pe(l,3)),this.setAttribute("normal",new pe(h,3)),this.setAttribute("uv",new pe(u,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Ay(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class ok extends be{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},t!==null){const e=[],i=new Set,n=new T,s=new T;if(t.index!==null){const r=t.attributes.position,a=t.index;let c=t.groups;c.length===0&&(c=[{start:0,count:a.count,materialIndex:0}]);for(let l=0,h=c.length;l<h;++l){const u=c[l],d=u.start,f=u.count;for(let p=d,m=d+f;p<m;p+=3)for(let g=0;g<3;g++){const v=a.getX(p+g),M=a.getX(p+(g+1)%3);n.fromBufferAttribute(r,v),s.fromBufferAttribute(r,M),hx(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}}else{const r=t.attributes.position;for(let a=0,c=r.count/3;a<c;a++)for(let l=0;l<3;l++){const h=3*a+l,u=3*a+(l+1)%3;n.fromBufferAttribute(r,h),s.fromBufferAttribute(r,u),hx(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}this.setAttribute("position",new pe(e,3))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}}function hx(o,t,e){const i=`${o.x},${o.y},${o.z}-${t.x},${t.y},${t.z}`,n=`${t.x},${t.y},${t.z}-${o.x},${o.y},${o.z}`;return e.has(i)===!0||e.has(n)===!0?!1:(e.add(i),e.add(n),!0)}function Mu(o){const t={};for(const e in o){t[e]={};for(const i in o[e]){const n=o[e][i];if(ux(n))n.isRenderTargetTexture?(Ht("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[e][i]=null):t[e][i]=n.clone();else if(Array.isArray(n))if(ux(n[0])){const s=[];for(let r=0,a=n.length;r<a;r++)s[r]=n[r].clone();t[e][i]=s}else t[e][i]=n.slice();else t[e][i]=n}}return t}function ws(o){const t={};for(let e=0;e<o.length;e++){const i=Mu(o[e]);for(const n in i)t[n]=i[n]}return t}function ux(o){return o&&(o.isColor||o.isMatrix3||o.isMatrix4||o.isVector2||o.isVector3||o.isVector4||o.isTexture||o.isQuaternion)}function SI(o){const t=[];for(let e=0;e<o.length;e++)t.push(o[e].clone());return t}function AA(o){const t=o.getRenderTarget();return t===null?o.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:He.workingColorSpace}const EI={clone:Mu,merge:ws};var AI=`void main() {
|
|
784
784
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
785
785
|
}`,_I=`void main() {
|
|
786
786
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
@@ -4454,7 +4454,7 @@ void main() {
|
|
|
4454
4454
|
#include <tonemapping_fragment>
|
|
4455
4455
|
#include <colorspace_fragment>
|
|
4456
4456
|
#include <fog_fragment>
|
|
4457
|
-
}`,ue={alphahash_fragment:hD,alphahash_pars_fragment:uD,alphamap_fragment:dD,alphamap_pars_fragment:fD,alphatest_fragment:pD,alphatest_pars_fragment:mD,aomap_fragment:gD,aomap_pars_fragment:vD,batching_pars_vertex:MD,batching_vertex:yD,begin_vertex:wD,beginnormal_vertex:xD,bsdfs:bD,iridescence_fragment:SD,bumpmap_pars_fragment:ED,clipping_planes_fragment:AD,clipping_planes_pars_fragment:_D,clipping_planes_pars_vertex:TD,clipping_planes_vertex:RD,color_fragment:ID,color_pars_fragment:DD,color_pars_vertex:CD,color_vertex:OD,common:PD,cube_uv_reflection_fragment:ND,defaultnormal_vertex:LD,displacementmap_pars_vertex:kD,displacementmap_vertex:FD,emissivemap_fragment:UD,emissivemap_pars_fragment:zD,colorspace_fragment:BD,colorspace_pars_fragment:HD,envmap_fragment:GD,envmap_common_pars_fragment:VD,envmap_pars_fragment:WD,envmap_pars_vertex:XD,envmap_physical_pars_fragment:i6,envmap_vertex:$D,fog_vertex:YD,fog_pars_vertex:KD,fog_fragment:qD,fog_pars_fragment:ZD,gradientmap_pars_fragment:JD,lightmap_pars_fragment:jD,lights_lambert_fragment:QD,lights_lambert_pars_fragment:t6,lights_pars_begin:e6,lights_toon_fragment:n6,lights_toon_pars_fragment:s6,lights_phong_fragment:r6,lights_phong_pars_fragment:a6,lights_physical_fragment:o6,lights_physical_pars_fragment:c6,lights_fragment_begin:l6,lights_fragment_maps:h6,lights_fragment_end:u6,lightprobes_pars_fragment:d6,logdepthbuf_fragment:f6,logdepthbuf_pars_fragment:p6,logdepthbuf_pars_vertex:m6,logdepthbuf_vertex:g6,map_fragment:v6,map_pars_fragment:M6,map_particle_fragment:y6,map_particle_pars_fragment:w6,metalnessmap_fragment:x6,metalnessmap_pars_fragment:b6,morphinstance_vertex:S6,morphcolor_vertex:E6,morphnormal_vertex:A6,morphtarget_pars_vertex:_6,morphtarget_vertex:T6,normal_fragment_begin:R6,normal_fragment_maps:I6,normal_pars_fragment:D6,normal_pars_vertex:C6,normal_vertex:O6,normalmap_pars_fragment:P6,clearcoat_normal_fragment_begin:N6,clearcoat_normal_fragment_maps:L6,clearcoat_pars_fragment:k6,iridescence_pars_fragment:F6,opaque_fragment:U6,packing:z6,premultiplied_alpha_fragment:B6,project_vertex:H6,dithering_fragment:G6,dithering_pars_fragment:V6,roughnessmap_fragment:W6,roughnessmap_pars_fragment:X6,shadowmap_pars_fragment:$6,shadowmap_pars_vertex:Y6,shadowmap_vertex:K6,shadowmask_pars_fragment:q6,skinbase_vertex:Z6,skinning_pars_vertex:J6,skinning_vertex:j6,skinnormal_vertex:Q6,specularmap_fragment:tC,specularmap_pars_fragment:eC,tonemapping_fragment:iC,tonemapping_pars_fragment:nC,transmission_fragment:sC,transmission_pars_fragment:rC,uv_pars_fragment:aC,uv_pars_vertex:oC,uv_vertex:cC,worldpos_vertex:lC,background_vert:hC,background_frag:uC,backgroundCube_vert:dC,backgroundCube_frag:fC,cube_vert:pC,cube_frag:mC,depth_vert:gC,depth_frag:vC,distance_vert:MC,distance_frag:yC,equirect_vert:wC,equirect_frag:xC,linedashed_vert:bC,linedashed_frag:SC,meshbasic_vert:EC,meshbasic_frag:AC,meshlambert_vert:_C,meshlambert_frag:TC,meshmatcap_vert:RC,meshmatcap_frag:IC,meshnormal_vert:DC,meshnormal_frag:CC,meshphong_vert:OC,meshphong_frag:PC,meshphysical_vert:NC,meshphysical_frag:LC,meshtoon_vert:kC,meshtoon_frag:FC,points_vert:UC,points_frag:zC,shadow_vert:BC,shadow_frag:HC,sprite_vert:GC,sprite_frag:VC},bt={common:{diffuse:{value:new rt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new de},alphaMap:{value:null},alphaMapTransform:{value:new de},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new de}},envmap:{envMap:{value:null},envMapRotation:{value:new de},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new de}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new de}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new de},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new de},normalScale:{value:new tt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new de},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new de}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new de}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new de}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new rt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new T},probesMax:{value:new T},probesResolution:{value:new T}},points:{diffuse:{value:new rt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new de},alphaTest:{value:0},uvTransform:{value:new de}},sprite:{diffuse:{value:new rt(16777215)},opacity:{value:1},center:{value:new tt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new de},alphaMap:{value:null},alphaMapTransform:{value:new de},alphaTest:{value:0}}},fa={basic:{uniforms:ws([bt.common,bt.specularmap,bt.envmap,bt.aomap,bt.lightmap,bt.fog]),vertexShader:ue.meshbasic_vert,fragmentShader:ue.meshbasic_frag},lambert:{uniforms:ws([bt.common,bt.specularmap,bt.envmap,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.fog,bt.lights,{emissive:{value:new rt(0)},envMapIntensity:{value:1}}]),vertexShader:ue.meshlambert_vert,fragmentShader:ue.meshlambert_frag},phong:{uniforms:ws([bt.common,bt.specularmap,bt.envmap,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.fog,bt.lights,{emissive:{value:new rt(0)},specular:{value:new rt(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:ue.meshphong_vert,fragmentShader:ue.meshphong_frag},standard:{uniforms:ws([bt.common,bt.envmap,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.roughnessmap,bt.metalnessmap,bt.fog,bt.lights,{emissive:{value:new rt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ue.meshphysical_vert,fragmentShader:ue.meshphysical_frag},toon:{uniforms:ws([bt.common,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.gradientmap,bt.fog,bt.lights,{emissive:{value:new rt(0)}}]),vertexShader:ue.meshtoon_vert,fragmentShader:ue.meshtoon_frag},matcap:{uniforms:ws([bt.common,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.fog,{matcap:{value:null}}]),vertexShader:ue.meshmatcap_vert,fragmentShader:ue.meshmatcap_frag},points:{uniforms:ws([bt.points,bt.fog]),vertexShader:ue.points_vert,fragmentShader:ue.points_frag},dashed:{uniforms:ws([bt.common,bt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ue.linedashed_vert,fragmentShader:ue.linedashed_frag},depth:{uniforms:ws([bt.common,bt.displacementmap]),vertexShader:ue.depth_vert,fragmentShader:ue.depth_frag},normal:{uniforms:ws([bt.common,bt.bumpmap,bt.normalmap,bt.displacementmap,{opacity:{value:1}}]),vertexShader:ue.meshnormal_vert,fragmentShader:ue.meshnormal_frag},sprite:{uniforms:ws([bt.sprite,bt.fog]),vertexShader:ue.sprite_vert,fragmentShader:ue.sprite_frag},background:{uniforms:{uvTransform:{value:new de},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ue.background_vert,fragmentShader:ue.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new de}},vertexShader:ue.backgroundCube_vert,fragmentShader:ue.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ue.cube_vert,fragmentShader:ue.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ue.equirect_vert,fragmentShader:ue.equirect_frag},distance:{uniforms:ws([bt.common,bt.displacementmap,{referencePosition:{value:new T},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ue.distance_vert,fragmentShader:ue.distance_frag},shadow:{uniforms:ws([bt.lights,bt.fog,{color:{value:new rt(0)},opacity:{value:1}}]),vertexShader:ue.shadow_vert,fragmentShader:ue.shadow_frag}};fa.physical={uniforms:ws([fa.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new de},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new de},clearcoatNormalScale:{value:new tt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new de},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new de},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new de},sheen:{value:0},sheenColor:{value:new rt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new de},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new de},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new de},transmissionSamplerSize:{value:new tt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new de},attenuationDistance:{value:0},attenuationColor:{value:new rt(0)},specularColor:{value:new rt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new de},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new de},anisotropyVector:{value:new tt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new de}}]),vertexShader:ue.meshphysical_vert,fragmentShader:ue.meshphysical_frag};const Mp={r:0,b:0,g:0},WC=new Gt,NA=new de;NA.set(-1,0,0,0,1,0,0,0,1);function XC(o,t,e,i,n,s){const r=new rt(0);let a=n===!0?0:1,c,l,h=null,u=0,d=null;function f(M){let w=M.isScene===!0?M.background:null;if(w&&w.isTexture){const y=M.backgroundBlurriness>0;w=t.get(w,y)}return w}function p(M){let w=!1;const y=f(M);y===null?g(r,a):y&&y.isColor&&(g(y,1),w=!0);const x=o.xr.getEnvironmentBlendMode();x==="additive"?e.buffers.color.setClear(0,0,0,1,s):x==="alpha-blend"&&e.buffers.color.setClear(0,0,0,0,s),(o.autoClear||w)&&(e.buffers.depth.setTest(!0),e.buffers.depth.setMask(!0),e.buffers.color.setMask(!0),o.clear(o.autoClearColor,o.autoClearDepth,o.autoClearStencil))}function m(M,w){const y=f(w);y&&(y.isCubeTexture||y.mapping===Dm)?(l===void 0&&(l=new yt(new en(1,1,1),new De({name:"BackgroundCubeMaterial",uniforms:Mu(fa.backgroundCube.uniforms),vertexShader:fa.backgroundCube.vertexShader,fragmentShader:fa.backgroundCube.fragmentShader,side:zi,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(x,b,E){this.matrixWorld.copyPosition(E.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l)),l.material.uniforms.envMap.value=y,l.material.uniforms.backgroundBlurriness.value=w.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(WC.makeRotationFromEuler(w.backgroundRotation)).transpose(),y.isCubeTexture&&y.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(NA),l.material.toneMapped=He.getTransfer(y.colorSpace)!==ui,(h!==y||u!==y.version||d!==o.toneMapping)&&(l.material.needsUpdate=!0,h=y,u=y.version,d=o.toneMapping),l.layers.enableAll(),M.unshift(l,l.geometry,l.material,0,0,null)):y&&y.isTexture&&(c===void 0&&(c=new yt(new vs(2,2),new De({name:"BackgroundMaterial",uniforms:Mu(fa.background.uniforms),vertexShader:fa.background.vertexShader,fragmentShader:fa.background.fragmentShader,side:Ba,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c)),c.material.uniforms.t2D.value=y,c.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,c.material.toneMapped=He.getTransfer(y.colorSpace)!==ui,y.matrixAutoUpdate===!0&&y.updateMatrix(),c.material.uniforms.uvTransform.value.copy(y.matrix),(h!==y||u!==y.version||d!==o.toneMapping)&&(c.material.needsUpdate=!0,h=y,u=y.version,d=o.toneMapping),c.layers.enableAll(),M.unshift(c,c.geometry,c.material,0,0,null))}function g(M,w){M.getRGB(Mp,AA(o)),e.buffers.color.setClear(Mp.r,Mp.g,Mp.b,w,s)}function v(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return r},setClearColor:function(M,w=1){r.set(M),a=w,g(r,a)},getClearAlpha:function(){return a},setClearAlpha:function(M){a=M,g(r,a)},render:p,addToRenderList:m,dispose:v}}function $C(o,t){const e=o.getParameter(o.MAX_VERTEX_ATTRIBS),i={},n=d(null);let s=n,r=!1;function a(I,D,O,P,N){let k=!1;const B=u(I,P,O,D);s!==B&&(s=B,l(s.object)),k=f(I,P,O,N),k&&p(I,P,O,N),N!==null&&t.update(N,o.ELEMENT_ARRAY_BUFFER),(k||r)&&(r=!1,y(I,D,O,P),N!==null&&o.bindBuffer(o.ELEMENT_ARRAY_BUFFER,t.get(N).buffer))}function c(){return o.createVertexArray()}function l(I){return o.bindVertexArray(I)}function h(I){return o.deleteVertexArray(I)}function u(I,D,O,P){const N=P.wireframe===!0;let k=i[D.id];k===void 0&&(k={},i[D.id]=k);const B=I.isInstancedMesh===!0?I.id:0;let W=k[B];W===void 0&&(W={},k[B]=W);let Q=W[O.id];Q===void 0&&(Q={},W[O.id]=Q);let Z=Q[N];return Z===void 0&&(Z=d(c()),Q[N]=Z),Z}function d(I){const D=[],O=[],P=[];for(let N=0;N<e;N++)D[N]=0,O[N]=0,P[N]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:D,enabledAttributes:O,attributeDivisors:P,object:I,attributes:{},index:null}}function f(I,D,O,P){const N=s.attributes,k=D.attributes;let B=0;const W=O.getAttributes();for(const Q in W)if(W[Q].location>=0){const nt=N[Q];let ot=k[Q];if(ot===void 0&&(Q==="instanceMatrix"&&I.instanceMatrix&&(ot=I.instanceMatrix),Q==="instanceColor"&&I.instanceColor&&(ot=I.instanceColor)),nt===void 0||nt.attribute!==ot||ot&&nt.data!==ot.data)return!0;B++}return s.attributesNum!==B||s.index!==P}function p(I,D,O,P){const N={},k=D.attributes;let B=0;const W=O.getAttributes();for(const Q in W)if(W[Q].location>=0){let nt=k[Q];nt===void 0&&(Q==="instanceMatrix"&&I.instanceMatrix&&(nt=I.instanceMatrix),Q==="instanceColor"&&I.instanceColor&&(nt=I.instanceColor));const ot={};ot.attribute=nt,nt&&nt.data&&(ot.data=nt.data),N[Q]=ot,B++}s.attributes=N,s.attributesNum=B,s.index=P}function m(){const I=s.newAttributes;for(let D=0,O=I.length;D<O;D++)I[D]=0}function g(I){v(I,0)}function v(I,D){const O=s.newAttributes,P=s.enabledAttributes,N=s.attributeDivisors;O[I]=1,P[I]===0&&(o.enableVertexAttribArray(I),P[I]=1),N[I]!==D&&(o.vertexAttribDivisor(I,D),N[I]=D)}function M(){const I=s.newAttributes,D=s.enabledAttributes;for(let O=0,P=D.length;O<P;O++)D[O]!==I[O]&&(o.disableVertexAttribArray(O),D[O]=0)}function w(I,D,O,P,N,k,B){B===!0?o.vertexAttribIPointer(I,D,O,N,k):o.vertexAttribPointer(I,D,O,P,N,k)}function y(I,D,O,P){m();const N=P.attributes,k=O.getAttributes(),B=D.defaultAttributeValues;for(const W in k){const Q=k[W];if(Q.location>=0){let Z=N[W];if(Z===void 0&&(W==="instanceMatrix"&&I.instanceMatrix&&(Z=I.instanceMatrix),W==="instanceColor"&&I.instanceColor&&(Z=I.instanceColor)),Z!==void 0){const nt=Z.normalized,ot=Z.itemSize,Ut=t.get(Z);if(Ut===void 0)continue;const Zt=Ut.buffer,jt=Ut.type,K=Ut.bytesPerElement,lt=jt===o.INT||jt===o.UNSIGNED_INT||Z.gpuType===oy;if(Z.isInterleavedBufferAttribute){const ct=Z.data,V=ct.stride,Lt=Z.offset;if(ct.isInstancedInterleavedBuffer){for(let Xt=0;Xt<Q.locationSize;Xt++)v(Q.location+Xt,ct.meshPerAttribute);I.isInstancedMesh!==!0&&P._maxInstanceCount===void 0&&(P._maxInstanceCount=ct.meshPerAttribute*ct.count)}else for(let Xt=0;Xt<Q.locationSize;Xt++)g(Q.location+Xt);o.bindBuffer(o.ARRAY_BUFFER,Zt);for(let Xt=0;Xt<Q.locationSize;Xt++)w(Q.location+Xt,ot/Q.locationSize,jt,nt,V*K,(Lt+ot/Q.locationSize*Xt)*K,lt)}else{if(Z.isInstancedBufferAttribute){for(let ct=0;ct<Q.locationSize;ct++)v(Q.location+ct,Z.meshPerAttribute);I.isInstancedMesh!==!0&&P._maxInstanceCount===void 0&&(P._maxInstanceCount=Z.meshPerAttribute*Z.count)}else for(let ct=0;ct<Q.locationSize;ct++)g(Q.location+ct);o.bindBuffer(o.ARRAY_BUFFER,Zt);for(let ct=0;ct<Q.locationSize;ct++)w(Q.location+ct,ot/Q.locationSize,jt,nt,ot*K,ot/Q.locationSize*ct*K,lt)}}else if(B!==void 0){const nt=B[W];if(nt!==void 0)switch(nt.length){case 2:o.vertexAttrib2fv(Q.location,nt);break;case 3:o.vertexAttrib3fv(Q.location,nt);break;case 4:o.vertexAttrib4fv(Q.location,nt);break;default:o.vertexAttrib1fv(Q.location,nt)}}}}M()}function x(){A();for(const I in i){const D=i[I];for(const O in D){const P=D[O];for(const N in P){const k=P[N];for(const B in k)h(k[B].object),delete k[B];delete P[N]}}delete i[I]}}function b(I){if(i[I.id]===void 0)return;const D=i[I.id];for(const O in D){const P=D[O];for(const N in P){const k=P[N];for(const B in k)h(k[B].object),delete k[B];delete P[N]}}delete i[I.id]}function E(I){for(const D in i){const O=i[D];for(const P in O){const N=O[P];if(N[I.id]===void 0)continue;const k=N[I.id];for(const B in k)h(k[B].object),delete k[B];delete N[I.id]}}}function S(I){for(const D in i){const O=i[D],P=I.isInstancedMesh===!0?I.id:0,N=O[P];if(N!==void 0){for(const k in N){const B=N[k];for(const W in B)h(B[W].object),delete B[W];delete N[k]}delete O[P],Object.keys(O).length===0&&delete i[D]}}}function A(){_(),r=!0,s!==n&&(s=n,l(s.object))}function _(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:a,reset:A,resetDefaultState:_,dispose:x,releaseStatesOfGeometry:b,releaseStatesOfObject:S,releaseStatesOfProgram:E,initAttributes:m,enableAttribute:g,disableUnusedAttributes:M}}function YC(o,t,e){let i;function n(c){i=c}function s(c,l){o.drawArrays(i,c,l),e.update(l,i,1)}function r(c,l,h){h!==0&&(o.drawArraysInstanced(i,c,l,h),e.update(l,i,h))}function a(c,l,h){if(h===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,l,0,h);let d=0;for(let f=0;f<h;f++)d+=l[f];e.update(d,i,1)}this.setMode=n,this.render=s,this.renderInstances=r,this.renderMultiDraw=a}function KC(o,t,e,i){let n;function s(){if(n!==void 0)return n;if(t.has("EXT_texture_filter_anisotropic")===!0){const E=t.get("EXT_texture_filter_anisotropic");n=o.getParameter(E.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n}function r(E){return!(E!==tn&&i.convert(E)!==o.getParameter(o.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(E){const S=E===Ye&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(E!==fs&&i.convert(E)!==o.getParameter(o.IMPLEMENTATION_COLOR_READ_TYPE)&&E!==ts&&!S)}function c(E){if(E==="highp"){if(o.getShaderPrecisionFormat(o.VERTEX_SHADER,o.HIGH_FLOAT).precision>0&&o.getShaderPrecisionFormat(o.FRAGMENT_SHADER,o.HIGH_FLOAT).precision>0)return"highp";E="mediump"}return E==="mediump"&&o.getShaderPrecisionFormat(o.VERTEX_SHADER,o.MEDIUM_FLOAT).precision>0&&o.getShaderPrecisionFormat(o.FRAGMENT_SHADER,o.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=e.precision!==void 0?e.precision:"highp";const h=c(l);h!==l&&(Ht("WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);const u=e.logarithmicDepthBuffer===!0,d=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control");e.reversedDepthBuffer===!0&&d===!1&&Ht("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");const f=o.getParameter(o.MAX_TEXTURE_IMAGE_UNITS),p=o.getParameter(o.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=o.getParameter(o.MAX_TEXTURE_SIZE),g=o.getParameter(o.MAX_CUBE_MAP_TEXTURE_SIZE),v=o.getParameter(o.MAX_VERTEX_ATTRIBS),M=o.getParameter(o.MAX_VERTEX_UNIFORM_VECTORS),w=o.getParameter(o.MAX_VARYING_VECTORS),y=o.getParameter(o.MAX_FRAGMENT_UNIFORM_VECTORS),x=o.getParameter(o.MAX_SAMPLES),b=o.getParameter(o.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:r,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:d,maxTextures:f,maxVertexTextures:p,maxTextureSize:m,maxCubemapSize:g,maxAttributes:v,maxVertexUniforms:M,maxVaryings:w,maxFragmentUniforms:y,maxSamples:x,samples:b}}function qC(o){const t=this;let e=null,i=0,n=!1,s=!1;const r=new Hr,a=new de,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const f=u.length!==0||d||i!==0||n;return n=d,i=u.length,f},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(u,d){e=h(u,d,0)},this.setState=function(u,d,f){const p=u.clippingPlanes,m=u.clipIntersection,g=u.clipShadows,v=o.get(u);if(!n||p===null||p.length===0||s&&!g)s?h(null):l();else{const M=s?0:i,w=M*4;let y=v.clippingState||null;c.value=y,y=h(p,d,w,f);for(let x=0;x!==w;++x)y[x]=e[x];v.clippingState=y,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=M}};function l(){c.value!==e&&(c.value=e,c.needsUpdate=i>0),t.numPlanes=i,t.numIntersection=0}function h(u,d,f,p){const m=u!==null?u.length:0;let g=null;if(m!==0){if(g=c.value,p!==!0||g===null){const v=f+m*4,M=d.matrixWorldInverse;a.getNormalMatrix(M),(g===null||g.length<v)&&(g=new Float32Array(v));for(let w=0,y=f;w!==m;++w,y+=4)r.copy(u[w]).applyMatrix4(M,a),r.normal.toArray(g,y),g[y+3]=r.constant}c.value=g,c.needsUpdate=!0}return t.numPlanes=m,t.numIntersection=0,g}}const fc=4,Sx=[.125,.215,.35,.446,.526,.582],Gc=20,ZC=256,Vu=new ur,Ex=new rt;let Gg=null,Vg=0,Wg=0,Xg=!1;const JC=new T;class rM{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(t,e=0,i=.1,n=100,s={}){const{size:r=256,position:a=JC}=s;Gg=this._renderer.getRenderTarget(),Vg=this._renderer.getActiveCubeFace(),Wg=this._renderer.getActiveMipmapLevel(),Xg=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(t,i,n,c,a),e>0&&this._blur(c,0,0,e),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Tx(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=_x(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t<this._lodMeshes.length;t++)this._lodMeshes[t].geometry.dispose()}_cleanup(t){this._renderer.setRenderTarget(Gg,Vg,Wg),this._renderer.xr.enabled=Xg,t.scissorTest=!1,th(t,0,0,t.width,t.height)}_fromTexture(t,e){t.mapping===wl||t.mapping===pu?this._setSize(t.image.length===0?16:t.image[0].width||t.image[0].image.width):this._setSize(t.image.width/4),Gg=this._renderer.getRenderTarget(),Vg=this._renderer.getActiveCubeFace(),Wg=this._renderer.getActiveMipmapLevel(),Xg=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const i=e||this._allocateTargets();return this._textureToCubeUV(t,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const t=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,i={magFilter:Me,minFilter:Me,generateMipmaps:!1,type:Ye,format:tn,colorSpace:G0,depthBuffer:!1},n=Ax(t,e,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==t||this._pingPongRenderTarget.height!==e){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ax(t,e,i);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=jC(s)),this._blurMaterial=tO(s,t,e),this._ggxMaterial=QC(s,t,e)}return n}_compileMaterial(t){const e=new yt(new be,t);this._renderer.compile(e,Vu)}_sceneToCubeUV(t,e,i,n,s){const c=new jn(90,1,e,i),l=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],u=this._renderer,d=u.autoClear,f=u.toneMapping;u.getClearColor(Ex),u.toneMapping=ka,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(n),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new yt(new en,new Is({name:"PMREM.Background",side:zi,depthWrite:!1,depthTest:!1})));const m=this._backgroundBox,g=m.material;let v=!1;const M=t.background;M?M.isColor&&(g.color.copy(M),t.background=null,v=!0):(g.color.copy(Ex),v=!0);for(let w=0;w<6;w++){const y=w%3;y===0?(c.up.set(0,l[w],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x+h[w],s.y,s.z)):y===1?(c.up.set(0,0,l[w]),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y+h[w],s.z)):(c.up.set(0,l[w],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y,s.z+h[w]));const x=this._cubeSize;th(n,y*x,w>2?x:0,x,x),u.setRenderTarget(n),v&&u.render(m,c),u.render(t,c)}u.toneMapping=f,u.autoClear=d,t.background=M}_textureToCubeUV(t,e){const i=this._renderer,n=t.mapping===wl||t.mapping===pu;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=Tx()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=_x());const s=n?this._cubemapMaterial:this._equirectMaterial,r=this._lodMeshes[0];r.material=s;const a=s.uniforms;a.envMap.value=t;const c=this._cubeSize;th(e,0,0,3*c,2*c),i.setRenderTarget(e),i.render(r,Vu)}_applyPMREM(t){const e=this._renderer,i=e.autoClear;e.autoClear=!1;const n=this._lodMeshes.length;for(let s=1;s<n;s++)this._applyGGXFilter(t,s-1,s);e.autoClear=i}_applyGGXFilter(t,e,i){const n=this._renderer,s=this._pingPongRenderTarget,r=this._ggxMaterial,a=this._lodMeshes[i];a.material=r;const c=r.uniforms,l=i/(this._lodMeshes.length-1),h=e/(this._lodMeshes.length-1),u=Math.sqrt(l*l-h*h),d=0+l*1.25,f=u*d,{_lodMax:p}=this,m=this._sizeLods[i],g=3*m*(i>p-fc?i-p+fc:0),v=4*(this._cubeSize-m);c.envMap.value=t.texture,c.roughness.value=f,c.mipInt.value=p-e,th(s,g,v,3*m,2*m),n.setRenderTarget(s),n.render(a,Vu),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=p-i,th(t,g,v,3*m,2*m),n.setRenderTarget(t),n.render(a,Vu)}_blur(t,e,i,n,s){const r=this._pingPongRenderTarget;this._halfBlur(t,r,e,i,n,"latitudinal",s),this._halfBlur(r,t,i,i,n,"longitudinal",s)}_halfBlur(t,e,i,n,s,r,a){const c=this._renderer,l=this._blurMaterial;r!=="latitudinal"&&r!=="longitudinal"&&le("blur direction must be either latitudinal or longitudinal!");const h=3,u=this._lodMeshes[n];u.material=l;const d=l.uniforms,f=this._sizeLods[i]-1,p=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Gc-1),m=s/p,g=isFinite(s)?1+Math.floor(h*m):Gc;g>Gc&&Ht(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Gc}`);const v=[];let M=0;for(let E=0;E<Gc;++E){const S=E/m,A=Math.exp(-S*S/2);v.push(A),E===0?M+=A:E<g&&(M+=2*A)}for(let E=0;E<v.length;E++)v[E]=v[E]/M;d.envMap.value=t.texture,d.samples.value=g,d.weights.value=v,d.latitudinal.value=r==="latitudinal",a&&(d.poleAxis.value=a);const{_lodMax:w}=this;d.dTheta.value=p,d.mipInt.value=w-i;const y=this._sizeLods[n],x=3*y*(n>w-fc?n-w+fc:0),b=4*(this._cubeSize-y);th(e,x,b,3*y,2*y),c.setRenderTarget(e),c.render(u,Vu)}}function jC(o){const t=[],e=[],i=[];let n=o;const s=o-fc+1+Sx.length;for(let r=0;r<s;r++){const a=Math.pow(2,n);t.push(a);let c=1/a;r>o-fc?c=Sx[r-o+fc-1]:r===0&&(c=0),e.push(c);const l=1/(a-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,p=6,m=3,g=2,v=1,M=new Float32Array(m*p*f),w=new Float32Array(g*p*f),y=new Float32Array(v*p*f);for(let b=0;b<f;b++){const E=b%3*2/3-1,S=b>2?0:-1,A=[E,S,0,E+2/3,S,0,E+2/3,S+1,0,E,S,0,E+2/3,S+1,0,E,S+1,0];M.set(A,m*p*b),w.set(d,g*p*b);const _=[b,b,b,b,b,b];y.set(_,v*p*b)}const x=new be;x.setAttribute("position",new ye(M,m)),x.setAttribute("uv",new ye(w,g)),x.setAttribute("faceIndex",new ye(y,v)),i.push(new yt(x,null)),n>fc&&n--}return{lodMeshes:i,sizeLods:t,sigmas:e}}function Ax(o,t,e){const i=new Qe(o,t,e);return i.texture.mapping=Dm,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function th(o,t,e,i,n){o.viewport.set(t,e,i,n),o.scissor.set(t,e,i,n)}function QC(o,t,e){return new De({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:ZC,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${o}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Nm(),fragmentShader:`
|
|
4457
|
+
}`,ue={alphahash_fragment:hD,alphahash_pars_fragment:uD,alphamap_fragment:dD,alphamap_pars_fragment:fD,alphatest_fragment:pD,alphatest_pars_fragment:mD,aomap_fragment:gD,aomap_pars_fragment:vD,batching_pars_vertex:MD,batching_vertex:yD,begin_vertex:wD,beginnormal_vertex:xD,bsdfs:bD,iridescence_fragment:SD,bumpmap_pars_fragment:ED,clipping_planes_fragment:AD,clipping_planes_pars_fragment:_D,clipping_planes_pars_vertex:TD,clipping_planes_vertex:RD,color_fragment:ID,color_pars_fragment:DD,color_pars_vertex:CD,color_vertex:OD,common:PD,cube_uv_reflection_fragment:ND,defaultnormal_vertex:LD,displacementmap_pars_vertex:kD,displacementmap_vertex:FD,emissivemap_fragment:UD,emissivemap_pars_fragment:zD,colorspace_fragment:BD,colorspace_pars_fragment:HD,envmap_fragment:GD,envmap_common_pars_fragment:VD,envmap_pars_fragment:WD,envmap_pars_vertex:XD,envmap_physical_pars_fragment:i6,envmap_vertex:$D,fog_vertex:YD,fog_pars_vertex:KD,fog_fragment:qD,fog_pars_fragment:ZD,gradientmap_pars_fragment:JD,lightmap_pars_fragment:jD,lights_lambert_fragment:QD,lights_lambert_pars_fragment:t6,lights_pars_begin:e6,lights_toon_fragment:n6,lights_toon_pars_fragment:s6,lights_phong_fragment:r6,lights_phong_pars_fragment:a6,lights_physical_fragment:o6,lights_physical_pars_fragment:c6,lights_fragment_begin:l6,lights_fragment_maps:h6,lights_fragment_end:u6,lightprobes_pars_fragment:d6,logdepthbuf_fragment:f6,logdepthbuf_pars_fragment:p6,logdepthbuf_pars_vertex:m6,logdepthbuf_vertex:g6,map_fragment:v6,map_pars_fragment:M6,map_particle_fragment:y6,map_particle_pars_fragment:w6,metalnessmap_fragment:x6,metalnessmap_pars_fragment:b6,morphinstance_vertex:S6,morphcolor_vertex:E6,morphnormal_vertex:A6,morphtarget_pars_vertex:_6,morphtarget_vertex:T6,normal_fragment_begin:R6,normal_fragment_maps:I6,normal_pars_fragment:D6,normal_pars_vertex:C6,normal_vertex:O6,normalmap_pars_fragment:P6,clearcoat_normal_fragment_begin:N6,clearcoat_normal_fragment_maps:L6,clearcoat_pars_fragment:k6,iridescence_pars_fragment:F6,opaque_fragment:U6,packing:z6,premultiplied_alpha_fragment:B6,project_vertex:H6,dithering_fragment:G6,dithering_pars_fragment:V6,roughnessmap_fragment:W6,roughnessmap_pars_fragment:X6,shadowmap_pars_fragment:$6,shadowmap_pars_vertex:Y6,shadowmap_vertex:K6,shadowmask_pars_fragment:q6,skinbase_vertex:Z6,skinning_pars_vertex:J6,skinning_vertex:j6,skinnormal_vertex:Q6,specularmap_fragment:tC,specularmap_pars_fragment:eC,tonemapping_fragment:iC,tonemapping_pars_fragment:nC,transmission_fragment:sC,transmission_pars_fragment:rC,uv_pars_fragment:aC,uv_pars_vertex:oC,uv_vertex:cC,worldpos_vertex:lC,background_vert:hC,background_frag:uC,backgroundCube_vert:dC,backgroundCube_frag:fC,cube_vert:pC,cube_frag:mC,depth_vert:gC,depth_frag:vC,distance_vert:MC,distance_frag:yC,equirect_vert:wC,equirect_frag:xC,linedashed_vert:bC,linedashed_frag:SC,meshbasic_vert:EC,meshbasic_frag:AC,meshlambert_vert:_C,meshlambert_frag:TC,meshmatcap_vert:RC,meshmatcap_frag:IC,meshnormal_vert:DC,meshnormal_frag:CC,meshphong_vert:OC,meshphong_frag:PC,meshphysical_vert:NC,meshphysical_frag:LC,meshtoon_vert:kC,meshtoon_frag:FC,points_vert:UC,points_frag:zC,shadow_vert:BC,shadow_frag:HC,sprite_vert:GC,sprite_frag:VC},bt={common:{diffuse:{value:new rt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new de},alphaMap:{value:null},alphaMapTransform:{value:new de},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new de}},envmap:{envMap:{value:null},envMapRotation:{value:new de},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new de}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new de}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new de},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new de},normalScale:{value:new tt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new de},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new de}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new de}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new de}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new rt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new T},probesMax:{value:new T},probesResolution:{value:new T}},points:{diffuse:{value:new rt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new de},alphaTest:{value:0},uvTransform:{value:new de}},sprite:{diffuse:{value:new rt(16777215)},opacity:{value:1},center:{value:new tt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new de},alphaMap:{value:null},alphaMapTransform:{value:new de},alphaTest:{value:0}}},fa={basic:{uniforms:ws([bt.common,bt.specularmap,bt.envmap,bt.aomap,bt.lightmap,bt.fog]),vertexShader:ue.meshbasic_vert,fragmentShader:ue.meshbasic_frag},lambert:{uniforms:ws([bt.common,bt.specularmap,bt.envmap,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.fog,bt.lights,{emissive:{value:new rt(0)},envMapIntensity:{value:1}}]),vertexShader:ue.meshlambert_vert,fragmentShader:ue.meshlambert_frag},phong:{uniforms:ws([bt.common,bt.specularmap,bt.envmap,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.fog,bt.lights,{emissive:{value:new rt(0)},specular:{value:new rt(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:ue.meshphong_vert,fragmentShader:ue.meshphong_frag},standard:{uniforms:ws([bt.common,bt.envmap,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.roughnessmap,bt.metalnessmap,bt.fog,bt.lights,{emissive:{value:new rt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ue.meshphysical_vert,fragmentShader:ue.meshphysical_frag},toon:{uniforms:ws([bt.common,bt.aomap,bt.lightmap,bt.emissivemap,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.gradientmap,bt.fog,bt.lights,{emissive:{value:new rt(0)}}]),vertexShader:ue.meshtoon_vert,fragmentShader:ue.meshtoon_frag},matcap:{uniforms:ws([bt.common,bt.bumpmap,bt.normalmap,bt.displacementmap,bt.fog,{matcap:{value:null}}]),vertexShader:ue.meshmatcap_vert,fragmentShader:ue.meshmatcap_frag},points:{uniforms:ws([bt.points,bt.fog]),vertexShader:ue.points_vert,fragmentShader:ue.points_frag},dashed:{uniforms:ws([bt.common,bt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ue.linedashed_vert,fragmentShader:ue.linedashed_frag},depth:{uniforms:ws([bt.common,bt.displacementmap]),vertexShader:ue.depth_vert,fragmentShader:ue.depth_frag},normal:{uniforms:ws([bt.common,bt.bumpmap,bt.normalmap,bt.displacementmap,{opacity:{value:1}}]),vertexShader:ue.meshnormal_vert,fragmentShader:ue.meshnormal_frag},sprite:{uniforms:ws([bt.sprite,bt.fog]),vertexShader:ue.sprite_vert,fragmentShader:ue.sprite_frag},background:{uniforms:{uvTransform:{value:new de},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ue.background_vert,fragmentShader:ue.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new de}},vertexShader:ue.backgroundCube_vert,fragmentShader:ue.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ue.cube_vert,fragmentShader:ue.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ue.equirect_vert,fragmentShader:ue.equirect_frag},distance:{uniforms:ws([bt.common,bt.displacementmap,{referencePosition:{value:new T},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ue.distance_vert,fragmentShader:ue.distance_frag},shadow:{uniforms:ws([bt.lights,bt.fog,{color:{value:new rt(0)},opacity:{value:1}}]),vertexShader:ue.shadow_vert,fragmentShader:ue.shadow_frag}};fa.physical={uniforms:ws([fa.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new de},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new de},clearcoatNormalScale:{value:new tt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new de},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new de},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new de},sheen:{value:0},sheenColor:{value:new rt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new de},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new de},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new de},transmissionSamplerSize:{value:new tt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new de},attenuationDistance:{value:0},attenuationColor:{value:new rt(0)},specularColor:{value:new rt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new de},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new de},anisotropyVector:{value:new tt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new de}}]),vertexShader:ue.meshphysical_vert,fragmentShader:ue.meshphysical_frag};const Mp={r:0,b:0,g:0},WC=new Gt,NA=new de;NA.set(-1,0,0,0,1,0,0,0,1);function XC(o,t,e,i,n,s){const r=new rt(0);let a=n===!0?0:1,c,l,h=null,u=0,d=null;function f(M){let w=M.isScene===!0?M.background:null;if(w&&w.isTexture){const y=M.backgroundBlurriness>0;w=t.get(w,y)}return w}function p(M){let w=!1;const y=f(M);y===null?g(r,a):y&&y.isColor&&(g(y,1),w=!0);const x=o.xr.getEnvironmentBlendMode();x==="additive"?e.buffers.color.setClear(0,0,0,1,s):x==="alpha-blend"&&e.buffers.color.setClear(0,0,0,0,s),(o.autoClear||w)&&(e.buffers.depth.setTest(!0),e.buffers.depth.setMask(!0),e.buffers.color.setMask(!0),o.clear(o.autoClearColor,o.autoClearDepth,o.autoClearStencil))}function m(M,w){const y=f(w);y&&(y.isCubeTexture||y.mapping===Dm)?(l===void 0&&(l=new yt(new en(1,1,1),new De({name:"BackgroundCubeMaterial",uniforms:Mu(fa.backgroundCube.uniforms),vertexShader:fa.backgroundCube.vertexShader,fragmentShader:fa.backgroundCube.fragmentShader,side:zi,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(x,b,E){this.matrixWorld.copyPosition(E.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l)),l.material.uniforms.envMap.value=y,l.material.uniforms.backgroundBlurriness.value=w.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(WC.makeRotationFromEuler(w.backgroundRotation)).transpose(),y.isCubeTexture&&y.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(NA),l.material.toneMapped=He.getTransfer(y.colorSpace)!==ui,(h!==y||u!==y.version||d!==o.toneMapping)&&(l.material.needsUpdate=!0,h=y,u=y.version,d=o.toneMapping),l.layers.enableAll(),M.unshift(l,l.geometry,l.material,0,0,null)):y&&y.isTexture&&(c===void 0&&(c=new yt(new vs(2,2),new De({name:"BackgroundMaterial",uniforms:Mu(fa.background.uniforms),vertexShader:fa.background.vertexShader,fragmentShader:fa.background.fragmentShader,side:Ba,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c)),c.material.uniforms.t2D.value=y,c.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,c.material.toneMapped=He.getTransfer(y.colorSpace)!==ui,y.matrixAutoUpdate===!0&&y.updateMatrix(),c.material.uniforms.uvTransform.value.copy(y.matrix),(h!==y||u!==y.version||d!==o.toneMapping)&&(c.material.needsUpdate=!0,h=y,u=y.version,d=o.toneMapping),c.layers.enableAll(),M.unshift(c,c.geometry,c.material,0,0,null))}function g(M,w){M.getRGB(Mp,AA(o)),e.buffers.color.setClear(Mp.r,Mp.g,Mp.b,w,s)}function v(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return r},setClearColor:function(M,w=1){r.set(M),a=w,g(r,a)},getClearAlpha:function(){return a},setClearAlpha:function(M){a=M,g(r,a)},render:p,addToRenderList:m,dispose:v}}function $C(o,t){const e=o.getParameter(o.MAX_VERTEX_ATTRIBS),i={},n=d(null);let s=n,r=!1;function a(I,D,O,P,N){let k=!1;const B=u(I,P,O,D);s!==B&&(s=B,l(s.object)),k=f(I,P,O,N),k&&p(I,P,O,N),N!==null&&t.update(N,o.ELEMENT_ARRAY_BUFFER),(k||r)&&(r=!1,y(I,D,O,P),N!==null&&o.bindBuffer(o.ELEMENT_ARRAY_BUFFER,t.get(N).buffer))}function c(){return o.createVertexArray()}function l(I){return o.bindVertexArray(I)}function h(I){return o.deleteVertexArray(I)}function u(I,D,O,P){const N=P.wireframe===!0;let k=i[D.id];k===void 0&&(k={},i[D.id]=k);const B=I.isInstancedMesh===!0?I.id:0;let W=k[B];W===void 0&&(W={},k[B]=W);let Q=W[O.id];Q===void 0&&(Q={},W[O.id]=Q);let Z=Q[N];return Z===void 0&&(Z=d(c()),Q[N]=Z),Z}function d(I){const D=[],O=[],P=[];for(let N=0;N<e;N++)D[N]=0,O[N]=0,P[N]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:D,enabledAttributes:O,attributeDivisors:P,object:I,attributes:{},index:null}}function f(I,D,O,P){const N=s.attributes,k=D.attributes;let B=0;const W=O.getAttributes();for(const Q in W)if(W[Q].location>=0){const nt=N[Q];let ot=k[Q];if(ot===void 0&&(Q==="instanceMatrix"&&I.instanceMatrix&&(ot=I.instanceMatrix),Q==="instanceColor"&&I.instanceColor&&(ot=I.instanceColor)),nt===void 0||nt.attribute!==ot||ot&&nt.data!==ot.data)return!0;B++}return s.attributesNum!==B||s.index!==P}function p(I,D,O,P){const N={},k=D.attributes;let B=0;const W=O.getAttributes();for(const Q in W)if(W[Q].location>=0){let nt=k[Q];nt===void 0&&(Q==="instanceMatrix"&&I.instanceMatrix&&(nt=I.instanceMatrix),Q==="instanceColor"&&I.instanceColor&&(nt=I.instanceColor));const ot={};ot.attribute=nt,nt&&nt.data&&(ot.data=nt.data),N[Q]=ot,B++}s.attributes=N,s.attributesNum=B,s.index=P}function m(){const I=s.newAttributes;for(let D=0,O=I.length;D<O;D++)I[D]=0}function g(I){v(I,0)}function v(I,D){const O=s.newAttributes,P=s.enabledAttributes,N=s.attributeDivisors;O[I]=1,P[I]===0&&(o.enableVertexAttribArray(I),P[I]=1),N[I]!==D&&(o.vertexAttribDivisor(I,D),N[I]=D)}function M(){const I=s.newAttributes,D=s.enabledAttributes;for(let O=0,P=D.length;O<P;O++)D[O]!==I[O]&&(o.disableVertexAttribArray(O),D[O]=0)}function w(I,D,O,P,N,k,B){B===!0?o.vertexAttribIPointer(I,D,O,N,k):o.vertexAttribPointer(I,D,O,P,N,k)}function y(I,D,O,P){m();const N=P.attributes,k=O.getAttributes(),B=D.defaultAttributeValues;for(const W in k){const Q=k[W];if(Q.location>=0){let Z=N[W];if(Z===void 0&&(W==="instanceMatrix"&&I.instanceMatrix&&(Z=I.instanceMatrix),W==="instanceColor"&&I.instanceColor&&(Z=I.instanceColor)),Z!==void 0){const nt=Z.normalized,ot=Z.itemSize,Ut=t.get(Z);if(Ut===void 0)continue;const Zt=Ut.buffer,jt=Ut.type,K=Ut.bytesPerElement,lt=jt===o.INT||jt===o.UNSIGNED_INT||Z.gpuType===oy;if(Z.isInterleavedBufferAttribute){const ct=Z.data,V=ct.stride,Lt=Z.offset;if(ct.isInstancedInterleavedBuffer){for(let Xt=0;Xt<Q.locationSize;Xt++)v(Q.location+Xt,ct.meshPerAttribute);I.isInstancedMesh!==!0&&P._maxInstanceCount===void 0&&(P._maxInstanceCount=ct.meshPerAttribute*ct.count)}else for(let Xt=0;Xt<Q.locationSize;Xt++)g(Q.location+Xt);o.bindBuffer(o.ARRAY_BUFFER,Zt);for(let Xt=0;Xt<Q.locationSize;Xt++)w(Q.location+Xt,ot/Q.locationSize,jt,nt,V*K,(Lt+ot/Q.locationSize*Xt)*K,lt)}else{if(Z.isInstancedBufferAttribute){for(let ct=0;ct<Q.locationSize;ct++)v(Q.location+ct,Z.meshPerAttribute);I.isInstancedMesh!==!0&&P._maxInstanceCount===void 0&&(P._maxInstanceCount=Z.meshPerAttribute*Z.count)}else for(let ct=0;ct<Q.locationSize;ct++)g(Q.location+ct);o.bindBuffer(o.ARRAY_BUFFER,Zt);for(let ct=0;ct<Q.locationSize;ct++)w(Q.location+ct,ot/Q.locationSize,jt,nt,ot*K,ot/Q.locationSize*ct*K,lt)}}else if(B!==void 0){const nt=B[W];if(nt!==void 0)switch(nt.length){case 2:o.vertexAttrib2fv(Q.location,nt);break;case 3:o.vertexAttrib3fv(Q.location,nt);break;case 4:o.vertexAttrib4fv(Q.location,nt);break;default:o.vertexAttrib1fv(Q.location,nt)}}}}M()}function x(){A();for(const I in i){const D=i[I];for(const O in D){const P=D[O];for(const N in P){const k=P[N];for(const B in k)h(k[B].object),delete k[B];delete P[N]}}delete i[I]}}function b(I){if(i[I.id]===void 0)return;const D=i[I.id];for(const O in D){const P=D[O];for(const N in P){const k=P[N];for(const B in k)h(k[B].object),delete k[B];delete P[N]}}delete i[I.id]}function E(I){for(const D in i){const O=i[D];for(const P in O){const N=O[P];if(N[I.id]===void 0)continue;const k=N[I.id];for(const B in k)h(k[B].object),delete k[B];delete N[I.id]}}}function S(I){for(const D in i){const O=i[D],P=I.isInstancedMesh===!0?I.id:0,N=O[P];if(N!==void 0){for(const k in N){const B=N[k];for(const W in B)h(B[W].object),delete B[W];delete N[k]}delete O[P],Object.keys(O).length===0&&delete i[D]}}}function A(){_(),r=!0,s!==n&&(s=n,l(s.object))}function _(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:a,reset:A,resetDefaultState:_,dispose:x,releaseStatesOfGeometry:b,releaseStatesOfObject:S,releaseStatesOfProgram:E,initAttributes:m,enableAttribute:g,disableUnusedAttributes:M}}function YC(o,t,e){let i;function n(c){i=c}function s(c,l){o.drawArrays(i,c,l),e.update(l,i,1)}function r(c,l,h){h!==0&&(o.drawArraysInstanced(i,c,l,h),e.update(l,i,h))}function a(c,l,h){if(h===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,l,0,h);let d=0;for(let f=0;f<h;f++)d+=l[f];e.update(d,i,1)}this.setMode=n,this.render=s,this.renderInstances=r,this.renderMultiDraw=a}function KC(o,t,e,i){let n;function s(){if(n!==void 0)return n;if(t.has("EXT_texture_filter_anisotropic")===!0){const E=t.get("EXT_texture_filter_anisotropic");n=o.getParameter(E.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n}function r(E){return!(E!==tn&&i.convert(E)!==o.getParameter(o.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(E){const S=E===Ye&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(E!==fs&&i.convert(E)!==o.getParameter(o.IMPLEMENTATION_COLOR_READ_TYPE)&&E!==ts&&!S)}function c(E){if(E==="highp"){if(o.getShaderPrecisionFormat(o.VERTEX_SHADER,o.HIGH_FLOAT).precision>0&&o.getShaderPrecisionFormat(o.FRAGMENT_SHADER,o.HIGH_FLOAT).precision>0)return"highp";E="mediump"}return E==="mediump"&&o.getShaderPrecisionFormat(o.VERTEX_SHADER,o.MEDIUM_FLOAT).precision>0&&o.getShaderPrecisionFormat(o.FRAGMENT_SHADER,o.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=e.precision!==void 0?e.precision:"highp";const h=c(l);h!==l&&(Ht("WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);const u=e.logarithmicDepthBuffer===!0,d=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control");e.reversedDepthBuffer===!0&&d===!1&&Ht("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");const f=o.getParameter(o.MAX_TEXTURE_IMAGE_UNITS),p=o.getParameter(o.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=o.getParameter(o.MAX_TEXTURE_SIZE),g=o.getParameter(o.MAX_CUBE_MAP_TEXTURE_SIZE),v=o.getParameter(o.MAX_VERTEX_ATTRIBS),M=o.getParameter(o.MAX_VERTEX_UNIFORM_VECTORS),w=o.getParameter(o.MAX_VARYING_VECTORS),y=o.getParameter(o.MAX_FRAGMENT_UNIFORM_VECTORS),x=o.getParameter(o.MAX_SAMPLES),b=o.getParameter(o.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:r,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:d,maxTextures:f,maxVertexTextures:p,maxTextureSize:m,maxCubemapSize:g,maxAttributes:v,maxVertexUniforms:M,maxVaryings:w,maxFragmentUniforms:y,maxSamples:x,samples:b}}function qC(o){const t=this;let e=null,i=0,n=!1,s=!1;const r=new Hr,a=new de,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const f=u.length!==0||d||i!==0||n;return n=d,i=u.length,f},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(u,d){e=h(u,d,0)},this.setState=function(u,d,f){const p=u.clippingPlanes,m=u.clipIntersection,g=u.clipShadows,v=o.get(u);if(!n||p===null||p.length===0||s&&!g)s?h(null):l();else{const M=s?0:i,w=M*4;let y=v.clippingState||null;c.value=y,y=h(p,d,w,f);for(let x=0;x!==w;++x)y[x]=e[x];v.clippingState=y,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=M}};function l(){c.value!==e&&(c.value=e,c.needsUpdate=i>0),t.numPlanes=i,t.numIntersection=0}function h(u,d,f,p){const m=u!==null?u.length:0;let g=null;if(m!==0){if(g=c.value,p!==!0||g===null){const v=f+m*4,M=d.matrixWorldInverse;a.getNormalMatrix(M),(g===null||g.length<v)&&(g=new Float32Array(v));for(let w=0,y=f;w!==m;++w,y+=4)r.copy(u[w]).applyMatrix4(M,a),r.normal.toArray(g,y),g[y+3]=r.constant}c.value=g,c.needsUpdate=!0}return t.numPlanes=m,t.numIntersection=0,g}}const fc=4,Sx=[.125,.215,.35,.446,.526,.582],Gc=20,ZC=256,Vu=new ur,Ex=new rt;let Gg=null,Vg=0,Wg=0,Xg=!1;const JC=new T;class rM{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(t,e=0,i=.1,n=100,s={}){const{size:r=256,position:a=JC}=s;Gg=this._renderer.getRenderTarget(),Vg=this._renderer.getActiveCubeFace(),Wg=this._renderer.getActiveMipmapLevel(),Xg=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(t,i,n,c,a),e>0&&this._blur(c,0,0,e),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Tx(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=_x(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t<this._lodMeshes.length;t++)this._lodMeshes[t].geometry.dispose()}_cleanup(t){this._renderer.setRenderTarget(Gg,Vg,Wg),this._renderer.xr.enabled=Xg,t.scissorTest=!1,th(t,0,0,t.width,t.height)}_fromTexture(t,e){t.mapping===wl||t.mapping===pu?this._setSize(t.image.length===0?16:t.image[0].width||t.image[0].image.width):this._setSize(t.image.width/4),Gg=this._renderer.getRenderTarget(),Vg=this._renderer.getActiveCubeFace(),Wg=this._renderer.getActiveMipmapLevel(),Xg=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const i=e||this._allocateTargets();return this._textureToCubeUV(t,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const t=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,i={magFilter:Me,minFilter:Me,generateMipmaps:!1,type:Ye,format:tn,colorSpace:G0,depthBuffer:!1},n=Ax(t,e,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==t||this._pingPongRenderTarget.height!==e){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ax(t,e,i);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=jC(s)),this._blurMaterial=tO(s,t,e),this._ggxMaterial=QC(s,t,e)}return n}_compileMaterial(t){const e=new yt(new be,t);this._renderer.compile(e,Vu)}_sceneToCubeUV(t,e,i,n,s){const c=new jn(90,1,e,i),l=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],u=this._renderer,d=u.autoClear,f=u.toneMapping;u.getClearColor(Ex),u.toneMapping=ka,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(n),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new yt(new en,new Is({name:"PMREM.Background",side:zi,depthWrite:!1,depthTest:!1})));const m=this._backgroundBox,g=m.material;let v=!1;const M=t.background;M?M.isColor&&(g.color.copy(M),t.background=null,v=!0):(g.color.copy(Ex),v=!0);for(let w=0;w<6;w++){const y=w%3;y===0?(c.up.set(0,l[w],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x+h[w],s.y,s.z)):y===1?(c.up.set(0,0,l[w]),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y+h[w],s.z)):(c.up.set(0,l[w],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y,s.z+h[w]));const x=this._cubeSize;th(n,y*x,w>2?x:0,x,x),u.setRenderTarget(n),v&&u.render(m,c),u.render(t,c)}u.toneMapping=f,u.autoClear=d,t.background=M}_textureToCubeUV(t,e){const i=this._renderer,n=t.mapping===wl||t.mapping===pu;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=Tx()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=_x());const s=n?this._cubemapMaterial:this._equirectMaterial,r=this._lodMeshes[0];r.material=s;const a=s.uniforms;a.envMap.value=t;const c=this._cubeSize;th(e,0,0,3*c,2*c),i.setRenderTarget(e),i.render(r,Vu)}_applyPMREM(t){const e=this._renderer,i=e.autoClear;e.autoClear=!1;const n=this._lodMeshes.length;for(let s=1;s<n;s++)this._applyGGXFilter(t,s-1,s);e.autoClear=i}_applyGGXFilter(t,e,i){const n=this._renderer,s=this._pingPongRenderTarget,r=this._ggxMaterial,a=this._lodMeshes[i];a.material=r;const c=r.uniforms,l=i/(this._lodMeshes.length-1),h=e/(this._lodMeshes.length-1),u=Math.sqrt(l*l-h*h),d=0+l*1.25,f=u*d,{_lodMax:p}=this,m=this._sizeLods[i],g=3*m*(i>p-fc?i-p+fc:0),v=4*(this._cubeSize-m);c.envMap.value=t.texture,c.roughness.value=f,c.mipInt.value=p-e,th(s,g,v,3*m,2*m),n.setRenderTarget(s),n.render(a,Vu),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=p-i,th(t,g,v,3*m,2*m),n.setRenderTarget(t),n.render(a,Vu)}_blur(t,e,i,n,s){const r=this._pingPongRenderTarget;this._halfBlur(t,r,e,i,n,"latitudinal",s),this._halfBlur(r,t,i,i,n,"longitudinal",s)}_halfBlur(t,e,i,n,s,r,a){const c=this._renderer,l=this._blurMaterial;r!=="latitudinal"&&r!=="longitudinal"&&le("blur direction must be either latitudinal or longitudinal!");const h=3,u=this._lodMeshes[n];u.material=l;const d=l.uniforms,f=this._sizeLods[i]-1,p=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Gc-1),m=s/p,g=isFinite(s)?1+Math.floor(h*m):Gc;g>Gc&&Ht(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Gc}`);const v=[];let M=0;for(let E=0;E<Gc;++E){const S=E/m,A=Math.exp(-S*S/2);v.push(A),E===0?M+=A:E<g&&(M+=2*A)}for(let E=0;E<v.length;E++)v[E]=v[E]/M;d.envMap.value=t.texture,d.samples.value=g,d.weights.value=v,d.latitudinal.value=r==="latitudinal",a&&(d.poleAxis.value=a);const{_lodMax:w}=this;d.dTheta.value=p,d.mipInt.value=w-i;const y=this._sizeLods[n],x=3*y*(n>w-fc?n-w+fc:0),b=4*(this._cubeSize-y);th(e,x,b,3*y,2*y),c.setRenderTarget(e),c.render(u,Vu)}}function jC(o){const t=[],e=[],i=[];let n=o;const s=o-fc+1+Sx.length;for(let r=0;r<s;r++){const a=Math.pow(2,n);t.push(a);let c=1/a;r>o-fc?c=Sx[r-o+fc-1]:r===0&&(c=0),e.push(c);const l=1/(a-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,p=6,m=3,g=2,v=1,M=new Float32Array(m*p*f),w=new Float32Array(g*p*f),y=new Float32Array(v*p*f);for(let b=0;b<f;b++){const E=b%3*2/3-1,S=b>2?0:-1,A=[E,S,0,E+2/3,S,0,E+2/3,S+1,0,E,S,0,E+2/3,S+1,0,E,S+1,0];M.set(A,m*p*b),w.set(d,g*p*b);const _=[b,b,b,b,b,b];y.set(_,v*p*b)}const x=new be;x.setAttribute("position",new we(M,m)),x.setAttribute("uv",new we(w,g)),x.setAttribute("faceIndex",new we(y,v)),i.push(new yt(x,null)),n>fc&&n--}return{lodMeshes:i,sizeLods:t,sigmas:e}}function Ax(o,t,e){const i=new Qe(o,t,e);return i.texture.mapping=Dm,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function th(o,t,e,i,n){o.viewport.set(t,e,i,n),o.scissor.set(t,e,i,n)}function QC(o,t,e){return new De({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:ZC,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${o}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Nm(),fragmentShader:`
|
|
4458
4458
|
|
|
4459
4459
|
precision highp float;
|
|
4460
4460
|
precision highp int;
|
|
@@ -4867,7 +4867,7 @@ void main() {
|
|
|
4867
4867
|
squared_mean = squared_mean / samples;
|
|
4868
4868
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
4869
4869
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
4870
|
-
}`,GP=[new T(1,0,0),new T(-1,0,0),new T(0,1,0),new T(0,-1,0),new T(0,0,1),new T(0,0,-1)],VP=[new T(0,-1,0),new T(0,-1,0),new T(0,0,1),new T(0,0,-1),new T(0,-1,0),new T(0,-1,0)],Wx=new Gt,Wu=new T,Yg=new T;function WP(o,t,e){let i=new Cm;const n=new tt,s=new tt,r=new Ie,a=new RI,c=new II,l={},h=e.maxTextureSize,u={[Ba]:zi,[zi]:Ba,[Tn]:Tn},d=new De({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new tt},radius:{value:4}},vertexShader:BP,fragmentShader:HP}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new be;p.setAttribute("position",new ye(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new yt(p,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=dd;let v=this.type;this.render=function(b,E,S){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||b.length===0)return;this.type===M4&&(Ht("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=dd);const A=o.getRenderTarget(),_=o.getActiveCubeFace(),I=o.getActiveMipmapLevel(),D=o.state;D.setBlending(Ys),D.buffers.depth.getReversed()===!0?D.buffers.color.setClear(0,0,0,0):D.buffers.color.setClear(1,1,1,1),D.buffers.depth.setTest(!0),D.setScissorTest(!1);const O=v!==this.type;O&&E.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(N=>N.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,N=b.length;P<N;P++){const k=b[P],B=k.shadow;if(B===void 0){Ht("WebGLShadowMap:",k,"has no shadow.");continue}if(B.autoUpdate===!1&&B.needsUpdate===!1)continue;n.copy(B.mapSize);const W=B.getFrameExtents();n.multiply(W),s.copy(B.mapSize),(n.x>h||n.y>h)&&(n.x>h&&(s.x=Math.floor(h/W.x),n.x=s.x*W.x,B.mapSize.x=s.x),n.y>h&&(s.y=Math.floor(h/W.y),n.y=s.y*W.y,B.mapSize.y=s.y));const Q=o.state.buffers.depth.getReversed();if(B.camera._reversedDepth=Q,B.map===null||O===!0){if(B.map!==null&&(B.map.depthTexture!==null&&(B.map.depthTexture.dispose(),B.map.depthTexture=null),B.map.dispose()),this.type===cd){if(k.isPointLight){Ht("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}B.map=new Qe(n.x,n.y,{format:xl,type:Ye,minFilter:Me,magFilter:Me,generateMipmaps:!1}),B.map.texture.name=k.name+".shadowMap",B.map.depthTexture=new Sc(n.x,n.y,ts),B.map.depthTexture.name=k.name+".shadowMapDepth",B.map.depthTexture.format=So,B.map.depthTexture.compareFunction=null,B.map.depthTexture.minFilter=si,B.map.depthTexture.magFilter=si}else k.isPointLight?(B.map=new pf(n.x),B.map.depthTexture=new WR(n.x,_r)):(B.map=new Qe(n.x,n.y),B.map.depthTexture=new Sc(n.x,n.y,_r)),B.map.depthTexture.name=k.name+".shadowMap",B.map.depthTexture.format=So,this.type===dd?(B.map.depthTexture.compareFunction=Q?my:py,B.map.depthTexture.minFilter=Me,B.map.depthTexture.magFilter=Me):(B.map.depthTexture.compareFunction=null,B.map.depthTexture.minFilter=si,B.map.depthTexture.magFilter=si);B.camera.updateProjectionMatrix()}const Z=B.map.isWebGLCubeRenderTarget?6:1;for(let nt=0;nt<Z;nt++){if(B.map.isWebGLCubeRenderTarget)o.setRenderTarget(B.map,nt),o.clear();else{nt===0&&(o.setRenderTarget(B.map),o.clear());const ot=B.getViewport(nt);r.set(s.x*ot.x,s.y*ot.y,s.x*ot.z,s.y*ot.w),D.viewport(r)}if(k.isPointLight){const ot=B.camera,Ut=B.matrix,Zt=k.distance||ot.far;Zt!==ot.far&&(ot.far=Zt,ot.updateProjectionMatrix()),Wu.setFromMatrixPosition(k.matrixWorld),ot.position.copy(Wu),Yg.copy(ot.position),Yg.add(GP[nt]),ot.up.copy(VP[nt]),ot.lookAt(Yg),ot.updateMatrixWorld(),Ut.makeTranslation(-Wu.x,-Wu.y,-Wu.z),Wx.multiplyMatrices(ot.projectionMatrix,ot.matrixWorldInverse),B._frustum.setFromProjectionMatrix(Wx,ot.coordinateSystem,ot.reversedDepth)}else B.updateMatrices(k);i=B.getFrustum(),y(E,S,B.camera,k,this.type)}B.isPointLightShadow!==!0&&this.type===cd&&M(B,S),B.needsUpdate=!1}v=this.type,g.needsUpdate=!1,o.setRenderTarget(A,_,I)};function M(b,E){const S=t.update(m);d.defines.VSM_SAMPLES!==b.blurSamples&&(d.defines.VSM_SAMPLES=b.blurSamples,f.defines.VSM_SAMPLES=b.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),b.mapPass===null&&(b.mapPass=new Qe(n.x,n.y,{format:xl,type:Ye})),d.uniforms.shadow_pass.value=b.map.depthTexture,d.uniforms.resolution.value=b.mapSize,d.uniforms.radius.value=b.radius,o.setRenderTarget(b.mapPass),o.clear(),o.renderBufferDirect(E,null,S,d,m,null),f.uniforms.shadow_pass.value=b.mapPass.texture,f.uniforms.resolution.value=b.mapSize,f.uniforms.radius.value=b.radius,o.setRenderTarget(b.map),o.clear(),o.renderBufferDirect(E,null,S,f,m,null)}function w(b,E,S,A){let _=null;const I=S.isPointLight===!0?b.customDistanceMaterial:b.customDepthMaterial;if(I!==void 0)_=I;else if(_=S.isPointLight===!0?c:a,o.localClippingEnabled&&E.clipShadows===!0&&Array.isArray(E.clippingPlanes)&&E.clippingPlanes.length!==0||E.displacementMap&&E.displacementScale!==0||E.alphaMap&&E.alphaTest>0||E.map&&E.alphaTest>0||E.alphaToCoverage===!0){const D=_.uuid,O=E.uuid;let P=l[D];P===void 0&&(P={},l[D]=P);let N=P[O];N===void 0&&(N=_.clone(),P[O]=N,E.addEventListener("dispose",x)),_=N}if(_.visible=E.visible,_.wireframe=E.wireframe,A===cd?_.side=E.shadowSide!==null?E.shadowSide:E.side:_.side=E.shadowSide!==null?E.shadowSide:u[E.side],_.alphaMap=E.alphaMap,_.alphaTest=E.alphaToCoverage===!0?.5:E.alphaTest,_.map=E.map,_.clipShadows=E.clipShadows,_.clippingPlanes=E.clippingPlanes,_.clipIntersection=E.clipIntersection,_.displacementMap=E.displacementMap,_.displacementScale=E.displacementScale,_.displacementBias=E.displacementBias,_.wireframeLinewidth=E.wireframeLinewidth,_.linewidth=E.linewidth,S.isPointLight===!0&&_.isMeshDistanceMaterial===!0){const D=o.properties.get(_);D.light=S}return _}function y(b,E,S,A,_){if(b.visible===!1)return;if(b.layers.test(E.layers)&&(b.isMesh||b.isLine||b.isPoints)&&(b.castShadow||b.receiveShadow&&_===cd)&&(!b.frustumCulled||i.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,b.matrixWorld);const O=t.update(b),P=b.material;if(Array.isArray(P)){const N=O.groups;for(let k=0,B=N.length;k<B;k++){const W=N[k],Q=P[W.materialIndex];if(Q&&Q.visible){const Z=w(b,Q,A,_);b.onBeforeShadow(o,b,E,S,O,Z,W),o.renderBufferDirect(S,null,O,Z,b,W),b.onAfterShadow(o,b,E,S,O,Z,W)}}}else if(P.visible){const N=w(b,P,A,_);b.onBeforeShadow(o,b,E,S,O,N,null),o.renderBufferDirect(S,null,O,N,b,null),b.onAfterShadow(o,b,E,S,O,N,null)}}const D=b.children;for(let O=0,P=D.length;O<P;O++)y(D[O],E,S,A,_)}function x(b){b.target.removeEventListener("dispose",x);for(const S in l){const A=l[S],_=b.target.uuid;_ in A&&(A[_].dispose(),delete A[_])}}}function XP(o,t){function e(){let U=!1;const ft=new Ie;let et=null;const Mt=new Ie(0,0,0,0);return{setMask:function(At){et!==At&&!U&&(o.colorMask(At,At,At,At),et=At)},setLocked:function(At){U=At},setClear:function(At,st,Wt,Ft,Ki){Ki===!0&&(At*=Ft,st*=Ft,Wt*=Ft),ft.set(At,st,Wt,Ft),Mt.equals(ft)===!1&&(o.clearColor(At,st,Wt,Ft),Mt.copy(ft))},reset:function(){U=!1,et=null,Mt.set(-1,0,0,0)}}}function i(){let U=!1,ft=!1,et=null,Mt=null,At=null;return{setReversed:function(st){if(ft!==st){const Wt=t.get("EXT_clip_control");st?Wt.clipControlEXT(Wt.LOWER_LEFT_EXT,Wt.ZERO_TO_ONE_EXT):Wt.clipControlEXT(Wt.LOWER_LEFT_EXT,Wt.NEGATIVE_ONE_TO_ONE_EXT),ft=st;const Ft=At;At=null,this.setClear(Ft)}},getReversed:function(){return ft},setTest:function(st){st?ct(o.DEPTH_TEST):V(o.DEPTH_TEST)},setMask:function(st){et!==st&&!U&&(o.depthMask(st),et=st)},setFunc:function(st){if(ft&&(st=Q4[st]),Mt!==st){switch(st){case fv:o.depthFunc(o.NEVER);break;case pv:o.depthFunc(o.ALWAYS);break;case mv:o.depthFunc(o.LESS);break;case fu:o.depthFunc(o.LEQUAL);break;case gv:o.depthFunc(o.EQUAL);break;case vv:o.depthFunc(o.GEQUAL);break;case Mv:o.depthFunc(o.GREATER);break;case yv:o.depthFunc(o.NOTEQUAL);break;default:o.depthFunc(o.LEQUAL)}Mt=st}},setLocked:function(st){U=st},setClear:function(st){At!==st&&(At=st,ft&&(st=1-st),o.clearDepth(st))},reset:function(){U=!1,et=null,Mt=null,At=null,ft=!1}}}function n(){let U=!1,ft=null,et=null,Mt=null,At=null,st=null,Wt=null,Ft=null,Ki=null;return{setTest:function(Ti){U||(Ti?ct(o.STENCIL_TEST):V(o.STENCIL_TEST))},setMask:function(Ti){ft!==Ti&&!U&&(o.stencilMask(Ti),ft=Ti)},setFunc:function(Ti,Zr,Jr){(et!==Ti||Mt!==Zr||At!==Jr)&&(o.stencilFunc(Ti,Zr,Jr),et=Ti,Mt=Zr,At=Jr)},setOp:function(Ti,Zr,Jr){(st!==Ti||Wt!==Zr||Ft!==Jr)&&(o.stencilOp(Ti,Zr,Jr),st=Ti,Wt=Zr,Ft=Jr)},setLocked:function(Ti){U=Ti},setClear:function(Ti){Ki!==Ti&&(o.clearStencil(Ti),Ki=Ti)},reset:function(){U=!1,ft=null,et=null,Mt=null,At=null,st=null,Wt=null,Ft=null,Ki=null}}}const s=new e,r=new i,a=new n,c=new WeakMap,l=new WeakMap;let h={},u={},d={},f=new WeakMap,p=[],m=null,g=!1,v=null,M=null,w=null,y=null,x=null,b=null,E=null,S=new rt(0,0,0),A=0,_=!1,I=null,D=null,O=null,P=null,N=null;const k=o.getParameter(o.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let B=!1,W=0;const Q=o.getParameter(o.VERSION);Q.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(Q)[1]),B=W>=1):Q.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),B=W>=2);let Z=null,nt={};const ot=o.getParameter(o.SCISSOR_BOX),Ut=o.getParameter(o.VIEWPORT),Zt=new Ie().fromArray(ot),jt=new Ie().fromArray(Ut);function K(U,ft,et,Mt){const At=new Uint8Array(4),st=o.createTexture();o.bindTexture(U,st),o.texParameteri(U,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(U,o.TEXTURE_MAG_FILTER,o.NEAREST);for(let Wt=0;Wt<et;Wt++)U===o.TEXTURE_3D||U===o.TEXTURE_2D_ARRAY?o.texImage3D(ft,0,o.RGBA,1,1,Mt,0,o.RGBA,o.UNSIGNED_BYTE,At):o.texImage2D(ft+Wt,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,At);return st}const lt={};lt[o.TEXTURE_2D]=K(o.TEXTURE_2D,o.TEXTURE_2D,1),lt[o.TEXTURE_CUBE_MAP]=K(o.TEXTURE_CUBE_MAP,o.TEXTURE_CUBE_MAP_POSITIVE_X,6),lt[o.TEXTURE_2D_ARRAY]=K(o.TEXTURE_2D_ARRAY,o.TEXTURE_2D_ARRAY,1,1),lt[o.TEXTURE_3D]=K(o.TEXTURE_3D,o.TEXTURE_3D,1,1),s.setClear(0,0,0,1),r.setClear(1),a.setClear(0),ct(o.DEPTH_TEST),r.setFunc(fu),ri(!1),ai(Mw),ct(o.CULL_FACE),ne(Ys);function ct(U){h[U]!==!0&&(o.enable(U),h[U]=!0)}function V(U){h[U]!==!1&&(o.disable(U),h[U]=!1)}function Lt(U,ft){return d[U]!==ft?(o.bindFramebuffer(U,ft),d[U]=ft,U===o.DRAW_FRAMEBUFFER&&(d[o.FRAMEBUFFER]=ft),U===o.FRAMEBUFFER&&(d[o.DRAW_FRAMEBUFFER]=ft),!0):!1}function Xt(U,ft){let et=p,Mt=!1;if(U){et=f.get(ft),et===void 0&&(et=[],f.set(ft,et));const At=U.textures;if(et.length!==At.length||et[0]!==o.COLOR_ATTACHMENT0){for(let st=0,Wt=At.length;st<Wt;st++)et[st]=o.COLOR_ATTACHMENT0+st;et.length=At.length,Mt=!0}}else et[0]!==o.BACK&&(et[0]=o.BACK,Mt=!0);Mt&&o.drawBuffers(et)}function kt(U){return m!==U?(o.useProgram(U),m=U,!0):!1}const Rt={[ao]:o.FUNC_ADD,[y4]:o.FUNC_SUBTRACT,[w4]:o.FUNC_REVERSE_SUBTRACT};Rt[x4]=o.MIN,Rt[b4]=o.MAX;const te={[Ta]:o.ZERO,[yl]:o.ONE,[S4]:o.SRC_COLOR,[k0]:o.SRC_ALPHA,[I4]:o.SRC_ALPHA_SATURATE,[T4]:o.DST_COLOR,[A4]:o.DST_ALPHA,[E4]:o.ONE_MINUS_SRC_COLOR,[af]:o.ONE_MINUS_SRC_ALPHA,[R4]:o.ONE_MINUS_DST_COLOR,[_4]:o.ONE_MINUS_DST_ALPHA,[D4]:o.CONSTANT_COLOR,[C4]:o.ONE_MINUS_CONSTANT_COLOR,[O4]:o.CONSTANT_ALPHA,[P4]:o.ONE_MINUS_CONSTANT_ALPHA};function ne(U,ft,et,Mt,At,st,Wt,Ft,Ki,Ti){if(U===Ys){g===!0&&(V(o.BLEND),g=!1);return}if(g===!1&&(ct(o.BLEND),g=!0),U!==Ml){if(U!==v||Ti!==_){if((M!==ao||x!==ao)&&(o.blendEquation(o.FUNC_ADD),M=ao,x=ao),Ti)switch(U){case Mc:o.blendFuncSeparate(o.ONE,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA);break;case Cn:o.blendFunc(o.ONE,o.ONE);break;case yw:o.blendFuncSeparate(o.ZERO,o.ONE_MINUS_SRC_COLOR,o.ZERO,o.ONE);break;case ww:o.blendFuncSeparate(o.DST_COLOR,o.ONE_MINUS_SRC_ALPHA,o.ZERO,o.ONE);break;default:le("WebGLState: Invalid blending: ",U);break}else switch(U){case Mc:o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA);break;case Cn:o.blendFuncSeparate(o.SRC_ALPHA,o.ONE,o.ONE,o.ONE);break;case yw:le("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case ww:le("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:le("WebGLState: Invalid blending: ",U);break}w=null,y=null,b=null,E=null,S.set(0,0,0),A=0,v=U,_=Ti}return}At=At||ft,st=st||et,Wt=Wt||Mt,(ft!==M||At!==x)&&(o.blendEquationSeparate(Rt[ft],Rt[At]),M=ft,x=At),(et!==w||Mt!==y||st!==b||Wt!==E)&&(o.blendFuncSeparate(te[et],te[Mt],te[st],te[Wt]),w=et,y=Mt,b=st,E=Wt),(Ft.equals(S)===!1||Ki!==A)&&(o.blendColor(Ft.r,Ft.g,Ft.b,Ki),S.copy(Ft),A=Ki),v=U,_=!1}function se(U,ft){U.side===Tn?V(o.CULL_FACE):ct(o.CULL_FACE);let et=U.side===zi;ft&&(et=!et),ri(et),U.blending===Mc&&U.transparent===!1?ne(Ys):ne(U.blending,U.blendEquation,U.blendSrc,U.blendDst,U.blendEquationAlpha,U.blendSrcAlpha,U.blendDstAlpha,U.blendColor,U.blendAlpha,U.premultipliedAlpha),r.setFunc(U.depthFunc),r.setTest(U.depthTest),r.setMask(U.depthWrite),s.setMask(U.colorWrite);const Mt=U.stencilWrite;a.setTest(Mt),Mt&&(a.setMask(U.stencilWriteMask),a.setFunc(U.stencilFunc,U.stencilRef,U.stencilFuncMask),a.setOp(U.stencilFail,U.stencilZFail,U.stencilZPass)),Gi(U.polygonOffset,U.polygonOffsetFactor,U.polygonOffsetUnits),U.alphaToCoverage===!0?ct(o.SAMPLE_ALPHA_TO_COVERAGE):V(o.SAMPLE_ALPHA_TO_COVERAGE)}function ri(U){I!==U&&(U?o.frontFace(o.CW):o.frontFace(o.CCW),I=U)}function ai(U){U!==g4?(ct(o.CULL_FACE),U!==D&&(U===Mw?o.cullFace(o.BACK):U===v4?o.cullFace(o.FRONT):o.cullFace(o.FRONT_AND_BACK))):V(o.CULL_FACE),D=U}function $i(U){U!==O&&(B&&o.lineWidth(U),O=U)}function Gi(U,ft,et){U?(ct(o.POLYGON_OFFSET_FILL),(P!==ft||N!==et)&&(P=ft,N=et,r.getReversed()&&(ft=-ft),o.polygonOffset(ft,et))):V(o.POLYGON_OFFSET_FILL)}function Yi(U){U?ct(o.SCISSOR_TEST):V(o.SCISSOR_TEST)}function un(U){U===void 0&&(U=o.TEXTURE0+k-1),Z!==U&&(o.activeTexture(U),Z=U)}function z(U,ft,et){et===void 0&&(Z===null?et=o.TEXTURE0+k-1:et=Z);let Mt=nt[et];Mt===void 0&&(Mt={type:void 0,texture:void 0},nt[et]=Mt),(Mt.type!==U||Mt.texture!==ft)&&(Z!==et&&(o.activeTexture(et),Z=et),o.bindTexture(U,ft||lt[U]),Mt.type=U,Mt.texture=ft)}function Os(){const U=nt[Z];U!==void 0&&U.type!==void 0&&(o.bindTexture(U.type,null),U.type=void 0,U.texture=void 0)}function oi(){try{o.compressedTexImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function L(){try{o.compressedTexImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function R(){try{o.texSubImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function G(){try{o.texSubImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function Y(){try{o.compressedTexSubImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function J(){try{o.compressedTexSubImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function ut(){try{o.texStorage2D(...arguments)}catch(U){le("WebGLState:",U)}}function pt(){try{o.texStorage3D(...arguments)}catch(U){le("WebGLState:",U)}}function j(){try{o.texImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function it(){try{o.texImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function gt(U){return u[U]!==void 0?u[U]:o.getParameter(U)}function $t(U,ft){u[U]!==ft&&(o.pixelStorei(U,ft),u[U]=ft)}function xt(U){Zt.equals(U)===!1&&(o.scissor(U.x,U.y,U.z,U.w),Zt.copy(U))}function vt(U){jt.equals(U)===!1&&(o.viewport(U.x,U.y,U.z,U.w),jt.copy(U))}function Qt(U,ft){let et=l.get(ft);et===void 0&&(et=new WeakMap,l.set(ft,et));let Mt=et.get(U);Mt===void 0&&(Mt=o.getUniformBlockIndex(ft,U.name),et.set(U,Mt))}function ae(U,ft){const Mt=l.get(ft).get(U);c.get(ft)!==Mt&&(o.uniformBlockBinding(ft,Mt,U.__bindingPointIndex),c.set(ft,Mt))}function Ae(){o.disable(o.BLEND),o.disable(o.CULL_FACE),o.disable(o.DEPTH_TEST),o.disable(o.POLYGON_OFFSET_FILL),o.disable(o.SCISSOR_TEST),o.disable(o.STENCIL_TEST),o.disable(o.SAMPLE_ALPHA_TO_COVERAGE),o.blendEquation(o.FUNC_ADD),o.blendFunc(o.ONE,o.ZERO),o.blendFuncSeparate(o.ONE,o.ZERO,o.ONE,o.ZERO),o.blendColor(0,0,0,0),o.colorMask(!0,!0,!0,!0),o.clearColor(0,0,0,0),o.depthMask(!0),o.depthFunc(o.LESS),r.setReversed(!1),o.clearDepth(1),o.stencilMask(4294967295),o.stencilFunc(o.ALWAYS,0,4294967295),o.stencilOp(o.KEEP,o.KEEP,o.KEEP),o.clearStencil(0),o.cullFace(o.BACK),o.frontFace(o.CCW),o.polygonOffset(0,0),o.activeTexture(o.TEXTURE0),o.bindFramebuffer(o.FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,null),o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.useProgram(null),o.lineWidth(1),o.scissor(0,0,o.canvas.width,o.canvas.height),o.viewport(0,0,o.canvas.width,o.canvas.height),o.pixelStorei(o.PACK_ALIGNMENT,4),o.pixelStorei(o.UNPACK_ALIGNMENT,4),o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!1),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),o.pixelStorei(o.UNPACK_COLORSPACE_CONVERSION_WEBGL,o.BROWSER_DEFAULT_WEBGL),o.pixelStorei(o.PACK_ROW_LENGTH,0),o.pixelStorei(o.PACK_SKIP_PIXELS,0),o.pixelStorei(o.PACK_SKIP_ROWS,0),o.pixelStorei(o.UNPACK_ROW_LENGTH,0),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,0),o.pixelStorei(o.UNPACK_SKIP_PIXELS,0),o.pixelStorei(o.UNPACK_SKIP_ROWS,0),o.pixelStorei(o.UNPACK_SKIP_IMAGES,0),h={},u={},Z=null,nt={},d={},f=new WeakMap,p=[],m=null,g=!1,v=null,M=null,w=null,y=null,x=null,b=null,E=null,S=new rt(0,0,0),A=0,_=!1,I=null,D=null,O=null,P=null,N=null,Zt.set(0,0,o.canvas.width,o.canvas.height),jt.set(0,0,o.canvas.width,o.canvas.height),s.reset(),r.reset(),a.reset()}return{buffers:{color:s,depth:r,stencil:a},enable:ct,disable:V,bindFramebuffer:Lt,drawBuffers:Xt,useProgram:kt,setBlending:ne,setMaterial:se,setFlipSided:ri,setCullFace:ai,setLineWidth:$i,setPolygonOffset:Gi,setScissorTest:Yi,activeTexture:un,bindTexture:z,unbindTexture:Os,compressedTexImage2D:oi,compressedTexImage3D:L,texImage2D:j,texImage3D:it,pixelStorei:$t,getParameter:gt,updateUBOMapping:Qt,uniformBlockBinding:ae,texStorage2D:ut,texStorage3D:pt,texSubImage2D:R,texSubImage3D:G,compressedTexSubImage2D:Y,compressedTexSubImage3D:J,scissor:xt,viewport:vt,reset:Ae}}function $P(o,t,e,i,n,s,r){const a=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new tt,h=new WeakMap,u=new Set;let d;const f=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(L,R){return p?new OffscreenCanvas(L,R):hf("canvas")}function g(L,R,G){let Y=1;const J=oi(L);if((J.width>G||J.height>G)&&(Y=G/Math.max(J.width,J.height)),Y<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){const ut=Math.floor(Y*J.width),pt=Math.floor(Y*J.height);d===void 0&&(d=m(ut,pt));const j=R?m(ut,pt):d;return j.width=ut,j.height=pt,j.getContext("2d").drawImage(L,0,0,ut,pt),Ht("WebGLRenderer: Texture has been resized from ("+J.width+"x"+J.height+") to ("+ut+"x"+pt+")."),j}else return"data"in L&&Ht("WebGLRenderer: Image in DataTexture is too big ("+J.width+"x"+J.height+")."),L;return L}function v(L){return L.generateMipmaps}function M(L){o.generateMipmap(L)}function w(L){return L.isWebGLCubeRenderTarget?o.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?o.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?o.TEXTURE_2D_ARRAY:o.TEXTURE_2D}function y(L,R,G,Y,J,ut=!1){if(L!==null){if(o[L]!==void 0)return o[L];Ht("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let pt;Y&&(pt=t.get("EXT_texture_norm16"),pt||Ht("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let j=R;if(R===o.RED&&(G===o.FLOAT&&(j=o.R32F),G===o.HALF_FLOAT&&(j=o.R16F),G===o.UNSIGNED_BYTE&&(j=o.R8),G===o.UNSIGNED_SHORT&&pt&&(j=pt.R16_EXT),G===o.SHORT&&pt&&(j=pt.R16_SNORM_EXT)),R===o.RED_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.R8UI),G===o.UNSIGNED_SHORT&&(j=o.R16UI),G===o.UNSIGNED_INT&&(j=o.R32UI),G===o.BYTE&&(j=o.R8I),G===o.SHORT&&(j=o.R16I),G===o.INT&&(j=o.R32I)),R===o.RG&&(G===o.FLOAT&&(j=o.RG32F),G===o.HALF_FLOAT&&(j=o.RG16F),G===o.UNSIGNED_BYTE&&(j=o.RG8),G===o.UNSIGNED_SHORT&&pt&&(j=pt.RG16_EXT),G===o.SHORT&&pt&&(j=pt.RG16_SNORM_EXT)),R===o.RG_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.RG8UI),G===o.UNSIGNED_SHORT&&(j=o.RG16UI),G===o.UNSIGNED_INT&&(j=o.RG32UI),G===o.BYTE&&(j=o.RG8I),G===o.SHORT&&(j=o.RG16I),G===o.INT&&(j=o.RG32I)),R===o.RGB_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.RGB8UI),G===o.UNSIGNED_SHORT&&(j=o.RGB16UI),G===o.UNSIGNED_INT&&(j=o.RGB32UI),G===o.BYTE&&(j=o.RGB8I),G===o.SHORT&&(j=o.RGB16I),G===o.INT&&(j=o.RGB32I)),R===o.RGBA_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.RGBA8UI),G===o.UNSIGNED_SHORT&&(j=o.RGBA16UI),G===o.UNSIGNED_INT&&(j=o.RGBA32UI),G===o.BYTE&&(j=o.RGBA8I),G===o.SHORT&&(j=o.RGBA16I),G===o.INT&&(j=o.RGBA32I)),R===o.RGB&&(G===o.UNSIGNED_SHORT&&pt&&(j=pt.RGB16_EXT),G===o.SHORT&&pt&&(j=pt.RGB16_SNORM_EXT),G===o.UNSIGNED_INT_5_9_9_9_REV&&(j=o.RGB9_E5),G===o.UNSIGNED_INT_10F_11F_11F_REV&&(j=o.R11F_G11F_B10F)),R===o.RGBA){const it=ut?V0:He.getTransfer(J);G===o.FLOAT&&(j=o.RGBA32F),G===o.HALF_FLOAT&&(j=o.RGBA16F),G===o.UNSIGNED_BYTE&&(j=it===ui?o.SRGB8_ALPHA8:o.RGBA8),G===o.UNSIGNED_SHORT&&pt&&(j=pt.RGBA16_EXT),G===o.SHORT&&pt&&(j=pt.RGBA16_SNORM_EXT),G===o.UNSIGNED_SHORT_4_4_4_4&&(j=o.RGBA4),G===o.UNSIGNED_SHORT_5_5_5_1&&(j=o.RGB5_A1)}return(j===o.R16F||j===o.R32F||j===o.RG16F||j===o.RG32F||j===o.RGBA16F||j===o.RGBA32F)&&t.get("EXT_color_buffer_float"),j}function x(L,R){let G;return L?R===null||R===_r||R===cf?G=o.DEPTH24_STENCIL8:R===ts?G=o.DEPTH32F_STENCIL8:R===of&&(G=o.DEPTH24_STENCIL8,Ht("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):R===null||R===_r||R===cf?G=o.DEPTH_COMPONENT24:R===ts?G=o.DEPTH_COMPONENT32F:R===of&&(G=o.DEPTH_COMPONENT16),G}function b(L,R){return v(L)===!0||L.isFramebufferTexture&&L.minFilter!==si&&L.minFilter!==Me?Math.log2(Math.max(R.width,R.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?R.mipmaps.length:1}function E(L){const R=L.target;R.removeEventListener("dispose",E),A(R),R.isVideoTexture&&h.delete(R),R.isHTMLTexture&&u.delete(R)}function S(L){const R=L.target;R.removeEventListener("dispose",S),I(R)}function A(L){const R=i.get(L);if(R.__webglInit===void 0)return;const G=L.source,Y=f.get(G);if(Y){const J=Y[R.__cacheKey];J.usedTimes--,J.usedTimes===0&&_(L),Object.keys(Y).length===0&&f.delete(G)}i.remove(L)}function _(L){const R=i.get(L);o.deleteTexture(R.__webglTexture);const G=L.source,Y=f.get(G);delete Y[R.__cacheKey],r.memory.textures--}function I(L){const R=i.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),i.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let Y=0;Y<6;Y++){if(Array.isArray(R.__webglFramebuffer[Y]))for(let J=0;J<R.__webglFramebuffer[Y].length;J++)o.deleteFramebuffer(R.__webglFramebuffer[Y][J]);else o.deleteFramebuffer(R.__webglFramebuffer[Y]);R.__webglDepthbuffer&&o.deleteRenderbuffer(R.__webglDepthbuffer[Y])}else{if(Array.isArray(R.__webglFramebuffer))for(let Y=0;Y<R.__webglFramebuffer.length;Y++)o.deleteFramebuffer(R.__webglFramebuffer[Y]);else o.deleteFramebuffer(R.__webglFramebuffer);if(R.__webglDepthbuffer&&o.deleteRenderbuffer(R.__webglDepthbuffer),R.__webglMultisampledFramebuffer&&o.deleteFramebuffer(R.__webglMultisampledFramebuffer),R.__webglColorRenderbuffer)for(let Y=0;Y<R.__webglColorRenderbuffer.length;Y++)R.__webglColorRenderbuffer[Y]&&o.deleteRenderbuffer(R.__webglColorRenderbuffer[Y]);R.__webglDepthRenderbuffer&&o.deleteRenderbuffer(R.__webglDepthRenderbuffer)}const G=L.textures;for(let Y=0,J=G.length;Y<J;Y++){const ut=i.get(G[Y]);ut.__webglTexture&&(o.deleteTexture(ut.__webglTexture),r.memory.textures--),i.remove(G[Y])}i.remove(L)}let D=0;function O(){D=0}function P(){return D}function N(L){D=L}function k(){const L=D;return L>=n.maxTextures&&Ht("WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+n.maxTextures),D+=1,L}function B(L){const R=[];return R.push(L.wrapS),R.push(L.wrapT),R.push(L.wrapR||0),R.push(L.magFilter),R.push(L.minFilter),R.push(L.anisotropy),R.push(L.internalFormat),R.push(L.format),R.push(L.type),R.push(L.generateMipmaps),R.push(L.premultiplyAlpha),R.push(L.flipY),R.push(L.unpackAlignment),R.push(L.colorSpace),R.join()}function W(L,R){const G=i.get(L);if(L.isVideoTexture&&z(L),L.isRenderTargetTexture===!1&&L.isExternalTexture!==!0&&L.version>0&&G.__version!==L.version){const Y=L.image;if(Y===null)Ht("WebGLRenderer: Texture marked for update but no image data found.");else if(Y.complete===!1)Ht("WebGLRenderer: Texture marked for update but image is incomplete");else{V(G,L,R);return}}else L.isExternalTexture&&(G.__webglTexture=L.sourceTexture?L.sourceTexture:null);e.bindTexture(o.TEXTURE_2D,G.__webglTexture,o.TEXTURE0+R)}function Q(L,R){const G=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&G.__version!==L.version){V(G,L,R);return}else L.isExternalTexture&&(G.__webglTexture=L.sourceTexture?L.sourceTexture:null);e.bindTexture(o.TEXTURE_2D_ARRAY,G.__webglTexture,o.TEXTURE0+R)}function Z(L,R){const G=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&G.__version!==L.version){V(G,L,R);return}e.bindTexture(o.TEXTURE_3D,G.__webglTexture,o.TEXTURE0+R)}function nt(L,R){const G=i.get(L);if(L.isCubeDepthTexture!==!0&&L.version>0&&G.__version!==L.version){Lt(G,L,R);return}e.bindTexture(o.TEXTURE_CUBE_MAP,G.__webglTexture,o.TEXTURE0+R)}const ot={[bc]:o.REPEAT,[Qi]:o.CLAMP_TO_EDGE,[wv]:o.MIRRORED_REPEAT},Ut={[si]:o.NEAREST,[F4]:o.NEAREST_MIPMAP_NEAREST,[zf]:o.NEAREST_MIPMAP_LINEAR,[Me]:o.LINEAR,[cg]:o.LINEAR_MIPMAP_NEAREST,[cr]:o.LINEAR_MIPMAP_LINEAR},Zt={[V4]:o.NEVER,[K4]:o.ALWAYS,[W4]:o.LESS,[py]:o.LEQUAL,[X4]:o.EQUAL,[my]:o.GEQUAL,[$4]:o.GREATER,[Y4]:o.NOTEQUAL};function jt(L,R){if(R.type===ts&&t.has("OES_texture_float_linear")===!1&&(R.magFilter===Me||R.magFilter===cg||R.magFilter===zf||R.magFilter===cr||R.minFilter===Me||R.minFilter===cg||R.minFilter===zf||R.minFilter===cr)&&Ht("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),o.texParameteri(L,o.TEXTURE_WRAP_S,ot[R.wrapS]),o.texParameteri(L,o.TEXTURE_WRAP_T,ot[R.wrapT]),(L===o.TEXTURE_3D||L===o.TEXTURE_2D_ARRAY)&&o.texParameteri(L,o.TEXTURE_WRAP_R,ot[R.wrapR]),o.texParameteri(L,o.TEXTURE_MAG_FILTER,Ut[R.magFilter]),o.texParameteri(L,o.TEXTURE_MIN_FILTER,Ut[R.minFilter]),R.compareFunction&&(o.texParameteri(L,o.TEXTURE_COMPARE_MODE,o.COMPARE_REF_TO_TEXTURE),o.texParameteri(L,o.TEXTURE_COMPARE_FUNC,Zt[R.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(R.magFilter===si||R.minFilter!==zf&&R.minFilter!==cr||R.type===ts&&t.has("OES_texture_float_linear")===!1)return;if(R.anisotropy>1||i.get(R).__currentAnisotropy){const G=t.get("EXT_texture_filter_anisotropic");o.texParameterf(L,G.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,n.getMaxAnisotropy())),i.get(R).__currentAnisotropy=R.anisotropy}}}function K(L,R){let G=!1;L.__webglInit===void 0&&(L.__webglInit=!0,R.addEventListener("dispose",E));const Y=R.source;let J=f.get(Y);J===void 0&&(J={},f.set(Y,J));const ut=B(R);if(ut!==L.__cacheKey){J[ut]===void 0&&(J[ut]={texture:o.createTexture(),usedTimes:0},r.memory.textures++,G=!0),J[ut].usedTimes++;const pt=J[L.__cacheKey];pt!==void 0&&(J[L.__cacheKey].usedTimes--,pt.usedTimes===0&&_(R)),L.__cacheKey=ut,L.__webglTexture=J[ut].texture}return G}function lt(L,R,G){return Math.floor(Math.floor(L/G)/R)}function ct(L,R,G,Y){const ut=L.updateRanges;if(ut.length===0)e.texSubImage2D(o.TEXTURE_2D,0,0,0,R.width,R.height,G,Y,R.data);else{ut.sort(($t,xt)=>$t.start-xt.start);let pt=0;for(let $t=1;$t<ut.length;$t++){const xt=ut[pt],vt=ut[$t],Qt=xt.start+xt.count,ae=lt(vt.start,R.width,4),Ae=lt(xt.start,R.width,4);vt.start<=Qt+1&&ae===Ae&<(vt.start+vt.count-1,R.width,4)===ae?xt.count=Math.max(xt.count,vt.start+vt.count-xt.start):(++pt,ut[pt]=vt)}ut.length=pt+1;const j=e.getParameter(o.UNPACK_ROW_LENGTH),it=e.getParameter(o.UNPACK_SKIP_PIXELS),gt=e.getParameter(o.UNPACK_SKIP_ROWS);e.pixelStorei(o.UNPACK_ROW_LENGTH,R.width);for(let $t=0,xt=ut.length;$t<xt;$t++){const vt=ut[$t],Qt=Math.floor(vt.start/4),ae=Math.ceil(vt.count/4),Ae=Qt%R.width,U=Math.floor(Qt/R.width),ft=ae,et=1;e.pixelStorei(o.UNPACK_SKIP_PIXELS,Ae),e.pixelStorei(o.UNPACK_SKIP_ROWS,U),e.texSubImage2D(o.TEXTURE_2D,0,Ae,U,ft,et,G,Y,R.data)}L.clearUpdateRanges(),e.pixelStorei(o.UNPACK_ROW_LENGTH,j),e.pixelStorei(o.UNPACK_SKIP_PIXELS,it),e.pixelStorei(o.UNPACK_SKIP_ROWS,gt)}}function V(L,R,G){let Y=o.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(Y=o.TEXTURE_2D_ARRAY),R.isData3DTexture&&(Y=o.TEXTURE_3D);const J=K(L,R),ut=R.source;e.bindTexture(Y,L.__webglTexture,o.TEXTURE0+G);const pt=i.get(ut);if(ut.version!==pt.__version||J===!0){if(e.activeTexture(o.TEXTURE0+G),(typeof ImageBitmap<"u"&&R.image instanceof ImageBitmap)===!1){const et=He.getPrimaries(He.workingColorSpace),Mt=R.colorSpace===tc?null:He.getPrimaries(R.colorSpace),At=R.colorSpace===tc||et===Mt?o.NONE:o.BROWSER_DEFAULT_WEBGL;e.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,R.flipY),e.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),e.pixelStorei(o.UNPACK_COLORSPACE_CONVERSION_WEBGL,At)}e.pixelStorei(o.UNPACK_ALIGNMENT,R.unpackAlignment);let it=g(R.image,!1,n.maxTextureSize);it=Os(R,it);const gt=s.convert(R.format,R.colorSpace),$t=s.convert(R.type);let xt=y(R.internalFormat,gt,$t,R.normalized,R.colorSpace,R.isVideoTexture);jt(Y,R);let vt;const Qt=R.mipmaps,ae=R.isVideoTexture!==!0,Ae=pt.__version===void 0||J===!0,U=ut.dataReady,ft=b(R,it);if(R.isDepthTexture)xt=x(R.format===tl,R.type),Ae&&(ae?e.texStorage2D(o.TEXTURE_2D,1,xt,it.width,it.height):e.texImage2D(o.TEXTURE_2D,0,xt,it.width,it.height,0,gt,$t,null));else if(R.isDataTexture)if(Qt.length>0){ae&&Ae&&e.texStorage2D(o.TEXTURE_2D,ft,xt,Qt[0].width,Qt[0].height);for(let et=0,Mt=Qt.length;et<Mt;et++)vt=Qt[et],ae?U&&e.texSubImage2D(o.TEXTURE_2D,et,0,0,vt.width,vt.height,gt,$t,vt.data):e.texImage2D(o.TEXTURE_2D,et,xt,vt.width,vt.height,0,gt,$t,vt.data);R.generateMipmaps=!1}else ae?(Ae&&e.texStorage2D(o.TEXTURE_2D,ft,xt,it.width,it.height),U&&ct(R,it,gt,$t)):e.texImage2D(o.TEXTURE_2D,0,xt,it.width,it.height,0,gt,$t,it.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){ae&&Ae&&e.texStorage3D(o.TEXTURE_2D_ARRAY,ft,xt,Qt[0].width,Qt[0].height,it.depth);for(let et=0,Mt=Qt.length;et<Mt;et++)if(vt=Qt[et],R.format!==tn)if(gt!==null)if(ae){if(U)if(R.layerUpdates.size>0){const At=bx(vt.width,vt.height,R.format,R.type);for(const st of R.layerUpdates){const Wt=vt.data.subarray(st*At/vt.data.BYTES_PER_ELEMENT,(st+1)*At/vt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(o.TEXTURE_2D_ARRAY,et,0,0,st,vt.width,vt.height,1,gt,Wt)}R.clearLayerUpdates()}else e.compressedTexSubImage3D(o.TEXTURE_2D_ARRAY,et,0,0,0,vt.width,vt.height,it.depth,gt,vt.data)}else e.compressedTexImage3D(o.TEXTURE_2D_ARRAY,et,xt,vt.width,vt.height,it.depth,0,vt.data,0,0);else Ht("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else ae?U&&e.texSubImage3D(o.TEXTURE_2D_ARRAY,et,0,0,0,vt.width,vt.height,it.depth,gt,$t,vt.data):e.texImage3D(o.TEXTURE_2D_ARRAY,et,xt,vt.width,vt.height,it.depth,0,gt,$t,vt.data)}else{ae&&Ae&&e.texStorage2D(o.TEXTURE_2D,ft,xt,Qt[0].width,Qt[0].height);for(let et=0,Mt=Qt.length;et<Mt;et++)vt=Qt[et],R.format!==tn?gt!==null?ae?U&&e.compressedTexSubImage2D(o.TEXTURE_2D,et,0,0,vt.width,vt.height,gt,vt.data):e.compressedTexImage2D(o.TEXTURE_2D,et,xt,vt.width,vt.height,0,vt.data):Ht("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):ae?U&&e.texSubImage2D(o.TEXTURE_2D,et,0,0,vt.width,vt.height,gt,$t,vt.data):e.texImage2D(o.TEXTURE_2D,et,xt,vt.width,vt.height,0,gt,$t,vt.data)}else if(R.isDataArrayTexture)if(ae){if(Ae&&e.texStorage3D(o.TEXTURE_2D_ARRAY,ft,xt,it.width,it.height,it.depth),U)if(R.layerUpdates.size>0){const et=bx(it.width,it.height,R.format,R.type);for(const Mt of R.layerUpdates){const At=it.data.subarray(Mt*et/it.data.BYTES_PER_ELEMENT,(Mt+1)*et/it.data.BYTES_PER_ELEMENT);e.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,Mt,it.width,it.height,1,gt,$t,At)}R.clearLayerUpdates()}else e.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,0,it.width,it.height,it.depth,gt,$t,it.data)}else e.texImage3D(o.TEXTURE_2D_ARRAY,0,xt,it.width,it.height,it.depth,0,gt,$t,it.data);else if(R.isData3DTexture)ae?(Ae&&e.texStorage3D(o.TEXTURE_3D,ft,xt,it.width,it.height,it.depth),U&&e.texSubImage3D(o.TEXTURE_3D,0,0,0,0,it.width,it.height,it.depth,gt,$t,it.data)):e.texImage3D(o.TEXTURE_3D,0,xt,it.width,it.height,it.depth,0,gt,$t,it.data);else if(R.isFramebufferTexture){if(Ae)if(ae)e.texStorage2D(o.TEXTURE_2D,ft,xt,it.width,it.height);else{let et=it.width,Mt=it.height;for(let At=0;At<ft;At++)e.texImage2D(o.TEXTURE_2D,At,xt,et,Mt,0,gt,$t,null),et>>=1,Mt>>=1}}else if(R.isHTMLTexture){if("texElementImage2D"in o){const et=o.canvas;if(et.hasAttribute("layoutsubtree")||et.setAttribute("layoutsubtree","true"),it.parentNode!==et){et.appendChild(it),u.add(R),et.onpaint=Mt=>{const At=Mt.changedElements;for(const st of u)At.includes(st.image)&&(st.needsUpdate=!0)},et.requestPaint();return}if(o.texElementImage2D.length===3)o.texElementImage2D(o.TEXTURE_2D,o.RGBA8,it);else{const At=o.RGBA,st=o.RGBA,Wt=o.UNSIGNED_BYTE;o.texElementImage2D(o.TEXTURE_2D,0,At,st,Wt,it)}o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE)}}else if(Qt.length>0){if(ae&&Ae){const et=oi(Qt[0]);e.texStorage2D(o.TEXTURE_2D,ft,xt,et.width,et.height)}for(let et=0,Mt=Qt.length;et<Mt;et++)vt=Qt[et],ae?U&&e.texSubImage2D(o.TEXTURE_2D,et,0,0,gt,$t,vt):e.texImage2D(o.TEXTURE_2D,et,xt,gt,$t,vt);R.generateMipmaps=!1}else if(ae){if(Ae){const et=oi(it);e.texStorage2D(o.TEXTURE_2D,ft,xt,et.width,et.height)}U&&e.texSubImage2D(o.TEXTURE_2D,0,0,0,gt,$t,it)}else e.texImage2D(o.TEXTURE_2D,0,xt,gt,$t,it);v(R)&&M(Y),pt.__version=ut.version,R.onUpdate&&R.onUpdate(R)}L.__version=R.version}function Lt(L,R,G){if(R.image.length!==6)return;const Y=K(L,R),J=R.source;e.bindTexture(o.TEXTURE_CUBE_MAP,L.__webglTexture,o.TEXTURE0+G);const ut=i.get(J);if(J.version!==ut.__version||Y===!0){e.activeTexture(o.TEXTURE0+G);const pt=He.getPrimaries(He.workingColorSpace),j=R.colorSpace===tc?null:He.getPrimaries(R.colorSpace),it=R.colorSpace===tc||pt===j?o.NONE:o.BROWSER_DEFAULT_WEBGL;e.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,R.flipY),e.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),e.pixelStorei(o.UNPACK_ALIGNMENT,R.unpackAlignment),e.pixelStorei(o.UNPACK_COLORSPACE_CONVERSION_WEBGL,it);const gt=R.isCompressedTexture||R.image[0].isCompressedTexture,$t=R.image[0]&&R.image[0].isDataTexture,xt=[];for(let st=0;st<6;st++)!gt&&!$t?xt[st]=g(R.image[st],!0,n.maxCubemapSize):xt[st]=$t?R.image[st].image:R.image[st],xt[st]=Os(R,xt[st]);const vt=xt[0],Qt=s.convert(R.format,R.colorSpace),ae=s.convert(R.type),Ae=y(R.internalFormat,Qt,ae,R.normalized,R.colorSpace),U=R.isVideoTexture!==!0,ft=ut.__version===void 0||Y===!0,et=J.dataReady;let Mt=b(R,vt);jt(o.TEXTURE_CUBE_MAP,R);let At;if(gt){U&&ft&&e.texStorage2D(o.TEXTURE_CUBE_MAP,Mt,Ae,vt.width,vt.height);for(let st=0;st<6;st++){At=xt[st].mipmaps;for(let Wt=0;Wt<At.length;Wt++){const Ft=At[Wt];R.format!==tn?Qt!==null?U?et&&e.compressedTexSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,0,0,Ft.width,Ft.height,Qt,Ft.data):e.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,Ae,Ft.width,Ft.height,0,Ft.data):Ht("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,0,0,Ft.width,Ft.height,Qt,ae,Ft.data):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,Ae,Ft.width,Ft.height,0,Qt,ae,Ft.data)}}}else{if(At=R.mipmaps,U&&ft){At.length>0&&Mt++;const st=oi(xt[0]);e.texStorage2D(o.TEXTURE_CUBE_MAP,Mt,Ae,st.width,st.height)}for(let st=0;st<6;st++)if($t){U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,0,0,xt[st].width,xt[st].height,Qt,ae,xt[st].data):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,Ae,xt[st].width,xt[st].height,0,Qt,ae,xt[st].data);for(let Wt=0;Wt<At.length;Wt++){const Ki=At[Wt].image[st].image;U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,0,0,Ki.width,Ki.height,Qt,ae,Ki.data):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,Ae,Ki.width,Ki.height,0,Qt,ae,Ki.data)}}else{U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,0,0,Qt,ae,xt[st]):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,Ae,Qt,ae,xt[st]);for(let Wt=0;Wt<At.length;Wt++){const Ft=At[Wt];U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,0,0,Qt,ae,Ft.image[st]):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,Ae,Qt,ae,Ft.image[st])}}}v(R)&&M(o.TEXTURE_CUBE_MAP),ut.__version=J.version,R.onUpdate&&R.onUpdate(R)}L.__version=R.version}function Xt(L,R,G,Y,J,ut){const pt=s.convert(G.format,G.colorSpace),j=s.convert(G.type),it=y(G.internalFormat,pt,j,G.normalized,G.colorSpace),gt=i.get(R),$t=i.get(G);if($t.__renderTarget=R,!gt.__hasExternalTextures){const xt=Math.max(1,R.width>>ut),vt=Math.max(1,R.height>>ut);J===o.TEXTURE_3D||J===o.TEXTURE_2D_ARRAY?e.texImage3D(J,ut,it,xt,vt,R.depth,0,pt,j,null):e.texImage2D(J,ut,it,xt,vt,0,pt,j,null)}e.bindFramebuffer(o.FRAMEBUFFER,L),un(R)?a.framebufferTexture2DMultisampleEXT(o.FRAMEBUFFER,Y,J,$t.__webglTexture,0,Yi(R)):(J===o.TEXTURE_2D||J>=o.TEXTURE_CUBE_MAP_POSITIVE_X&&J<=o.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&o.framebufferTexture2D(o.FRAMEBUFFER,Y,J,$t.__webglTexture,ut),e.bindFramebuffer(o.FRAMEBUFFER,null)}function kt(L,R,G){if(o.bindRenderbuffer(o.RENDERBUFFER,L),R.depthBuffer){const Y=R.depthTexture,J=Y&&Y.isDepthTexture?Y.type:null,ut=x(R.stencilBuffer,J),pt=R.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT;un(R)?a.renderbufferStorageMultisampleEXT(o.RENDERBUFFER,Yi(R),ut,R.width,R.height):G?o.renderbufferStorageMultisample(o.RENDERBUFFER,Yi(R),ut,R.width,R.height):o.renderbufferStorage(o.RENDERBUFFER,ut,R.width,R.height),o.framebufferRenderbuffer(o.FRAMEBUFFER,pt,o.RENDERBUFFER,L)}else{const Y=R.textures;for(let J=0;J<Y.length;J++){const ut=Y[J],pt=s.convert(ut.format,ut.colorSpace),j=s.convert(ut.type),it=y(ut.internalFormat,pt,j,ut.normalized,ut.colorSpace);un(R)?a.renderbufferStorageMultisampleEXT(o.RENDERBUFFER,Yi(R),it,R.width,R.height):G?o.renderbufferStorageMultisample(o.RENDERBUFFER,Yi(R),it,R.width,R.height):o.renderbufferStorage(o.RENDERBUFFER,it,R.width,R.height)}}o.bindRenderbuffer(o.RENDERBUFFER,null)}function Rt(L,R,G){const Y=R.isWebGLCubeRenderTarget===!0;if(e.bindFramebuffer(o.FRAMEBUFFER,L),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const J=i.get(R.depthTexture);if(J.__renderTarget=R,(!J.__webglTexture||R.depthTexture.image.width!==R.width||R.depthTexture.image.height!==R.height)&&(R.depthTexture.image.width=R.width,R.depthTexture.image.height=R.height,R.depthTexture.needsUpdate=!0),Y){if(J.__webglInit===void 0&&(J.__webglInit=!0,R.depthTexture.addEventListener("dispose",E)),J.__webglTexture===void 0){J.__webglTexture=o.createTexture(),e.bindTexture(o.TEXTURE_CUBE_MAP,J.__webglTexture),jt(o.TEXTURE_CUBE_MAP,R.depthTexture);const gt=s.convert(R.depthTexture.format),$t=s.convert(R.depthTexture.type);let xt;R.depthTexture.format===So?xt=o.DEPTH_COMPONENT24:R.depthTexture.format===tl&&(xt=o.DEPTH24_STENCIL8);for(let vt=0;vt<6;vt++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+vt,0,xt,R.width,R.height,0,gt,$t,null)}}else W(R.depthTexture,0);const ut=J.__webglTexture,pt=Yi(R),j=Y?o.TEXTURE_CUBE_MAP_POSITIVE_X+G:o.TEXTURE_2D,it=R.depthTexture.format===tl?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT;if(R.depthTexture.format===So)un(R)?a.framebufferTexture2DMultisampleEXT(o.FRAMEBUFFER,it,j,ut,0,pt):o.framebufferTexture2D(o.FRAMEBUFFER,it,j,ut,0);else if(R.depthTexture.format===tl)un(R)?a.framebufferTexture2DMultisampleEXT(o.FRAMEBUFFER,it,j,ut,0,pt):o.framebufferTexture2D(o.FRAMEBUFFER,it,j,ut,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function te(L){const R=i.get(L),G=L.isWebGLCubeRenderTarget===!0;if(R.__boundDepthTexture!==L.depthTexture){const Y=L.depthTexture;if(R.__depthDisposeCallback&&R.__depthDisposeCallback(),Y){const J=()=>{delete R.__boundDepthTexture,delete R.__depthDisposeCallback,Y.removeEventListener("dispose",J)};Y.addEventListener("dispose",J),R.__depthDisposeCallback=J}R.__boundDepthTexture=Y}if(L.depthTexture&&!R.__autoAllocateDepthBuffer)if(G)for(let Y=0;Y<6;Y++)Rt(R.__webglFramebuffer[Y],L,Y);else{const Y=L.texture.mipmaps;Y&&Y.length>0?Rt(R.__webglFramebuffer[0],L,0):Rt(R.__webglFramebuffer,L,0)}else if(G){R.__webglDepthbuffer=[];for(let Y=0;Y<6;Y++)if(e.bindFramebuffer(o.FRAMEBUFFER,R.__webglFramebuffer[Y]),R.__webglDepthbuffer[Y]===void 0)R.__webglDepthbuffer[Y]=o.createRenderbuffer(),kt(R.__webglDepthbuffer[Y],L,!1);else{const J=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT,ut=R.__webglDepthbuffer[Y];o.bindRenderbuffer(o.RENDERBUFFER,ut),o.framebufferRenderbuffer(o.FRAMEBUFFER,J,o.RENDERBUFFER,ut)}}else{const Y=L.texture.mipmaps;if(Y&&Y.length>0?e.bindFramebuffer(o.FRAMEBUFFER,R.__webglFramebuffer[0]):e.bindFramebuffer(o.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer===void 0)R.__webglDepthbuffer=o.createRenderbuffer(),kt(R.__webglDepthbuffer,L,!1);else{const J=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT,ut=R.__webglDepthbuffer;o.bindRenderbuffer(o.RENDERBUFFER,ut),o.framebufferRenderbuffer(o.FRAMEBUFFER,J,o.RENDERBUFFER,ut)}}e.bindFramebuffer(o.FRAMEBUFFER,null)}function ne(L,R,G){const Y=i.get(L);R!==void 0&&Xt(Y.__webglFramebuffer,L,L.texture,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,0),G!==void 0&&te(L)}function se(L){const R=L.texture,G=i.get(L),Y=i.get(R);L.addEventListener("dispose",S);const J=L.textures,ut=L.isWebGLCubeRenderTarget===!0,pt=J.length>1;if(pt||(Y.__webglTexture===void 0&&(Y.__webglTexture=o.createTexture()),Y.__version=R.version,r.memory.textures++),ut){G.__webglFramebuffer=[];for(let j=0;j<6;j++)if(R.mipmaps&&R.mipmaps.length>0){G.__webglFramebuffer[j]=[];for(let it=0;it<R.mipmaps.length;it++)G.__webglFramebuffer[j][it]=o.createFramebuffer()}else G.__webglFramebuffer[j]=o.createFramebuffer()}else{if(R.mipmaps&&R.mipmaps.length>0){G.__webglFramebuffer=[];for(let j=0;j<R.mipmaps.length;j++)G.__webglFramebuffer[j]=o.createFramebuffer()}else G.__webglFramebuffer=o.createFramebuffer();if(pt)for(let j=0,it=J.length;j<it;j++){const gt=i.get(J[j]);gt.__webglTexture===void 0&&(gt.__webglTexture=o.createTexture(),r.memory.textures++)}if(L.samples>0&&un(L)===!1){G.__webglMultisampledFramebuffer=o.createFramebuffer(),G.__webglColorRenderbuffer=[],e.bindFramebuffer(o.FRAMEBUFFER,G.__webglMultisampledFramebuffer);for(let j=0;j<J.length;j++){const it=J[j];G.__webglColorRenderbuffer[j]=o.createRenderbuffer(),o.bindRenderbuffer(o.RENDERBUFFER,G.__webglColorRenderbuffer[j]);const gt=s.convert(it.format,it.colorSpace),$t=s.convert(it.type),xt=y(it.internalFormat,gt,$t,it.normalized,it.colorSpace,L.isXRRenderTarget===!0),vt=Yi(L);o.renderbufferStorageMultisample(o.RENDERBUFFER,vt,xt,L.width,L.height),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+j,o.RENDERBUFFER,G.__webglColorRenderbuffer[j])}o.bindRenderbuffer(o.RENDERBUFFER,null),L.depthBuffer&&(G.__webglDepthRenderbuffer=o.createRenderbuffer(),kt(G.__webglDepthRenderbuffer,L,!0)),e.bindFramebuffer(o.FRAMEBUFFER,null)}}if(ut){e.bindTexture(o.TEXTURE_CUBE_MAP,Y.__webglTexture),jt(o.TEXTURE_CUBE_MAP,R);for(let j=0;j<6;j++)if(R.mipmaps&&R.mipmaps.length>0)for(let it=0;it<R.mipmaps.length;it++)Xt(G.__webglFramebuffer[j][it],L,R,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+j,it);else Xt(G.__webglFramebuffer[j],L,R,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+j,0);v(R)&&M(o.TEXTURE_CUBE_MAP),e.unbindTexture()}else if(pt){for(let j=0,it=J.length;j<it;j++){const gt=J[j],$t=i.get(gt);let xt=o.TEXTURE_2D;(L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(xt=L.isWebGL3DRenderTarget?o.TEXTURE_3D:o.TEXTURE_2D_ARRAY),e.bindTexture(xt,$t.__webglTexture),jt(xt,gt),Xt(G.__webglFramebuffer,L,gt,o.COLOR_ATTACHMENT0+j,xt,0),v(gt)&&M(xt)}e.unbindTexture()}else{let j=o.TEXTURE_2D;if((L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(j=L.isWebGL3DRenderTarget?o.TEXTURE_3D:o.TEXTURE_2D_ARRAY),e.bindTexture(j,Y.__webglTexture),jt(j,R),R.mipmaps&&R.mipmaps.length>0)for(let it=0;it<R.mipmaps.length;it++)Xt(G.__webglFramebuffer[it],L,R,o.COLOR_ATTACHMENT0,j,it);else Xt(G.__webglFramebuffer,L,R,o.COLOR_ATTACHMENT0,j,0);v(R)&&M(j),e.unbindTexture()}L.depthBuffer&&te(L)}function ri(L){const R=L.textures;for(let G=0,Y=R.length;G<Y;G++){const J=R[G];if(v(J)){const ut=w(L),pt=i.get(J).__webglTexture;e.bindTexture(ut,pt),M(ut),e.unbindTexture()}}}const ai=[],$i=[];function Gi(L){if(L.samples>0){if(un(L)===!1){const R=L.textures,G=L.width,Y=L.height;let J=o.COLOR_BUFFER_BIT;const ut=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT,pt=i.get(L),j=R.length>1;if(j)for(let gt=0;gt<R.length;gt++)e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglMultisampledFramebuffer),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.RENDERBUFFER,null),e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglFramebuffer),o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.TEXTURE_2D,null,0);e.bindFramebuffer(o.READ_FRAMEBUFFER,pt.__webglMultisampledFramebuffer);const it=L.texture.mipmaps;it&&it.length>0?e.bindFramebuffer(o.DRAW_FRAMEBUFFER,pt.__webglFramebuffer[0]):e.bindFramebuffer(o.DRAW_FRAMEBUFFER,pt.__webglFramebuffer);for(let gt=0;gt<R.length;gt++){if(L.resolveDepthBuffer&&(L.depthBuffer&&(J|=o.DEPTH_BUFFER_BIT),L.stencilBuffer&&L.resolveStencilBuffer&&(J|=o.STENCIL_BUFFER_BIT)),j){o.framebufferRenderbuffer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.RENDERBUFFER,pt.__webglColorRenderbuffer[gt]);const $t=i.get(R[gt]).__webglTexture;o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,$t,0)}o.blitFramebuffer(0,0,G,Y,0,0,G,Y,J,o.NEAREST),c===!0&&(ai.length=0,$i.length=0,ai.push(o.COLOR_ATTACHMENT0+gt),L.depthBuffer&&L.resolveDepthBuffer===!1&&(ai.push(ut),$i.push(ut),o.invalidateFramebuffer(o.DRAW_FRAMEBUFFER,$i)),o.invalidateFramebuffer(o.READ_FRAMEBUFFER,ai))}if(e.bindFramebuffer(o.READ_FRAMEBUFFER,null),e.bindFramebuffer(o.DRAW_FRAMEBUFFER,null),j)for(let gt=0;gt<R.length;gt++){e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglMultisampledFramebuffer),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.RENDERBUFFER,pt.__webglColorRenderbuffer[gt]);const $t=i.get(R[gt]).__webglTexture;e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglFramebuffer),o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.TEXTURE_2D,$t,0)}e.bindFramebuffer(o.DRAW_FRAMEBUFFER,pt.__webglMultisampledFramebuffer)}else if(L.depthBuffer&&L.resolveDepthBuffer===!1&&c){const R=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT;o.invalidateFramebuffer(o.DRAW_FRAMEBUFFER,[R])}}}function Yi(L){return Math.min(n.maxSamples,L.samples)}function un(L){const R=i.get(L);return L.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function z(L){const R=r.render.frame;h.get(L)!==R&&(h.set(L,R),L.update())}function Os(L,R){const G=L.colorSpace,Y=L.format,J=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||G!==G0&&G!==tc&&(He.getTransfer(G)===ui?(Y!==tn||J!==fs)&&Ht("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):le("WebGLTextures: Unsupported texture color space:",G)),R}function oi(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(l.width=L.naturalWidth||L.width,l.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(l.width=L.displayWidth,l.height=L.displayHeight):(l.width=L.width,l.height=L.height),l}this.allocateTextureUnit=k,this.resetTextureUnits=O,this.getTextureUnits=P,this.setTextureUnits=N,this.setTexture2D=W,this.setTexture2DArray=Q,this.setTexture3D=Z,this.setTextureCube=nt,this.rebindTextures=ne,this.setupRenderTarget=se,this.updateRenderTargetMipmap=ri,this.updateMultisampleRenderTarget=Gi,this.setupDepthRenderbuffer=te,this.setupFrameBufferTexture=Xt,this.useMultisampledRTT=un,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function YP(o,t){function e(i,n=tc){let s;const r=He.getTransfer(n);if(i===fs)return o.UNSIGNED_BYTE;if(i===cy)return o.UNSIGNED_SHORT_4_4_4_4;if(i===ly)return o.UNSIGNED_SHORT_5_5_5_1;if(i===eA)return o.UNSIGNED_INT_5_9_9_9_REV;if(i===iA)return o.UNSIGNED_INT_10F_11F_11F_REV;if(i===QE)return o.BYTE;if(i===tA)return o.SHORT;if(i===of)return o.UNSIGNED_SHORT;if(i===oy)return o.INT;if(i===_r)return o.UNSIGNED_INT;if(i===ts)return o.FLOAT;if(i===Ye)return o.HALF_FLOAT;if(i===nA)return o.ALPHA;if(i===sA)return o.RGB;if(i===tn)return o.RGBA;if(i===So)return o.DEPTH_COMPONENT;if(i===tl)return o.DEPTH_STENCIL;if(i===mu)return o.RED;if(i===hy)return o.RED_INTEGER;if(i===xl)return o.RG;if(i===uy)return o.RG_INTEGER;if(i===dy)return o.RGBA_INTEGER;if(i===s0||i===r0||i===a0||i===o0)if(r===ui)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===s0)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===r0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===a0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===o0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===s0)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===r0)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===a0)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===o0)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===xv||i===bv||i===Sv||i===Ev)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===xv)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===bv)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Sv)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Ev)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Av||i===_v||i===Tv||i===Rv||i===Iv||i===F0||i===Dv)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===Av||i===_v)return r===ui?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Tv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===Rv)return s.COMPRESSED_R11_EAC;if(i===Iv)return s.COMPRESSED_SIGNED_R11_EAC;if(i===F0)return s.COMPRESSED_RG11_EAC;if(i===Dv)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===Cv||i===Ov||i===Pv||i===Nv||i===Lv||i===kv||i===Fv||i===Uv||i===zv||i===Bv||i===Hv||i===Gv||i===Vv||i===Wv)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===Cv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Ov)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Pv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Nv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Lv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===kv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Fv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Uv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===zv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Bv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Hv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Gv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Vv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Wv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Xv||i===$v||i===Yv)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===Xv)return r===ui?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===$v)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Yv)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Kv||i===qv||i===U0||i===Zv)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===Kv)return s.COMPRESSED_RED_RGTC1_EXT;if(i===qv)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===U0)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Zv)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===cf?o.UNSIGNED_INT_24_8:o[i]!==void 0?o[i]:null}return{convert:e}}const KP=`
|
|
4870
|
+
}`,GP=[new T(1,0,0),new T(-1,0,0),new T(0,1,0),new T(0,-1,0),new T(0,0,1),new T(0,0,-1)],VP=[new T(0,-1,0),new T(0,-1,0),new T(0,0,1),new T(0,0,-1),new T(0,-1,0),new T(0,-1,0)],Wx=new Gt,Wu=new T,Yg=new T;function WP(o,t,e){let i=new Cm;const n=new tt,s=new tt,r=new Ie,a=new RI,c=new II,l={},h=e.maxTextureSize,u={[Ba]:zi,[zi]:Ba,[Tn]:Tn},d=new De({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new tt},radius:{value:4}},vertexShader:BP,fragmentShader:HP}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new be;p.setAttribute("position",new we(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new yt(p,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=dd;let v=this.type;this.render=function(b,E,S){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||b.length===0)return;this.type===M4&&(Ht("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=dd);const A=o.getRenderTarget(),_=o.getActiveCubeFace(),I=o.getActiveMipmapLevel(),D=o.state;D.setBlending(Ys),D.buffers.depth.getReversed()===!0?D.buffers.color.setClear(0,0,0,0):D.buffers.color.setClear(1,1,1,1),D.buffers.depth.setTest(!0),D.setScissorTest(!1);const O=v!==this.type;O&&E.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(N=>N.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,N=b.length;P<N;P++){const k=b[P],B=k.shadow;if(B===void 0){Ht("WebGLShadowMap:",k,"has no shadow.");continue}if(B.autoUpdate===!1&&B.needsUpdate===!1)continue;n.copy(B.mapSize);const W=B.getFrameExtents();n.multiply(W),s.copy(B.mapSize),(n.x>h||n.y>h)&&(n.x>h&&(s.x=Math.floor(h/W.x),n.x=s.x*W.x,B.mapSize.x=s.x),n.y>h&&(s.y=Math.floor(h/W.y),n.y=s.y*W.y,B.mapSize.y=s.y));const Q=o.state.buffers.depth.getReversed();if(B.camera._reversedDepth=Q,B.map===null||O===!0){if(B.map!==null&&(B.map.depthTexture!==null&&(B.map.depthTexture.dispose(),B.map.depthTexture=null),B.map.dispose()),this.type===cd){if(k.isPointLight){Ht("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}B.map=new Qe(n.x,n.y,{format:xl,type:Ye,minFilter:Me,magFilter:Me,generateMipmaps:!1}),B.map.texture.name=k.name+".shadowMap",B.map.depthTexture=new Sc(n.x,n.y,ts),B.map.depthTexture.name=k.name+".shadowMapDepth",B.map.depthTexture.format=So,B.map.depthTexture.compareFunction=null,B.map.depthTexture.minFilter=si,B.map.depthTexture.magFilter=si}else k.isPointLight?(B.map=new pf(n.x),B.map.depthTexture=new WR(n.x,_r)):(B.map=new Qe(n.x,n.y),B.map.depthTexture=new Sc(n.x,n.y,_r)),B.map.depthTexture.name=k.name+".shadowMap",B.map.depthTexture.format=So,this.type===dd?(B.map.depthTexture.compareFunction=Q?my:py,B.map.depthTexture.minFilter=Me,B.map.depthTexture.magFilter=Me):(B.map.depthTexture.compareFunction=null,B.map.depthTexture.minFilter=si,B.map.depthTexture.magFilter=si);B.camera.updateProjectionMatrix()}const Z=B.map.isWebGLCubeRenderTarget?6:1;for(let nt=0;nt<Z;nt++){if(B.map.isWebGLCubeRenderTarget)o.setRenderTarget(B.map,nt),o.clear();else{nt===0&&(o.setRenderTarget(B.map),o.clear());const ot=B.getViewport(nt);r.set(s.x*ot.x,s.y*ot.y,s.x*ot.z,s.y*ot.w),D.viewport(r)}if(k.isPointLight){const ot=B.camera,Ut=B.matrix,Zt=k.distance||ot.far;Zt!==ot.far&&(ot.far=Zt,ot.updateProjectionMatrix()),Wu.setFromMatrixPosition(k.matrixWorld),ot.position.copy(Wu),Yg.copy(ot.position),Yg.add(GP[nt]),ot.up.copy(VP[nt]),ot.lookAt(Yg),ot.updateMatrixWorld(),Ut.makeTranslation(-Wu.x,-Wu.y,-Wu.z),Wx.multiplyMatrices(ot.projectionMatrix,ot.matrixWorldInverse),B._frustum.setFromProjectionMatrix(Wx,ot.coordinateSystem,ot.reversedDepth)}else B.updateMatrices(k);i=B.getFrustum(),y(E,S,B.camera,k,this.type)}B.isPointLightShadow!==!0&&this.type===cd&&M(B,S),B.needsUpdate=!1}v=this.type,g.needsUpdate=!1,o.setRenderTarget(A,_,I)};function M(b,E){const S=t.update(m);d.defines.VSM_SAMPLES!==b.blurSamples&&(d.defines.VSM_SAMPLES=b.blurSamples,f.defines.VSM_SAMPLES=b.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),b.mapPass===null&&(b.mapPass=new Qe(n.x,n.y,{format:xl,type:Ye})),d.uniforms.shadow_pass.value=b.map.depthTexture,d.uniforms.resolution.value=b.mapSize,d.uniforms.radius.value=b.radius,o.setRenderTarget(b.mapPass),o.clear(),o.renderBufferDirect(E,null,S,d,m,null),f.uniforms.shadow_pass.value=b.mapPass.texture,f.uniforms.resolution.value=b.mapSize,f.uniforms.radius.value=b.radius,o.setRenderTarget(b.map),o.clear(),o.renderBufferDirect(E,null,S,f,m,null)}function w(b,E,S,A){let _=null;const I=S.isPointLight===!0?b.customDistanceMaterial:b.customDepthMaterial;if(I!==void 0)_=I;else if(_=S.isPointLight===!0?c:a,o.localClippingEnabled&&E.clipShadows===!0&&Array.isArray(E.clippingPlanes)&&E.clippingPlanes.length!==0||E.displacementMap&&E.displacementScale!==0||E.alphaMap&&E.alphaTest>0||E.map&&E.alphaTest>0||E.alphaToCoverage===!0){const D=_.uuid,O=E.uuid;let P=l[D];P===void 0&&(P={},l[D]=P);let N=P[O];N===void 0&&(N=_.clone(),P[O]=N,E.addEventListener("dispose",x)),_=N}if(_.visible=E.visible,_.wireframe=E.wireframe,A===cd?_.side=E.shadowSide!==null?E.shadowSide:E.side:_.side=E.shadowSide!==null?E.shadowSide:u[E.side],_.alphaMap=E.alphaMap,_.alphaTest=E.alphaToCoverage===!0?.5:E.alphaTest,_.map=E.map,_.clipShadows=E.clipShadows,_.clippingPlanes=E.clippingPlanes,_.clipIntersection=E.clipIntersection,_.displacementMap=E.displacementMap,_.displacementScale=E.displacementScale,_.displacementBias=E.displacementBias,_.wireframeLinewidth=E.wireframeLinewidth,_.linewidth=E.linewidth,S.isPointLight===!0&&_.isMeshDistanceMaterial===!0){const D=o.properties.get(_);D.light=S}return _}function y(b,E,S,A,_){if(b.visible===!1)return;if(b.layers.test(E.layers)&&(b.isMesh||b.isLine||b.isPoints)&&(b.castShadow||b.receiveShadow&&_===cd)&&(!b.frustumCulled||i.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,b.matrixWorld);const O=t.update(b),P=b.material;if(Array.isArray(P)){const N=O.groups;for(let k=0,B=N.length;k<B;k++){const W=N[k],Q=P[W.materialIndex];if(Q&&Q.visible){const Z=w(b,Q,A,_);b.onBeforeShadow(o,b,E,S,O,Z,W),o.renderBufferDirect(S,null,O,Z,b,W),b.onAfterShadow(o,b,E,S,O,Z,W)}}}else if(P.visible){const N=w(b,P,A,_);b.onBeforeShadow(o,b,E,S,O,N,null),o.renderBufferDirect(S,null,O,N,b,null),b.onAfterShadow(o,b,E,S,O,N,null)}}const D=b.children;for(let O=0,P=D.length;O<P;O++)y(D[O],E,S,A,_)}function x(b){b.target.removeEventListener("dispose",x);for(const S in l){const A=l[S],_=b.target.uuid;_ in A&&(A[_].dispose(),delete A[_])}}}function XP(o,t){function e(){let U=!1;const ft=new Ie;let et=null;const Mt=new Ie(0,0,0,0);return{setMask:function(At){et!==At&&!U&&(o.colorMask(At,At,At,At),et=At)},setLocked:function(At){U=At},setClear:function(At,st,Wt,Ft,Ki){Ki===!0&&(At*=Ft,st*=Ft,Wt*=Ft),ft.set(At,st,Wt,Ft),Mt.equals(ft)===!1&&(o.clearColor(At,st,Wt,Ft),Mt.copy(ft))},reset:function(){U=!1,et=null,Mt.set(-1,0,0,0)}}}function i(){let U=!1,ft=!1,et=null,Mt=null,At=null;return{setReversed:function(st){if(ft!==st){const Wt=t.get("EXT_clip_control");st?Wt.clipControlEXT(Wt.LOWER_LEFT_EXT,Wt.ZERO_TO_ONE_EXT):Wt.clipControlEXT(Wt.LOWER_LEFT_EXT,Wt.NEGATIVE_ONE_TO_ONE_EXT),ft=st;const Ft=At;At=null,this.setClear(Ft)}},getReversed:function(){return ft},setTest:function(st){st?ct(o.DEPTH_TEST):V(o.DEPTH_TEST)},setMask:function(st){et!==st&&!U&&(o.depthMask(st),et=st)},setFunc:function(st){if(ft&&(st=Q4[st]),Mt!==st){switch(st){case fv:o.depthFunc(o.NEVER);break;case pv:o.depthFunc(o.ALWAYS);break;case mv:o.depthFunc(o.LESS);break;case fu:o.depthFunc(o.LEQUAL);break;case gv:o.depthFunc(o.EQUAL);break;case vv:o.depthFunc(o.GEQUAL);break;case Mv:o.depthFunc(o.GREATER);break;case yv:o.depthFunc(o.NOTEQUAL);break;default:o.depthFunc(o.LEQUAL)}Mt=st}},setLocked:function(st){U=st},setClear:function(st){At!==st&&(At=st,ft&&(st=1-st),o.clearDepth(st))},reset:function(){U=!1,et=null,Mt=null,At=null,ft=!1}}}function n(){let U=!1,ft=null,et=null,Mt=null,At=null,st=null,Wt=null,Ft=null,Ki=null;return{setTest:function(Ti){U||(Ti?ct(o.STENCIL_TEST):V(o.STENCIL_TEST))},setMask:function(Ti){ft!==Ti&&!U&&(o.stencilMask(Ti),ft=Ti)},setFunc:function(Ti,Zr,Jr){(et!==Ti||Mt!==Zr||At!==Jr)&&(o.stencilFunc(Ti,Zr,Jr),et=Ti,Mt=Zr,At=Jr)},setOp:function(Ti,Zr,Jr){(st!==Ti||Wt!==Zr||Ft!==Jr)&&(o.stencilOp(Ti,Zr,Jr),st=Ti,Wt=Zr,Ft=Jr)},setLocked:function(Ti){U=Ti},setClear:function(Ti){Ki!==Ti&&(o.clearStencil(Ti),Ki=Ti)},reset:function(){U=!1,ft=null,et=null,Mt=null,At=null,st=null,Wt=null,Ft=null,Ki=null}}}const s=new e,r=new i,a=new n,c=new WeakMap,l=new WeakMap;let h={},u={},d={},f=new WeakMap,p=[],m=null,g=!1,v=null,M=null,w=null,y=null,x=null,b=null,E=null,S=new rt(0,0,0),A=0,_=!1,I=null,D=null,O=null,P=null,N=null;const k=o.getParameter(o.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let B=!1,W=0;const Q=o.getParameter(o.VERSION);Q.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(Q)[1]),B=W>=1):Q.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),B=W>=2);let Z=null,nt={};const ot=o.getParameter(o.SCISSOR_BOX),Ut=o.getParameter(o.VIEWPORT),Zt=new Ie().fromArray(ot),jt=new Ie().fromArray(Ut);function K(U,ft,et,Mt){const At=new Uint8Array(4),st=o.createTexture();o.bindTexture(U,st),o.texParameteri(U,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(U,o.TEXTURE_MAG_FILTER,o.NEAREST);for(let Wt=0;Wt<et;Wt++)U===o.TEXTURE_3D||U===o.TEXTURE_2D_ARRAY?o.texImage3D(ft,0,o.RGBA,1,1,Mt,0,o.RGBA,o.UNSIGNED_BYTE,At):o.texImage2D(ft+Wt,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,At);return st}const lt={};lt[o.TEXTURE_2D]=K(o.TEXTURE_2D,o.TEXTURE_2D,1),lt[o.TEXTURE_CUBE_MAP]=K(o.TEXTURE_CUBE_MAP,o.TEXTURE_CUBE_MAP_POSITIVE_X,6),lt[o.TEXTURE_2D_ARRAY]=K(o.TEXTURE_2D_ARRAY,o.TEXTURE_2D_ARRAY,1,1),lt[o.TEXTURE_3D]=K(o.TEXTURE_3D,o.TEXTURE_3D,1,1),s.setClear(0,0,0,1),r.setClear(1),a.setClear(0),ct(o.DEPTH_TEST),r.setFunc(fu),ri(!1),ai(Mw),ct(o.CULL_FACE),ne(Ys);function ct(U){h[U]!==!0&&(o.enable(U),h[U]=!0)}function V(U){h[U]!==!1&&(o.disable(U),h[U]=!1)}function Lt(U,ft){return d[U]!==ft?(o.bindFramebuffer(U,ft),d[U]=ft,U===o.DRAW_FRAMEBUFFER&&(d[o.FRAMEBUFFER]=ft),U===o.FRAMEBUFFER&&(d[o.DRAW_FRAMEBUFFER]=ft),!0):!1}function Xt(U,ft){let et=p,Mt=!1;if(U){et=f.get(ft),et===void 0&&(et=[],f.set(ft,et));const At=U.textures;if(et.length!==At.length||et[0]!==o.COLOR_ATTACHMENT0){for(let st=0,Wt=At.length;st<Wt;st++)et[st]=o.COLOR_ATTACHMENT0+st;et.length=At.length,Mt=!0}}else et[0]!==o.BACK&&(et[0]=o.BACK,Mt=!0);Mt&&o.drawBuffers(et)}function kt(U){return m!==U?(o.useProgram(U),m=U,!0):!1}const Rt={[ao]:o.FUNC_ADD,[y4]:o.FUNC_SUBTRACT,[w4]:o.FUNC_REVERSE_SUBTRACT};Rt[x4]=o.MIN,Rt[b4]=o.MAX;const te={[Ta]:o.ZERO,[yl]:o.ONE,[S4]:o.SRC_COLOR,[k0]:o.SRC_ALPHA,[I4]:o.SRC_ALPHA_SATURATE,[T4]:o.DST_COLOR,[A4]:o.DST_ALPHA,[E4]:o.ONE_MINUS_SRC_COLOR,[af]:o.ONE_MINUS_SRC_ALPHA,[R4]:o.ONE_MINUS_DST_COLOR,[_4]:o.ONE_MINUS_DST_ALPHA,[D4]:o.CONSTANT_COLOR,[C4]:o.ONE_MINUS_CONSTANT_COLOR,[O4]:o.CONSTANT_ALPHA,[P4]:o.ONE_MINUS_CONSTANT_ALPHA};function ne(U,ft,et,Mt,At,st,Wt,Ft,Ki,Ti){if(U===Ys){g===!0&&(V(o.BLEND),g=!1);return}if(g===!1&&(ct(o.BLEND),g=!0),U!==Ml){if(U!==v||Ti!==_){if((M!==ao||x!==ao)&&(o.blendEquation(o.FUNC_ADD),M=ao,x=ao),Ti)switch(U){case Mc:o.blendFuncSeparate(o.ONE,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA);break;case Cn:o.blendFunc(o.ONE,o.ONE);break;case yw:o.blendFuncSeparate(o.ZERO,o.ONE_MINUS_SRC_COLOR,o.ZERO,o.ONE);break;case ww:o.blendFuncSeparate(o.DST_COLOR,o.ONE_MINUS_SRC_ALPHA,o.ZERO,o.ONE);break;default:le("WebGLState: Invalid blending: ",U);break}else switch(U){case Mc:o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA);break;case Cn:o.blendFuncSeparate(o.SRC_ALPHA,o.ONE,o.ONE,o.ONE);break;case yw:le("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case ww:le("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:le("WebGLState: Invalid blending: ",U);break}w=null,y=null,b=null,E=null,S.set(0,0,0),A=0,v=U,_=Ti}return}At=At||ft,st=st||et,Wt=Wt||Mt,(ft!==M||At!==x)&&(o.blendEquationSeparate(Rt[ft],Rt[At]),M=ft,x=At),(et!==w||Mt!==y||st!==b||Wt!==E)&&(o.blendFuncSeparate(te[et],te[Mt],te[st],te[Wt]),w=et,y=Mt,b=st,E=Wt),(Ft.equals(S)===!1||Ki!==A)&&(o.blendColor(Ft.r,Ft.g,Ft.b,Ki),S.copy(Ft),A=Ki),v=U,_=!1}function se(U,ft){U.side===Tn?V(o.CULL_FACE):ct(o.CULL_FACE);let et=U.side===zi;ft&&(et=!et),ri(et),U.blending===Mc&&U.transparent===!1?ne(Ys):ne(U.blending,U.blendEquation,U.blendSrc,U.blendDst,U.blendEquationAlpha,U.blendSrcAlpha,U.blendDstAlpha,U.blendColor,U.blendAlpha,U.premultipliedAlpha),r.setFunc(U.depthFunc),r.setTest(U.depthTest),r.setMask(U.depthWrite),s.setMask(U.colorWrite);const Mt=U.stencilWrite;a.setTest(Mt),Mt&&(a.setMask(U.stencilWriteMask),a.setFunc(U.stencilFunc,U.stencilRef,U.stencilFuncMask),a.setOp(U.stencilFail,U.stencilZFail,U.stencilZPass)),Gi(U.polygonOffset,U.polygonOffsetFactor,U.polygonOffsetUnits),U.alphaToCoverage===!0?ct(o.SAMPLE_ALPHA_TO_COVERAGE):V(o.SAMPLE_ALPHA_TO_COVERAGE)}function ri(U){I!==U&&(U?o.frontFace(o.CW):o.frontFace(o.CCW),I=U)}function ai(U){U!==g4?(ct(o.CULL_FACE),U!==D&&(U===Mw?o.cullFace(o.BACK):U===v4?o.cullFace(o.FRONT):o.cullFace(o.FRONT_AND_BACK))):V(o.CULL_FACE),D=U}function $i(U){U!==O&&(B&&o.lineWidth(U),O=U)}function Gi(U,ft,et){U?(ct(o.POLYGON_OFFSET_FILL),(P!==ft||N!==et)&&(P=ft,N=et,r.getReversed()&&(ft=-ft),o.polygonOffset(ft,et))):V(o.POLYGON_OFFSET_FILL)}function Yi(U){U?ct(o.SCISSOR_TEST):V(o.SCISSOR_TEST)}function un(U){U===void 0&&(U=o.TEXTURE0+k-1),Z!==U&&(o.activeTexture(U),Z=U)}function z(U,ft,et){et===void 0&&(Z===null?et=o.TEXTURE0+k-1:et=Z);let Mt=nt[et];Mt===void 0&&(Mt={type:void 0,texture:void 0},nt[et]=Mt),(Mt.type!==U||Mt.texture!==ft)&&(Z!==et&&(o.activeTexture(et),Z=et),o.bindTexture(U,ft||lt[U]),Mt.type=U,Mt.texture=ft)}function Os(){const U=nt[Z];U!==void 0&&U.type!==void 0&&(o.bindTexture(U.type,null),U.type=void 0,U.texture=void 0)}function oi(){try{o.compressedTexImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function L(){try{o.compressedTexImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function R(){try{o.texSubImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function G(){try{o.texSubImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function Y(){try{o.compressedTexSubImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function J(){try{o.compressedTexSubImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function ut(){try{o.texStorage2D(...arguments)}catch(U){le("WebGLState:",U)}}function pt(){try{o.texStorage3D(...arguments)}catch(U){le("WebGLState:",U)}}function j(){try{o.texImage2D(...arguments)}catch(U){le("WebGLState:",U)}}function it(){try{o.texImage3D(...arguments)}catch(U){le("WebGLState:",U)}}function gt(U){return u[U]!==void 0?u[U]:o.getParameter(U)}function $t(U,ft){u[U]!==ft&&(o.pixelStorei(U,ft),u[U]=ft)}function xt(U){Zt.equals(U)===!1&&(o.scissor(U.x,U.y,U.z,U.w),Zt.copy(U))}function vt(U){jt.equals(U)===!1&&(o.viewport(U.x,U.y,U.z,U.w),jt.copy(U))}function Qt(U,ft){let et=l.get(ft);et===void 0&&(et=new WeakMap,l.set(ft,et));let Mt=et.get(U);Mt===void 0&&(Mt=o.getUniformBlockIndex(ft,U.name),et.set(U,Mt))}function ae(U,ft){const Mt=l.get(ft).get(U);c.get(ft)!==Mt&&(o.uniformBlockBinding(ft,Mt,U.__bindingPointIndex),c.set(ft,Mt))}function Ae(){o.disable(o.BLEND),o.disable(o.CULL_FACE),o.disable(o.DEPTH_TEST),o.disable(o.POLYGON_OFFSET_FILL),o.disable(o.SCISSOR_TEST),o.disable(o.STENCIL_TEST),o.disable(o.SAMPLE_ALPHA_TO_COVERAGE),o.blendEquation(o.FUNC_ADD),o.blendFunc(o.ONE,o.ZERO),o.blendFuncSeparate(o.ONE,o.ZERO,o.ONE,o.ZERO),o.blendColor(0,0,0,0),o.colorMask(!0,!0,!0,!0),o.clearColor(0,0,0,0),o.depthMask(!0),o.depthFunc(o.LESS),r.setReversed(!1),o.clearDepth(1),o.stencilMask(4294967295),o.stencilFunc(o.ALWAYS,0,4294967295),o.stencilOp(o.KEEP,o.KEEP,o.KEEP),o.clearStencil(0),o.cullFace(o.BACK),o.frontFace(o.CCW),o.polygonOffset(0,0),o.activeTexture(o.TEXTURE0),o.bindFramebuffer(o.FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,null),o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.useProgram(null),o.lineWidth(1),o.scissor(0,0,o.canvas.width,o.canvas.height),o.viewport(0,0,o.canvas.width,o.canvas.height),o.pixelStorei(o.PACK_ALIGNMENT,4),o.pixelStorei(o.UNPACK_ALIGNMENT,4),o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!1),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),o.pixelStorei(o.UNPACK_COLORSPACE_CONVERSION_WEBGL,o.BROWSER_DEFAULT_WEBGL),o.pixelStorei(o.PACK_ROW_LENGTH,0),o.pixelStorei(o.PACK_SKIP_PIXELS,0),o.pixelStorei(o.PACK_SKIP_ROWS,0),o.pixelStorei(o.UNPACK_ROW_LENGTH,0),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,0),o.pixelStorei(o.UNPACK_SKIP_PIXELS,0),o.pixelStorei(o.UNPACK_SKIP_ROWS,0),o.pixelStorei(o.UNPACK_SKIP_IMAGES,0),h={},u={},Z=null,nt={},d={},f=new WeakMap,p=[],m=null,g=!1,v=null,M=null,w=null,y=null,x=null,b=null,E=null,S=new rt(0,0,0),A=0,_=!1,I=null,D=null,O=null,P=null,N=null,Zt.set(0,0,o.canvas.width,o.canvas.height),jt.set(0,0,o.canvas.width,o.canvas.height),s.reset(),r.reset(),a.reset()}return{buffers:{color:s,depth:r,stencil:a},enable:ct,disable:V,bindFramebuffer:Lt,drawBuffers:Xt,useProgram:kt,setBlending:ne,setMaterial:se,setFlipSided:ri,setCullFace:ai,setLineWidth:$i,setPolygonOffset:Gi,setScissorTest:Yi,activeTexture:un,bindTexture:z,unbindTexture:Os,compressedTexImage2D:oi,compressedTexImage3D:L,texImage2D:j,texImage3D:it,pixelStorei:$t,getParameter:gt,updateUBOMapping:Qt,uniformBlockBinding:ae,texStorage2D:ut,texStorage3D:pt,texSubImage2D:R,texSubImage3D:G,compressedTexSubImage2D:Y,compressedTexSubImage3D:J,scissor:xt,viewport:vt,reset:Ae}}function $P(o,t,e,i,n,s,r){const a=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new tt,h=new WeakMap,u=new Set;let d;const f=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(L,R){return p?new OffscreenCanvas(L,R):hf("canvas")}function g(L,R,G){let Y=1;const J=oi(L);if((J.width>G||J.height>G)&&(Y=G/Math.max(J.width,J.height)),Y<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){const ut=Math.floor(Y*J.width),pt=Math.floor(Y*J.height);d===void 0&&(d=m(ut,pt));const j=R?m(ut,pt):d;return j.width=ut,j.height=pt,j.getContext("2d").drawImage(L,0,0,ut,pt),Ht("WebGLRenderer: Texture has been resized from ("+J.width+"x"+J.height+") to ("+ut+"x"+pt+")."),j}else return"data"in L&&Ht("WebGLRenderer: Image in DataTexture is too big ("+J.width+"x"+J.height+")."),L;return L}function v(L){return L.generateMipmaps}function M(L){o.generateMipmap(L)}function w(L){return L.isWebGLCubeRenderTarget?o.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?o.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?o.TEXTURE_2D_ARRAY:o.TEXTURE_2D}function y(L,R,G,Y,J,ut=!1){if(L!==null){if(o[L]!==void 0)return o[L];Ht("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let pt;Y&&(pt=t.get("EXT_texture_norm16"),pt||Ht("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let j=R;if(R===o.RED&&(G===o.FLOAT&&(j=o.R32F),G===o.HALF_FLOAT&&(j=o.R16F),G===o.UNSIGNED_BYTE&&(j=o.R8),G===o.UNSIGNED_SHORT&&pt&&(j=pt.R16_EXT),G===o.SHORT&&pt&&(j=pt.R16_SNORM_EXT)),R===o.RED_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.R8UI),G===o.UNSIGNED_SHORT&&(j=o.R16UI),G===o.UNSIGNED_INT&&(j=o.R32UI),G===o.BYTE&&(j=o.R8I),G===o.SHORT&&(j=o.R16I),G===o.INT&&(j=o.R32I)),R===o.RG&&(G===o.FLOAT&&(j=o.RG32F),G===o.HALF_FLOAT&&(j=o.RG16F),G===o.UNSIGNED_BYTE&&(j=o.RG8),G===o.UNSIGNED_SHORT&&pt&&(j=pt.RG16_EXT),G===o.SHORT&&pt&&(j=pt.RG16_SNORM_EXT)),R===o.RG_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.RG8UI),G===o.UNSIGNED_SHORT&&(j=o.RG16UI),G===o.UNSIGNED_INT&&(j=o.RG32UI),G===o.BYTE&&(j=o.RG8I),G===o.SHORT&&(j=o.RG16I),G===o.INT&&(j=o.RG32I)),R===o.RGB_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.RGB8UI),G===o.UNSIGNED_SHORT&&(j=o.RGB16UI),G===o.UNSIGNED_INT&&(j=o.RGB32UI),G===o.BYTE&&(j=o.RGB8I),G===o.SHORT&&(j=o.RGB16I),G===o.INT&&(j=o.RGB32I)),R===o.RGBA_INTEGER&&(G===o.UNSIGNED_BYTE&&(j=o.RGBA8UI),G===o.UNSIGNED_SHORT&&(j=o.RGBA16UI),G===o.UNSIGNED_INT&&(j=o.RGBA32UI),G===o.BYTE&&(j=o.RGBA8I),G===o.SHORT&&(j=o.RGBA16I),G===o.INT&&(j=o.RGBA32I)),R===o.RGB&&(G===o.UNSIGNED_SHORT&&pt&&(j=pt.RGB16_EXT),G===o.SHORT&&pt&&(j=pt.RGB16_SNORM_EXT),G===o.UNSIGNED_INT_5_9_9_9_REV&&(j=o.RGB9_E5),G===o.UNSIGNED_INT_10F_11F_11F_REV&&(j=o.R11F_G11F_B10F)),R===o.RGBA){const it=ut?V0:He.getTransfer(J);G===o.FLOAT&&(j=o.RGBA32F),G===o.HALF_FLOAT&&(j=o.RGBA16F),G===o.UNSIGNED_BYTE&&(j=it===ui?o.SRGB8_ALPHA8:o.RGBA8),G===o.UNSIGNED_SHORT&&pt&&(j=pt.RGBA16_EXT),G===o.SHORT&&pt&&(j=pt.RGBA16_SNORM_EXT),G===o.UNSIGNED_SHORT_4_4_4_4&&(j=o.RGBA4),G===o.UNSIGNED_SHORT_5_5_5_1&&(j=o.RGB5_A1)}return(j===o.R16F||j===o.R32F||j===o.RG16F||j===o.RG32F||j===o.RGBA16F||j===o.RGBA32F)&&t.get("EXT_color_buffer_float"),j}function x(L,R){let G;return L?R===null||R===_r||R===cf?G=o.DEPTH24_STENCIL8:R===ts?G=o.DEPTH32F_STENCIL8:R===of&&(G=o.DEPTH24_STENCIL8,Ht("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):R===null||R===_r||R===cf?G=o.DEPTH_COMPONENT24:R===ts?G=o.DEPTH_COMPONENT32F:R===of&&(G=o.DEPTH_COMPONENT16),G}function b(L,R){return v(L)===!0||L.isFramebufferTexture&&L.minFilter!==si&&L.minFilter!==Me?Math.log2(Math.max(R.width,R.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?R.mipmaps.length:1}function E(L){const R=L.target;R.removeEventListener("dispose",E),A(R),R.isVideoTexture&&h.delete(R),R.isHTMLTexture&&u.delete(R)}function S(L){const R=L.target;R.removeEventListener("dispose",S),I(R)}function A(L){const R=i.get(L);if(R.__webglInit===void 0)return;const G=L.source,Y=f.get(G);if(Y){const J=Y[R.__cacheKey];J.usedTimes--,J.usedTimes===0&&_(L),Object.keys(Y).length===0&&f.delete(G)}i.remove(L)}function _(L){const R=i.get(L);o.deleteTexture(R.__webglTexture);const G=L.source,Y=f.get(G);delete Y[R.__cacheKey],r.memory.textures--}function I(L){const R=i.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),i.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let Y=0;Y<6;Y++){if(Array.isArray(R.__webglFramebuffer[Y]))for(let J=0;J<R.__webglFramebuffer[Y].length;J++)o.deleteFramebuffer(R.__webglFramebuffer[Y][J]);else o.deleteFramebuffer(R.__webglFramebuffer[Y]);R.__webglDepthbuffer&&o.deleteRenderbuffer(R.__webglDepthbuffer[Y])}else{if(Array.isArray(R.__webglFramebuffer))for(let Y=0;Y<R.__webglFramebuffer.length;Y++)o.deleteFramebuffer(R.__webglFramebuffer[Y]);else o.deleteFramebuffer(R.__webglFramebuffer);if(R.__webglDepthbuffer&&o.deleteRenderbuffer(R.__webglDepthbuffer),R.__webglMultisampledFramebuffer&&o.deleteFramebuffer(R.__webglMultisampledFramebuffer),R.__webglColorRenderbuffer)for(let Y=0;Y<R.__webglColorRenderbuffer.length;Y++)R.__webglColorRenderbuffer[Y]&&o.deleteRenderbuffer(R.__webglColorRenderbuffer[Y]);R.__webglDepthRenderbuffer&&o.deleteRenderbuffer(R.__webglDepthRenderbuffer)}const G=L.textures;for(let Y=0,J=G.length;Y<J;Y++){const ut=i.get(G[Y]);ut.__webglTexture&&(o.deleteTexture(ut.__webglTexture),r.memory.textures--),i.remove(G[Y])}i.remove(L)}let D=0;function O(){D=0}function P(){return D}function N(L){D=L}function k(){const L=D;return L>=n.maxTextures&&Ht("WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+n.maxTextures),D+=1,L}function B(L){const R=[];return R.push(L.wrapS),R.push(L.wrapT),R.push(L.wrapR||0),R.push(L.magFilter),R.push(L.minFilter),R.push(L.anisotropy),R.push(L.internalFormat),R.push(L.format),R.push(L.type),R.push(L.generateMipmaps),R.push(L.premultiplyAlpha),R.push(L.flipY),R.push(L.unpackAlignment),R.push(L.colorSpace),R.join()}function W(L,R){const G=i.get(L);if(L.isVideoTexture&&z(L),L.isRenderTargetTexture===!1&&L.isExternalTexture!==!0&&L.version>0&&G.__version!==L.version){const Y=L.image;if(Y===null)Ht("WebGLRenderer: Texture marked for update but no image data found.");else if(Y.complete===!1)Ht("WebGLRenderer: Texture marked for update but image is incomplete");else{V(G,L,R);return}}else L.isExternalTexture&&(G.__webglTexture=L.sourceTexture?L.sourceTexture:null);e.bindTexture(o.TEXTURE_2D,G.__webglTexture,o.TEXTURE0+R)}function Q(L,R){const G=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&G.__version!==L.version){V(G,L,R);return}else L.isExternalTexture&&(G.__webglTexture=L.sourceTexture?L.sourceTexture:null);e.bindTexture(o.TEXTURE_2D_ARRAY,G.__webglTexture,o.TEXTURE0+R)}function Z(L,R){const G=i.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&G.__version!==L.version){V(G,L,R);return}e.bindTexture(o.TEXTURE_3D,G.__webglTexture,o.TEXTURE0+R)}function nt(L,R){const G=i.get(L);if(L.isCubeDepthTexture!==!0&&L.version>0&&G.__version!==L.version){Lt(G,L,R);return}e.bindTexture(o.TEXTURE_CUBE_MAP,G.__webglTexture,o.TEXTURE0+R)}const ot={[bc]:o.REPEAT,[Qi]:o.CLAMP_TO_EDGE,[wv]:o.MIRRORED_REPEAT},Ut={[si]:o.NEAREST,[F4]:o.NEAREST_MIPMAP_NEAREST,[zf]:o.NEAREST_MIPMAP_LINEAR,[Me]:o.LINEAR,[cg]:o.LINEAR_MIPMAP_NEAREST,[cr]:o.LINEAR_MIPMAP_LINEAR},Zt={[V4]:o.NEVER,[K4]:o.ALWAYS,[W4]:o.LESS,[py]:o.LEQUAL,[X4]:o.EQUAL,[my]:o.GEQUAL,[$4]:o.GREATER,[Y4]:o.NOTEQUAL};function jt(L,R){if(R.type===ts&&t.has("OES_texture_float_linear")===!1&&(R.magFilter===Me||R.magFilter===cg||R.magFilter===zf||R.magFilter===cr||R.minFilter===Me||R.minFilter===cg||R.minFilter===zf||R.minFilter===cr)&&Ht("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),o.texParameteri(L,o.TEXTURE_WRAP_S,ot[R.wrapS]),o.texParameteri(L,o.TEXTURE_WRAP_T,ot[R.wrapT]),(L===o.TEXTURE_3D||L===o.TEXTURE_2D_ARRAY)&&o.texParameteri(L,o.TEXTURE_WRAP_R,ot[R.wrapR]),o.texParameteri(L,o.TEXTURE_MAG_FILTER,Ut[R.magFilter]),o.texParameteri(L,o.TEXTURE_MIN_FILTER,Ut[R.minFilter]),R.compareFunction&&(o.texParameteri(L,o.TEXTURE_COMPARE_MODE,o.COMPARE_REF_TO_TEXTURE),o.texParameteri(L,o.TEXTURE_COMPARE_FUNC,Zt[R.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(R.magFilter===si||R.minFilter!==zf&&R.minFilter!==cr||R.type===ts&&t.has("OES_texture_float_linear")===!1)return;if(R.anisotropy>1||i.get(R).__currentAnisotropy){const G=t.get("EXT_texture_filter_anisotropic");o.texParameterf(L,G.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,n.getMaxAnisotropy())),i.get(R).__currentAnisotropy=R.anisotropy}}}function K(L,R){let G=!1;L.__webglInit===void 0&&(L.__webglInit=!0,R.addEventListener("dispose",E));const Y=R.source;let J=f.get(Y);J===void 0&&(J={},f.set(Y,J));const ut=B(R);if(ut!==L.__cacheKey){J[ut]===void 0&&(J[ut]={texture:o.createTexture(),usedTimes:0},r.memory.textures++,G=!0),J[ut].usedTimes++;const pt=J[L.__cacheKey];pt!==void 0&&(J[L.__cacheKey].usedTimes--,pt.usedTimes===0&&_(R)),L.__cacheKey=ut,L.__webglTexture=J[ut].texture}return G}function lt(L,R,G){return Math.floor(Math.floor(L/G)/R)}function ct(L,R,G,Y){const ut=L.updateRanges;if(ut.length===0)e.texSubImage2D(o.TEXTURE_2D,0,0,0,R.width,R.height,G,Y,R.data);else{ut.sort(($t,xt)=>$t.start-xt.start);let pt=0;for(let $t=1;$t<ut.length;$t++){const xt=ut[pt],vt=ut[$t],Qt=xt.start+xt.count,ae=lt(vt.start,R.width,4),Ae=lt(xt.start,R.width,4);vt.start<=Qt+1&&ae===Ae&<(vt.start+vt.count-1,R.width,4)===ae?xt.count=Math.max(xt.count,vt.start+vt.count-xt.start):(++pt,ut[pt]=vt)}ut.length=pt+1;const j=e.getParameter(o.UNPACK_ROW_LENGTH),it=e.getParameter(o.UNPACK_SKIP_PIXELS),gt=e.getParameter(o.UNPACK_SKIP_ROWS);e.pixelStorei(o.UNPACK_ROW_LENGTH,R.width);for(let $t=0,xt=ut.length;$t<xt;$t++){const vt=ut[$t],Qt=Math.floor(vt.start/4),ae=Math.ceil(vt.count/4),Ae=Qt%R.width,U=Math.floor(Qt/R.width),ft=ae,et=1;e.pixelStorei(o.UNPACK_SKIP_PIXELS,Ae),e.pixelStorei(o.UNPACK_SKIP_ROWS,U),e.texSubImage2D(o.TEXTURE_2D,0,Ae,U,ft,et,G,Y,R.data)}L.clearUpdateRanges(),e.pixelStorei(o.UNPACK_ROW_LENGTH,j),e.pixelStorei(o.UNPACK_SKIP_PIXELS,it),e.pixelStorei(o.UNPACK_SKIP_ROWS,gt)}}function V(L,R,G){let Y=o.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(Y=o.TEXTURE_2D_ARRAY),R.isData3DTexture&&(Y=o.TEXTURE_3D);const J=K(L,R),ut=R.source;e.bindTexture(Y,L.__webglTexture,o.TEXTURE0+G);const pt=i.get(ut);if(ut.version!==pt.__version||J===!0){if(e.activeTexture(o.TEXTURE0+G),(typeof ImageBitmap<"u"&&R.image instanceof ImageBitmap)===!1){const et=He.getPrimaries(He.workingColorSpace),Mt=R.colorSpace===tc?null:He.getPrimaries(R.colorSpace),At=R.colorSpace===tc||et===Mt?o.NONE:o.BROWSER_DEFAULT_WEBGL;e.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,R.flipY),e.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),e.pixelStorei(o.UNPACK_COLORSPACE_CONVERSION_WEBGL,At)}e.pixelStorei(o.UNPACK_ALIGNMENT,R.unpackAlignment);let it=g(R.image,!1,n.maxTextureSize);it=Os(R,it);const gt=s.convert(R.format,R.colorSpace),$t=s.convert(R.type);let xt=y(R.internalFormat,gt,$t,R.normalized,R.colorSpace,R.isVideoTexture);jt(Y,R);let vt;const Qt=R.mipmaps,ae=R.isVideoTexture!==!0,Ae=pt.__version===void 0||J===!0,U=ut.dataReady,ft=b(R,it);if(R.isDepthTexture)xt=x(R.format===tl,R.type),Ae&&(ae?e.texStorage2D(o.TEXTURE_2D,1,xt,it.width,it.height):e.texImage2D(o.TEXTURE_2D,0,xt,it.width,it.height,0,gt,$t,null));else if(R.isDataTexture)if(Qt.length>0){ae&&Ae&&e.texStorage2D(o.TEXTURE_2D,ft,xt,Qt[0].width,Qt[0].height);for(let et=0,Mt=Qt.length;et<Mt;et++)vt=Qt[et],ae?U&&e.texSubImage2D(o.TEXTURE_2D,et,0,0,vt.width,vt.height,gt,$t,vt.data):e.texImage2D(o.TEXTURE_2D,et,xt,vt.width,vt.height,0,gt,$t,vt.data);R.generateMipmaps=!1}else ae?(Ae&&e.texStorage2D(o.TEXTURE_2D,ft,xt,it.width,it.height),U&&ct(R,it,gt,$t)):e.texImage2D(o.TEXTURE_2D,0,xt,it.width,it.height,0,gt,$t,it.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){ae&&Ae&&e.texStorage3D(o.TEXTURE_2D_ARRAY,ft,xt,Qt[0].width,Qt[0].height,it.depth);for(let et=0,Mt=Qt.length;et<Mt;et++)if(vt=Qt[et],R.format!==tn)if(gt!==null)if(ae){if(U)if(R.layerUpdates.size>0){const At=bx(vt.width,vt.height,R.format,R.type);for(const st of R.layerUpdates){const Wt=vt.data.subarray(st*At/vt.data.BYTES_PER_ELEMENT,(st+1)*At/vt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(o.TEXTURE_2D_ARRAY,et,0,0,st,vt.width,vt.height,1,gt,Wt)}R.clearLayerUpdates()}else e.compressedTexSubImage3D(o.TEXTURE_2D_ARRAY,et,0,0,0,vt.width,vt.height,it.depth,gt,vt.data)}else e.compressedTexImage3D(o.TEXTURE_2D_ARRAY,et,xt,vt.width,vt.height,it.depth,0,vt.data,0,0);else Ht("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else ae?U&&e.texSubImage3D(o.TEXTURE_2D_ARRAY,et,0,0,0,vt.width,vt.height,it.depth,gt,$t,vt.data):e.texImage3D(o.TEXTURE_2D_ARRAY,et,xt,vt.width,vt.height,it.depth,0,gt,$t,vt.data)}else{ae&&Ae&&e.texStorage2D(o.TEXTURE_2D,ft,xt,Qt[0].width,Qt[0].height);for(let et=0,Mt=Qt.length;et<Mt;et++)vt=Qt[et],R.format!==tn?gt!==null?ae?U&&e.compressedTexSubImage2D(o.TEXTURE_2D,et,0,0,vt.width,vt.height,gt,vt.data):e.compressedTexImage2D(o.TEXTURE_2D,et,xt,vt.width,vt.height,0,vt.data):Ht("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):ae?U&&e.texSubImage2D(o.TEXTURE_2D,et,0,0,vt.width,vt.height,gt,$t,vt.data):e.texImage2D(o.TEXTURE_2D,et,xt,vt.width,vt.height,0,gt,$t,vt.data)}else if(R.isDataArrayTexture)if(ae){if(Ae&&e.texStorage3D(o.TEXTURE_2D_ARRAY,ft,xt,it.width,it.height,it.depth),U)if(R.layerUpdates.size>0){const et=bx(it.width,it.height,R.format,R.type);for(const Mt of R.layerUpdates){const At=it.data.subarray(Mt*et/it.data.BYTES_PER_ELEMENT,(Mt+1)*et/it.data.BYTES_PER_ELEMENT);e.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,Mt,it.width,it.height,1,gt,$t,At)}R.clearLayerUpdates()}else e.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,0,it.width,it.height,it.depth,gt,$t,it.data)}else e.texImage3D(o.TEXTURE_2D_ARRAY,0,xt,it.width,it.height,it.depth,0,gt,$t,it.data);else if(R.isData3DTexture)ae?(Ae&&e.texStorage3D(o.TEXTURE_3D,ft,xt,it.width,it.height,it.depth),U&&e.texSubImage3D(o.TEXTURE_3D,0,0,0,0,it.width,it.height,it.depth,gt,$t,it.data)):e.texImage3D(o.TEXTURE_3D,0,xt,it.width,it.height,it.depth,0,gt,$t,it.data);else if(R.isFramebufferTexture){if(Ae)if(ae)e.texStorage2D(o.TEXTURE_2D,ft,xt,it.width,it.height);else{let et=it.width,Mt=it.height;for(let At=0;At<ft;At++)e.texImage2D(o.TEXTURE_2D,At,xt,et,Mt,0,gt,$t,null),et>>=1,Mt>>=1}}else if(R.isHTMLTexture){if("texElementImage2D"in o){const et=o.canvas;if(et.hasAttribute("layoutsubtree")||et.setAttribute("layoutsubtree","true"),it.parentNode!==et){et.appendChild(it),u.add(R),et.onpaint=Mt=>{const At=Mt.changedElements;for(const st of u)At.includes(st.image)&&(st.needsUpdate=!0)},et.requestPaint();return}if(o.texElementImage2D.length===3)o.texElementImage2D(o.TEXTURE_2D,o.RGBA8,it);else{const At=o.RGBA,st=o.RGBA,Wt=o.UNSIGNED_BYTE;o.texElementImage2D(o.TEXTURE_2D,0,At,st,Wt,it)}o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE)}}else if(Qt.length>0){if(ae&&Ae){const et=oi(Qt[0]);e.texStorage2D(o.TEXTURE_2D,ft,xt,et.width,et.height)}for(let et=0,Mt=Qt.length;et<Mt;et++)vt=Qt[et],ae?U&&e.texSubImage2D(o.TEXTURE_2D,et,0,0,gt,$t,vt):e.texImage2D(o.TEXTURE_2D,et,xt,gt,$t,vt);R.generateMipmaps=!1}else if(ae){if(Ae){const et=oi(it);e.texStorage2D(o.TEXTURE_2D,ft,xt,et.width,et.height)}U&&e.texSubImage2D(o.TEXTURE_2D,0,0,0,gt,$t,it)}else e.texImage2D(o.TEXTURE_2D,0,xt,gt,$t,it);v(R)&&M(Y),pt.__version=ut.version,R.onUpdate&&R.onUpdate(R)}L.__version=R.version}function Lt(L,R,G){if(R.image.length!==6)return;const Y=K(L,R),J=R.source;e.bindTexture(o.TEXTURE_CUBE_MAP,L.__webglTexture,o.TEXTURE0+G);const ut=i.get(J);if(J.version!==ut.__version||Y===!0){e.activeTexture(o.TEXTURE0+G);const pt=He.getPrimaries(He.workingColorSpace),j=R.colorSpace===tc?null:He.getPrimaries(R.colorSpace),it=R.colorSpace===tc||pt===j?o.NONE:o.BROWSER_DEFAULT_WEBGL;e.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,R.flipY),e.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),e.pixelStorei(o.UNPACK_ALIGNMENT,R.unpackAlignment),e.pixelStorei(o.UNPACK_COLORSPACE_CONVERSION_WEBGL,it);const gt=R.isCompressedTexture||R.image[0].isCompressedTexture,$t=R.image[0]&&R.image[0].isDataTexture,xt=[];for(let st=0;st<6;st++)!gt&&!$t?xt[st]=g(R.image[st],!0,n.maxCubemapSize):xt[st]=$t?R.image[st].image:R.image[st],xt[st]=Os(R,xt[st]);const vt=xt[0],Qt=s.convert(R.format,R.colorSpace),ae=s.convert(R.type),Ae=y(R.internalFormat,Qt,ae,R.normalized,R.colorSpace),U=R.isVideoTexture!==!0,ft=ut.__version===void 0||Y===!0,et=J.dataReady;let Mt=b(R,vt);jt(o.TEXTURE_CUBE_MAP,R);let At;if(gt){U&&ft&&e.texStorage2D(o.TEXTURE_CUBE_MAP,Mt,Ae,vt.width,vt.height);for(let st=0;st<6;st++){At=xt[st].mipmaps;for(let Wt=0;Wt<At.length;Wt++){const Ft=At[Wt];R.format!==tn?Qt!==null?U?et&&e.compressedTexSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,0,0,Ft.width,Ft.height,Qt,Ft.data):e.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,Ae,Ft.width,Ft.height,0,Ft.data):Ht("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,0,0,Ft.width,Ft.height,Qt,ae,Ft.data):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt,Ae,Ft.width,Ft.height,0,Qt,ae,Ft.data)}}}else{if(At=R.mipmaps,U&&ft){At.length>0&&Mt++;const st=oi(xt[0]);e.texStorage2D(o.TEXTURE_CUBE_MAP,Mt,Ae,st.width,st.height)}for(let st=0;st<6;st++)if($t){U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,0,0,xt[st].width,xt[st].height,Qt,ae,xt[st].data):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,Ae,xt[st].width,xt[st].height,0,Qt,ae,xt[st].data);for(let Wt=0;Wt<At.length;Wt++){const Ki=At[Wt].image[st].image;U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,0,0,Ki.width,Ki.height,Qt,ae,Ki.data):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,Ae,Ki.width,Ki.height,0,Qt,ae,Ki.data)}}else{U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,0,0,Qt,ae,xt[st]):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,0,Ae,Qt,ae,xt[st]);for(let Wt=0;Wt<At.length;Wt++){const Ft=At[Wt];U?et&&e.texSubImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,0,0,Qt,ae,Ft.image[st]):e.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+st,Wt+1,Ae,Qt,ae,Ft.image[st])}}}v(R)&&M(o.TEXTURE_CUBE_MAP),ut.__version=J.version,R.onUpdate&&R.onUpdate(R)}L.__version=R.version}function Xt(L,R,G,Y,J,ut){const pt=s.convert(G.format,G.colorSpace),j=s.convert(G.type),it=y(G.internalFormat,pt,j,G.normalized,G.colorSpace),gt=i.get(R),$t=i.get(G);if($t.__renderTarget=R,!gt.__hasExternalTextures){const xt=Math.max(1,R.width>>ut),vt=Math.max(1,R.height>>ut);J===o.TEXTURE_3D||J===o.TEXTURE_2D_ARRAY?e.texImage3D(J,ut,it,xt,vt,R.depth,0,pt,j,null):e.texImage2D(J,ut,it,xt,vt,0,pt,j,null)}e.bindFramebuffer(o.FRAMEBUFFER,L),un(R)?a.framebufferTexture2DMultisampleEXT(o.FRAMEBUFFER,Y,J,$t.__webglTexture,0,Yi(R)):(J===o.TEXTURE_2D||J>=o.TEXTURE_CUBE_MAP_POSITIVE_X&&J<=o.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&o.framebufferTexture2D(o.FRAMEBUFFER,Y,J,$t.__webglTexture,ut),e.bindFramebuffer(o.FRAMEBUFFER,null)}function kt(L,R,G){if(o.bindRenderbuffer(o.RENDERBUFFER,L),R.depthBuffer){const Y=R.depthTexture,J=Y&&Y.isDepthTexture?Y.type:null,ut=x(R.stencilBuffer,J),pt=R.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT;un(R)?a.renderbufferStorageMultisampleEXT(o.RENDERBUFFER,Yi(R),ut,R.width,R.height):G?o.renderbufferStorageMultisample(o.RENDERBUFFER,Yi(R),ut,R.width,R.height):o.renderbufferStorage(o.RENDERBUFFER,ut,R.width,R.height),o.framebufferRenderbuffer(o.FRAMEBUFFER,pt,o.RENDERBUFFER,L)}else{const Y=R.textures;for(let J=0;J<Y.length;J++){const ut=Y[J],pt=s.convert(ut.format,ut.colorSpace),j=s.convert(ut.type),it=y(ut.internalFormat,pt,j,ut.normalized,ut.colorSpace);un(R)?a.renderbufferStorageMultisampleEXT(o.RENDERBUFFER,Yi(R),it,R.width,R.height):G?o.renderbufferStorageMultisample(o.RENDERBUFFER,Yi(R),it,R.width,R.height):o.renderbufferStorage(o.RENDERBUFFER,it,R.width,R.height)}}o.bindRenderbuffer(o.RENDERBUFFER,null)}function Rt(L,R,G){const Y=R.isWebGLCubeRenderTarget===!0;if(e.bindFramebuffer(o.FRAMEBUFFER,L),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const J=i.get(R.depthTexture);if(J.__renderTarget=R,(!J.__webglTexture||R.depthTexture.image.width!==R.width||R.depthTexture.image.height!==R.height)&&(R.depthTexture.image.width=R.width,R.depthTexture.image.height=R.height,R.depthTexture.needsUpdate=!0),Y){if(J.__webglInit===void 0&&(J.__webglInit=!0,R.depthTexture.addEventListener("dispose",E)),J.__webglTexture===void 0){J.__webglTexture=o.createTexture(),e.bindTexture(o.TEXTURE_CUBE_MAP,J.__webglTexture),jt(o.TEXTURE_CUBE_MAP,R.depthTexture);const gt=s.convert(R.depthTexture.format),$t=s.convert(R.depthTexture.type);let xt;R.depthTexture.format===So?xt=o.DEPTH_COMPONENT24:R.depthTexture.format===tl&&(xt=o.DEPTH24_STENCIL8);for(let vt=0;vt<6;vt++)o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+vt,0,xt,R.width,R.height,0,gt,$t,null)}}else W(R.depthTexture,0);const ut=J.__webglTexture,pt=Yi(R),j=Y?o.TEXTURE_CUBE_MAP_POSITIVE_X+G:o.TEXTURE_2D,it=R.depthTexture.format===tl?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT;if(R.depthTexture.format===So)un(R)?a.framebufferTexture2DMultisampleEXT(o.FRAMEBUFFER,it,j,ut,0,pt):o.framebufferTexture2D(o.FRAMEBUFFER,it,j,ut,0);else if(R.depthTexture.format===tl)un(R)?a.framebufferTexture2DMultisampleEXT(o.FRAMEBUFFER,it,j,ut,0,pt):o.framebufferTexture2D(o.FRAMEBUFFER,it,j,ut,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function te(L){const R=i.get(L),G=L.isWebGLCubeRenderTarget===!0;if(R.__boundDepthTexture!==L.depthTexture){const Y=L.depthTexture;if(R.__depthDisposeCallback&&R.__depthDisposeCallback(),Y){const J=()=>{delete R.__boundDepthTexture,delete R.__depthDisposeCallback,Y.removeEventListener("dispose",J)};Y.addEventListener("dispose",J),R.__depthDisposeCallback=J}R.__boundDepthTexture=Y}if(L.depthTexture&&!R.__autoAllocateDepthBuffer)if(G)for(let Y=0;Y<6;Y++)Rt(R.__webglFramebuffer[Y],L,Y);else{const Y=L.texture.mipmaps;Y&&Y.length>0?Rt(R.__webglFramebuffer[0],L,0):Rt(R.__webglFramebuffer,L,0)}else if(G){R.__webglDepthbuffer=[];for(let Y=0;Y<6;Y++)if(e.bindFramebuffer(o.FRAMEBUFFER,R.__webglFramebuffer[Y]),R.__webglDepthbuffer[Y]===void 0)R.__webglDepthbuffer[Y]=o.createRenderbuffer(),kt(R.__webglDepthbuffer[Y],L,!1);else{const J=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT,ut=R.__webglDepthbuffer[Y];o.bindRenderbuffer(o.RENDERBUFFER,ut),o.framebufferRenderbuffer(o.FRAMEBUFFER,J,o.RENDERBUFFER,ut)}}else{const Y=L.texture.mipmaps;if(Y&&Y.length>0?e.bindFramebuffer(o.FRAMEBUFFER,R.__webglFramebuffer[0]):e.bindFramebuffer(o.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer===void 0)R.__webglDepthbuffer=o.createRenderbuffer(),kt(R.__webglDepthbuffer,L,!1);else{const J=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT,ut=R.__webglDepthbuffer;o.bindRenderbuffer(o.RENDERBUFFER,ut),o.framebufferRenderbuffer(o.FRAMEBUFFER,J,o.RENDERBUFFER,ut)}}e.bindFramebuffer(o.FRAMEBUFFER,null)}function ne(L,R,G){const Y=i.get(L);R!==void 0&&Xt(Y.__webglFramebuffer,L,L.texture,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,0),G!==void 0&&te(L)}function se(L){const R=L.texture,G=i.get(L),Y=i.get(R);L.addEventListener("dispose",S);const J=L.textures,ut=L.isWebGLCubeRenderTarget===!0,pt=J.length>1;if(pt||(Y.__webglTexture===void 0&&(Y.__webglTexture=o.createTexture()),Y.__version=R.version,r.memory.textures++),ut){G.__webglFramebuffer=[];for(let j=0;j<6;j++)if(R.mipmaps&&R.mipmaps.length>0){G.__webglFramebuffer[j]=[];for(let it=0;it<R.mipmaps.length;it++)G.__webglFramebuffer[j][it]=o.createFramebuffer()}else G.__webglFramebuffer[j]=o.createFramebuffer()}else{if(R.mipmaps&&R.mipmaps.length>0){G.__webglFramebuffer=[];for(let j=0;j<R.mipmaps.length;j++)G.__webglFramebuffer[j]=o.createFramebuffer()}else G.__webglFramebuffer=o.createFramebuffer();if(pt)for(let j=0,it=J.length;j<it;j++){const gt=i.get(J[j]);gt.__webglTexture===void 0&&(gt.__webglTexture=o.createTexture(),r.memory.textures++)}if(L.samples>0&&un(L)===!1){G.__webglMultisampledFramebuffer=o.createFramebuffer(),G.__webglColorRenderbuffer=[],e.bindFramebuffer(o.FRAMEBUFFER,G.__webglMultisampledFramebuffer);for(let j=0;j<J.length;j++){const it=J[j];G.__webglColorRenderbuffer[j]=o.createRenderbuffer(),o.bindRenderbuffer(o.RENDERBUFFER,G.__webglColorRenderbuffer[j]);const gt=s.convert(it.format,it.colorSpace),$t=s.convert(it.type),xt=y(it.internalFormat,gt,$t,it.normalized,it.colorSpace,L.isXRRenderTarget===!0),vt=Yi(L);o.renderbufferStorageMultisample(o.RENDERBUFFER,vt,xt,L.width,L.height),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+j,o.RENDERBUFFER,G.__webglColorRenderbuffer[j])}o.bindRenderbuffer(o.RENDERBUFFER,null),L.depthBuffer&&(G.__webglDepthRenderbuffer=o.createRenderbuffer(),kt(G.__webglDepthRenderbuffer,L,!0)),e.bindFramebuffer(o.FRAMEBUFFER,null)}}if(ut){e.bindTexture(o.TEXTURE_CUBE_MAP,Y.__webglTexture),jt(o.TEXTURE_CUBE_MAP,R);for(let j=0;j<6;j++)if(R.mipmaps&&R.mipmaps.length>0)for(let it=0;it<R.mipmaps.length;it++)Xt(G.__webglFramebuffer[j][it],L,R,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+j,it);else Xt(G.__webglFramebuffer[j],L,R,o.COLOR_ATTACHMENT0,o.TEXTURE_CUBE_MAP_POSITIVE_X+j,0);v(R)&&M(o.TEXTURE_CUBE_MAP),e.unbindTexture()}else if(pt){for(let j=0,it=J.length;j<it;j++){const gt=J[j],$t=i.get(gt);let xt=o.TEXTURE_2D;(L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(xt=L.isWebGL3DRenderTarget?o.TEXTURE_3D:o.TEXTURE_2D_ARRAY),e.bindTexture(xt,$t.__webglTexture),jt(xt,gt),Xt(G.__webglFramebuffer,L,gt,o.COLOR_ATTACHMENT0+j,xt,0),v(gt)&&M(xt)}e.unbindTexture()}else{let j=o.TEXTURE_2D;if((L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(j=L.isWebGL3DRenderTarget?o.TEXTURE_3D:o.TEXTURE_2D_ARRAY),e.bindTexture(j,Y.__webglTexture),jt(j,R),R.mipmaps&&R.mipmaps.length>0)for(let it=0;it<R.mipmaps.length;it++)Xt(G.__webglFramebuffer[it],L,R,o.COLOR_ATTACHMENT0,j,it);else Xt(G.__webglFramebuffer,L,R,o.COLOR_ATTACHMENT0,j,0);v(R)&&M(j),e.unbindTexture()}L.depthBuffer&&te(L)}function ri(L){const R=L.textures;for(let G=0,Y=R.length;G<Y;G++){const J=R[G];if(v(J)){const ut=w(L),pt=i.get(J).__webglTexture;e.bindTexture(ut,pt),M(ut),e.unbindTexture()}}}const ai=[],$i=[];function Gi(L){if(L.samples>0){if(un(L)===!1){const R=L.textures,G=L.width,Y=L.height;let J=o.COLOR_BUFFER_BIT;const ut=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT,pt=i.get(L),j=R.length>1;if(j)for(let gt=0;gt<R.length;gt++)e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglMultisampledFramebuffer),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.RENDERBUFFER,null),e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglFramebuffer),o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.TEXTURE_2D,null,0);e.bindFramebuffer(o.READ_FRAMEBUFFER,pt.__webglMultisampledFramebuffer);const it=L.texture.mipmaps;it&&it.length>0?e.bindFramebuffer(o.DRAW_FRAMEBUFFER,pt.__webglFramebuffer[0]):e.bindFramebuffer(o.DRAW_FRAMEBUFFER,pt.__webglFramebuffer);for(let gt=0;gt<R.length;gt++){if(L.resolveDepthBuffer&&(L.depthBuffer&&(J|=o.DEPTH_BUFFER_BIT),L.stencilBuffer&&L.resolveStencilBuffer&&(J|=o.STENCIL_BUFFER_BIT)),j){o.framebufferRenderbuffer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.RENDERBUFFER,pt.__webglColorRenderbuffer[gt]);const $t=i.get(R[gt]).__webglTexture;o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,$t,0)}o.blitFramebuffer(0,0,G,Y,0,0,G,Y,J,o.NEAREST),c===!0&&(ai.length=0,$i.length=0,ai.push(o.COLOR_ATTACHMENT0+gt),L.depthBuffer&&L.resolveDepthBuffer===!1&&(ai.push(ut),$i.push(ut),o.invalidateFramebuffer(o.DRAW_FRAMEBUFFER,$i)),o.invalidateFramebuffer(o.READ_FRAMEBUFFER,ai))}if(e.bindFramebuffer(o.READ_FRAMEBUFFER,null),e.bindFramebuffer(o.DRAW_FRAMEBUFFER,null),j)for(let gt=0;gt<R.length;gt++){e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglMultisampledFramebuffer),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.RENDERBUFFER,pt.__webglColorRenderbuffer[gt]);const $t=i.get(R[gt]).__webglTexture;e.bindFramebuffer(o.FRAMEBUFFER,pt.__webglFramebuffer),o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0+gt,o.TEXTURE_2D,$t,0)}e.bindFramebuffer(o.DRAW_FRAMEBUFFER,pt.__webglMultisampledFramebuffer)}else if(L.depthBuffer&&L.resolveDepthBuffer===!1&&c){const R=L.stencilBuffer?o.DEPTH_STENCIL_ATTACHMENT:o.DEPTH_ATTACHMENT;o.invalidateFramebuffer(o.DRAW_FRAMEBUFFER,[R])}}}function Yi(L){return Math.min(n.maxSamples,L.samples)}function un(L){const R=i.get(L);return L.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function z(L){const R=r.render.frame;h.get(L)!==R&&(h.set(L,R),L.update())}function Os(L,R){const G=L.colorSpace,Y=L.format,J=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||G!==G0&&G!==tc&&(He.getTransfer(G)===ui?(Y!==tn||J!==fs)&&Ht("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):le("WebGLTextures: Unsupported texture color space:",G)),R}function oi(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(l.width=L.naturalWidth||L.width,l.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(l.width=L.displayWidth,l.height=L.displayHeight):(l.width=L.width,l.height=L.height),l}this.allocateTextureUnit=k,this.resetTextureUnits=O,this.getTextureUnits=P,this.setTextureUnits=N,this.setTexture2D=W,this.setTexture2DArray=Q,this.setTexture3D=Z,this.setTextureCube=nt,this.rebindTextures=ne,this.setupRenderTarget=se,this.updateRenderTargetMipmap=ri,this.updateMultisampleRenderTarget=Gi,this.setupDepthRenderbuffer=te,this.setupFrameBufferTexture=Xt,this.useMultisampledRTT=un,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function YP(o,t){function e(i,n=tc){let s;const r=He.getTransfer(n);if(i===fs)return o.UNSIGNED_BYTE;if(i===cy)return o.UNSIGNED_SHORT_4_4_4_4;if(i===ly)return o.UNSIGNED_SHORT_5_5_5_1;if(i===eA)return o.UNSIGNED_INT_5_9_9_9_REV;if(i===iA)return o.UNSIGNED_INT_10F_11F_11F_REV;if(i===QE)return o.BYTE;if(i===tA)return o.SHORT;if(i===of)return o.UNSIGNED_SHORT;if(i===oy)return o.INT;if(i===_r)return o.UNSIGNED_INT;if(i===ts)return o.FLOAT;if(i===Ye)return o.HALF_FLOAT;if(i===nA)return o.ALPHA;if(i===sA)return o.RGB;if(i===tn)return o.RGBA;if(i===So)return o.DEPTH_COMPONENT;if(i===tl)return o.DEPTH_STENCIL;if(i===mu)return o.RED;if(i===hy)return o.RED_INTEGER;if(i===xl)return o.RG;if(i===uy)return o.RG_INTEGER;if(i===dy)return o.RGBA_INTEGER;if(i===s0||i===r0||i===a0||i===o0)if(r===ui)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===s0)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===r0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===a0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===o0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===s0)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===r0)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===a0)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===o0)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===xv||i===bv||i===Sv||i===Ev)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===xv)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===bv)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Sv)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Ev)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Av||i===_v||i===Tv||i===Rv||i===Iv||i===F0||i===Dv)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===Av||i===_v)return r===ui?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Tv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===Rv)return s.COMPRESSED_R11_EAC;if(i===Iv)return s.COMPRESSED_SIGNED_R11_EAC;if(i===F0)return s.COMPRESSED_RG11_EAC;if(i===Dv)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===Cv||i===Ov||i===Pv||i===Nv||i===Lv||i===kv||i===Fv||i===Uv||i===zv||i===Bv||i===Hv||i===Gv||i===Vv||i===Wv)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===Cv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Ov)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Pv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Nv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Lv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===kv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Fv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Uv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===zv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Bv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Hv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Gv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Vv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Wv)return r===ui?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Xv||i===$v||i===Yv)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===Xv)return r===ui?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===$v)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Yv)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Kv||i===qv||i===U0||i===Zv)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===Kv)return s.COMPRESSED_RED_RGTC1_EXT;if(i===qv)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===U0)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Zv)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===cf?o.UNSIGNED_INT_24_8:o[i]!==void 0?o[i]:null}return{convert:e}}const KP=`
|
|
4871
4871
|
void main() {
|
|
4872
4872
|
|
|
4873
4873
|
gl_Position = vec4( position, 1.0 );
|
|
@@ -5793,16 +5793,24 @@ canvas[data-cursor="rotate"] {
|
|
|
5793
5793
|
.cited-mark {
|
|
5794
5794
|
position: absolute;
|
|
5795
5795
|
top: 50%;
|
|
5796
|
-
width:
|
|
5797
|
-
height:
|
|
5796
|
+
width: 18px;
|
|
5797
|
+
height: 18px;
|
|
5798
5798
|
padding: 0;
|
|
5799
|
-
|
|
5799
|
+
display: grid;
|
|
5800
|
+
place-items: center;
|
|
5801
|
+
transform: translate(-50%, -50%);
|
|
5800
5802
|
border: 1px solid rgba(0, 0, 0, .55);
|
|
5801
|
-
border-radius:
|
|
5803
|
+
border-radius: 50%;
|
|
5802
5804
|
background: #fc3;
|
|
5805
|
+
color: #1a1a1a;
|
|
5803
5806
|
pointer-events: auto;
|
|
5804
5807
|
cursor: pointer;
|
|
5805
5808
|
}
|
|
5809
|
+
.cited-mark svg {
|
|
5810
|
+
width: 12px;
|
|
5811
|
+
height: 12px;
|
|
5812
|
+
stroke-width: 2;
|
|
5813
|
+
}
|
|
5806
5814
|
.cited-mark:hover, .cited-mark:focus-visible {
|
|
5807
5815
|
outline: 2px solid #fff;
|
|
5808
5816
|
outline-offset: 1px;
|
|
@@ -6810,12 +6818,15 @@ canvas[data-cursor="rotate"] {
|
|
|
6810
6818
|
pointer-events: none;
|
|
6811
6819
|
white-space: nowrap;
|
|
6812
6820
|
}
|
|
6813
|
-
`;class Qh{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 Qh(e)}static TRAVEL_M=50;get travels(){return this.spanM>Qh.TRAVEL_M}get moved(){return this.spanM>Qh.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(re(e,t.east,e,t.west).x),Math.abs(re(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:$s(0,-s,i,n).lat,south:$s(0,s,i,n).lat,east:$s(s,0,i,n).lng,west:$s(-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 gr{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)>gr.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new gr(Math.max(1-(t.instrument.stabilization??0),gr.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]=gr.HZ;return{eastM:i*gr.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*gr.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*gr.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*gr.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*gr.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*gr.DRIFT_ROLL_DEG*n(s,2.9)}}}class li{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=Qh.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=re(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=li.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 li(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=li.of(t)?.offsetAt(e)??li.STILL;return i?n:li.add(n,gr.of(t)?.offsetAt(e))}static stepHzFor(t){return t<li.SLOWEST_WALK_M_PER_S||t>li.FASTEST_WALK_M_PER_S?0:li.REFERENCE_STEP_HZ*Math.pow(t/li.REFERENCE_SPEED_M_PER_S,li.CADENCE_EXPONENT)}offsetAt(t){return li.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/li.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>li.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/li.JOLT_DECAY_S)*Math.sin(2*Math.PI*li.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,li.STOP_LURCH_M,li.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,li.START_LURCH_M,li.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 li.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=li.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/li.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:li.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:li.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:li.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 b8{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 BA=["nw","n","ne","e","se","s","sw","w"],S8=24,xp=8,E8=3,A8=8;function bp(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 Xu(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const _8={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 nr{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-S8}},a=Xu(t.bounds),c={};for(const l of Object.keys(r))c[l]=bp(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...BA,"rotate"]){const s=nr.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=((nr.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=Xu(t),r=bp(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=_8[i];let d=a,f=c,p=a+l,m=c+h;return u.left&&(d=Math.min(r.x,p-xp)),u.right&&(p=Math.max(r.x,d+xp)),u.top&&(f=Math.min(r.y,m-xp)),u.bottom&&(m=Math.max(r.y,f+xp)),{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=nr.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=Xu(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=Xu(t.bounds);return t.points.map(i=>bp({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=A8){const n=nr.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=Xu(t.bounds),n=bp(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?nr.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=nr.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=nr.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<=E8?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const hM=6,Sp=hM/2,tb=20,eb=24,ib=9,nb=6,sb=7,rb=6,ea=4;class yu{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+ib*f),rb*f)-d:0,m=f>0?d*(1+sb*f)-d:0,g=3*eb*(t.blur??0)+1.5*tb*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(${(eb*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+ib*e),rb*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<=nb;d++){const f=d/nb,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+sb*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=tb*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(nr.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of nr.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,ea,ea,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(nr.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=yu.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,ea+2,ea+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,ea,ea,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,ea+2,ea+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+ea+5,s.picture.y-ea-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(nr.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 BA){const n=t[i];this.ctx.fillRect(n.x-Sp,n.y-Sp,hM,hM)}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,Sp+1,Sp+1,0,0,2*Math.PI),this.ctx.fill())}}const ab=.05,ob=.08,cb=2,lb=3,T8=14,R8=.02;class hb{context;constructor(t){this.context=t}voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}lr.isLive(this.context)&&lr.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(),lr.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const 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,ab);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,ab)}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*cb),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*cb),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*lb),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(R8*t.sampleRate)),s=Math.round(lb*T8);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,ob/3);const n=i+ob;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 gf{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}","out-of-range":"{path}: {found} is outside {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=gf.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=>` ${gf.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
6821
|
+
`;class Qh{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 Qh(e)}static TRAVEL_M=50;get travels(){return this.spanM>Qh.TRAVEL_M}get moved(){return this.spanM>Qh.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(re(e,t.east,e,t.west).x),Math.abs(re(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:$s(0,-s,i,n).lat,south:$s(0,s,i,n).lat,east:$s(s,0,i,n).lng,west:$s(-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 gr{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)>gr.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new gr(Math.max(1-(t.instrument.stabilization??0),gr.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]=gr.HZ;return{eastM:i*gr.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*gr.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*gr.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*gr.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*gr.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*gr.DRIFT_ROLL_DEG*n(s,2.9)}}}class li{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=Qh.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=re(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=li.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 li(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=li.of(t)?.offsetAt(e)??li.STILL;return i?n:li.add(n,gr.of(t)?.offsetAt(e))}static stepHzFor(t){return t<li.SLOWEST_WALK_M_PER_S||t>li.FASTEST_WALK_M_PER_S?0:li.REFERENCE_STEP_HZ*Math.pow(t/li.REFERENCE_SPEED_M_PER_S,li.CADENCE_EXPONENT)}offsetAt(t){return li.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/li.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>li.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/li.JOLT_DECAY_S)*Math.sin(2*Math.PI*li.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,li.STOP_LURCH_M,li.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,li.START_LURCH_M,li.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 li.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=li.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/li.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:li.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:li.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:li.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 b8{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 BA=["nw","n","ne","e","se","s","sw","w"],S8=24,xp=8,E8=3,A8=8;function bp(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 Xu(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const _8={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 nr{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-S8}},a=Xu(t.bounds),c={};for(const l of Object.keys(r))c[l]=bp(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...BA,"rotate"]){const s=nr.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=((nr.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=Xu(t),r=bp(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=_8[i];let d=a,f=c,p=a+l,m=c+h;return u.left&&(d=Math.min(r.x,p-xp)),u.right&&(p=Math.max(r.x,d+xp)),u.top&&(f=Math.min(r.y,m-xp)),u.bottom&&(m=Math.max(r.y,f+xp)),{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=nr.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=Xu(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=Xu(t.bounds);return t.points.map(i=>bp({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=A8){const n=nr.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=Xu(t.bounds),n=bp(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?nr.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=nr.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=nr.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<=E8?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const hM=6,Sp=hM/2,tb=20,eb=24,ib=9,nb=6,sb=7,rb=6,ea=4;class yu{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+ib*f),rb*f)-d:0,m=f>0?d*(1+sb*f)-d:0,g=3*eb*(t.blur??0)+1.5*tb*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(${(eb*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+ib*e),rb*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<=nb;d++){const f=d/nb,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+sb*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=tb*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(nr.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of nr.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,ea,ea,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(nr.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=yu.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,ea+2,ea+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,ea,ea,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,ea+2,ea+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+ea+5,s.picture.y-ea-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(nr.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 BA){const n=t[i];this.ctx.fillRect(n.x-Sp,n.y-Sp,hM,hM)}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,Sp+1,Sp+1,0,0,2*Math.PI),this.ctx.fill())}}const ab=.05,ob=.08,cb=2,lb=3,T8=14,R8=.02;class hb{context;constructor(t){this.context=t}voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}lr.isLive(this.context)&&lr.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(),lr.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const 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,ab);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,ab)}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*cb),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*cb),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*lb),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(R8*t.sampleRate)),s=Math.round(lb*T8);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,ob/3);const n=i+ob;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 ye{static draw(t,e="none"){return`<svg class="icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="${e}" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`}static TRASH=ye.draw('<path d="M2.5 4.5h11"/><path d="M6 4.5V3h4v1.5"/><path d="M4 4.5l.7 9h6.6l.7-9"/><path d="M6.8 7v4.5M9.2 7v4.5"/>');static TARGET=ye.draw('<circle cx="8" cy="8" r="5"/><circle cx="8" cy="8" r="1.6"/><path d="M8 1v2.2M8 12.8V15M1 8h2.2M12.8 8H15"/>');static PLAY=ye.draw('<path d="M5 3.2v9.6L12.6 8z"/>',"currentColor");static PAUSE=ye.draw('<path d="M5.5 3.5v9M10.5 3.5v9"/>');static RECORD=ye.draw('<circle cx="8" cy="8" r="4.2" fill="var(--error, #d93025)" stroke="none"/>');static STOP=ye.draw('<rect x="4" y="4" width="8" height="8" rx="1.2"/>',"currentColor");static PREVIOUS_MARK=ye.draw('<path d="M6.5 4 2.5 8l4 4"/><path d="M11 5.2 13.8 8 11 10.8 8.2 8z"/>');static NEXT_MARK=ye.draw('<path d="M9.5 4l4 4-4 4"/><path d="M5 5.2 7.8 8 5 10.8 2.2 8z"/>');static CLOSE=ye.draw('<path d="M4 4l8 8M12 4l-8 8"/>');static PLUS=ye.draw('<path d="M8 3v10M3 8h10"/>');static COPY=ye.draw('<rect x="5.5" y="5.5" width="8" height="8" rx="1.3"/><path d="M10.5 3.2h-7a1.3 1.3 0 0 0-1.3 1.3v7"/>');static CLOCK=ye.draw('<circle cx="8" cy="8" r="6"/><path d="M8 4.6V8l2.4 1.6"/>');static INTERVIEW=ye.draw('<path d="M13.3 9.2a1.6 1.6 0 0 1-1.6 1.6H6.2L3 13.4V4.4a1.6 1.6 0 0 1 1.6-1.6h7.1a1.6 1.6 0 0 1 1.6 1.6z"/><path d="M5.8 6.1h5.1M5.8 8.4h3.2"/>');static LOCK=ye.draw('<rect x="3.2" y="7.2" width="9.6" height="6.4" rx="1.4"/><path d="M5.6 7.2V5.4a2.4 2.4 0 0 1 4.8 0v1.8"/>');static LOCK_OPEN=ye.draw('<rect x="3.2" y="7.2" width="9.6" height="6.4" rx="1.4"/><path d="M5.6 7.2V5.4a2.4 2.4 0 0 1 4.6-.7"/>');static METEOR=ye.draw('<path d="M2.5 2.5l7 7"/><path d="M5.5 2.5l5 5"/><circle cx="11.5" cy="11.5" r="2"/>');static COMET=ye.draw('<circle cx="11" cy="11" r="2.4"/><path d="M9.3 9.3 2.5 2.5M9 11.2 3 7M11.2 9 7 3"/>');static STAR=ye.draw('<path d="M8 2.2l1.7 3.6 3.9.5-2.9 2.7.8 3.9L8 11l-3.5 1.9.8-3.9-2.9-2.7 3.9-.5z"/>');static SATELLITE=ye.draw('<rect x="6.3" y="6.3" width="3.4" height="3.4" transform="rotate(45 8 8)"/><path d="M5.4 5.4 3 3M10.6 10.6 13 13"/><path d="M1.8 4.2 4.2 1.8M11.8 14.2l2.4-2.4"/><path d="M10.5 3.5a3 3 0 0 1 2 2"/>');static FIREBALL=ye.draw('<circle cx="10.5" cy="10.5" r="2.6"/><path d="M8.6 8.6 3 3M8 10.6 4.5 8.5M10.6 8 8.5 4.5"/>');static SUMMARY=ye.draw('<rect x="3" y="2" width="10" height="12" rx="1.5"/><path d="M5.5 5.5h5M5.5 8h5M5.5 10.5h3"/>');static WITNESS=ye.draw('<circle cx="8" cy="5" r="2.6"/><path d="M2.8 14c.6-3 2.6-4.6 5.2-4.6s4.6 1.6 5.2 4.6"/>');static LOCATION=ye.draw('<path d="M8 14.3s4.5-4.3 4.5-7.8a4.5 4.5 0 0 0-9 0c0 3.5 4.5 7.8 4.5 7.8z"/><circle cx="8" cy="6.5" r="1.6"/>');static DATE=ye.draw('<rect x="2.3" y="3.3" width="11.4" height="10.4" rx="1.5"/><path d="M2.3 6.6h11.4M5.3 1.8v2.8M10.7 1.8v2.8"/>');static ENVIRONMENT=ye.draw('<path d="M1.5 14h13"/><path d="M2.8 14V8.3L6.3 5.5l3.5 2.8V14"/><path d="M12.2 14V9.4"/><circle cx="12.2" cy="7.4" r="2.1"/>');static SKY=ye.draw('<path d="M4.6 12.5h7a2.6 2.6 0 0 0 .3-5.2 3.8 3.8 0 0 0-7.3-.6 2.9 2.9 0 0 0 0 5.8z"/>');static PHENOMENON=ye.draw('<ellipse cx="8" cy="9" rx="6.3" ry="2.1"/><path d="M4.6 7.8a3.4 3.4 0 0 1 6.8 0"/><path d="M5 13.4l.6-1.4M11 13.4l-.6-1.4M8 14v-1.4"/>');static SOUND=ye.draw('<path d="M2.5 6.2h2.3L8 3.5v9L4.8 9.8H2.5z"/><path d="M10.5 6a2.8 2.8 0 0 1 0 4M12.3 4.2a5.4 5.4 0 0 1 0 7.6"/>');static PICTURES=ye.draw('<rect x="2" y="3" width="12" height="10" rx="1.5"/><circle cx="5.8" cy="6.4" r="1.2"/><path d="M2.5 12l3.8-3.6 2.4 2.2 2.2-1.8 2.6 2.5"/>');static FILES=ye.draw('<path d="M4 1.8h5.2L12.5 5v9.2H4z"/><path d="M9 1.8V5.2h3.5"/>');static BY_GLYPH={"🗑":ye.TRASH,"🎯":ye.TARGET,"+":ye.PLUS,"✕":ye.CLOSE,"▶":ye.PLAY,"⏸":ye.PAUSE,"⏺":ye.RECORD,"⏹":ye.STOP};static show(t,e){if(t.dataset.icon===e&&t.firstChild)return;const i=ye.BY_GLYPH[e];i?t.innerHTML=i:t.textContent=e,t.dataset.icon=e}static CSS=`
|
|
6822
|
+
.icon { display: block; flex: none; }
|
|
6823
|
+
button:has(> .icon:only-child) { display: inline-flex; align-items: center; justify-content: center; }
|
|
6824
|
+
`}class gf{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}","out-of-range":"{path}: {found} is outside {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=gf.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=>` ${gf.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
6814
6825
|
${i.join(`
|
|
6815
6826
|
`)}`)}}class vr{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!vr.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:vr.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(vr.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):vr.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:vr.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=vr.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:vr.typeOf(t)});return;default:typeof t!==e.type?n.push({kind:"wrong-type",path:i,expected:e.type,found:vr.typeOf(t)}):typeof t=="number"&&(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&n.push({kind:"out-of-range",path:i,expected:`${e.minimum??"−∞"}–${e.maximum??"∞"}`,found:String(t)})}}static STATED_KEYS=new Set(["value","basis","rationale","how","range","source"]);static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return vr.isObject(t)&&"value"in t&&Object.keys(t).every(e=>vr.STATED_KEYS.has(e))}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class Ur{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?Ur.travelDegOver(t,e,i,i+n*1e3)/s/Ur.PIXELS_PER_INSTANT:0,a=Ur.flashesOver(t,n)*Ur.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(Ur.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=Ur.directionAt(r,e,i),c=Ur.directionAt(r,e,n),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=Xr(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 HA=Math.PI/180,I8=180/Math.PI,D8=256,GA=19,C8=1.25;function VA(o,t){return 156543.03392*Math.cos(o*HA)/2**t}function WA(o,t){return VA(o,t)*D8}function O8(o,t){let e=0;for(;e<GA&&WA(o,e+1)>=t;)e++;return e}function XA(o,t){return WA(o,t)}function P8(o,t){const e=t*C8;let i=0;for(;i<GA&&VA(o,i)>e;)i++;return i}function d0(o){const t=o*HA;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function $A(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:d0(t)*i}}function YA(o,t,e){const i=d0(o.north),n=d0(o.south);return{x:(t-o.west)/(o.east-o.west),y:(d0(e)-i)/(n-i)}}function N8(o,t,e){const{x:i,y:n}=$A(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function L8(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=ub(o.y,t);return{south:ub(o.y+1,t),north:n,west:e,east:i}}function ub(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*I8}function KA(o,t,e,i){const n=N8(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(L8),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 k8="#2ec4ff";class Wc{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=YA(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??k8;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:Wc.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,Wc.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=re(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=Wc.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Wc.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(re(r,t.east,r,t.west).x)/this.width,l=Wc.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 vi{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 vi.including(t.boundsAround(vi.MIN_SPAN_M,vi.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(vi.MAX_ZOOM,Math.max(vi.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=vi.mercatorY01(e.north),s=vi.mercatorY01(e.south),r=vi.mercatorY01(i.north),a=vi.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=vi.mercatorY01(n.north),r=vi.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(vi.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=vi.mercatorY01(t.north),n=vi.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:vi.latitudeAt(i+(this.centerY-e)*(n-i)),south:vi.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=re(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=re(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:$s(0,-a,n,s).lat,south:$s(0,a,n,s).lat,east:$s(a,0,n,s).lng,west:$s(-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=vi.mercatorY01(t.north),s=vi.mercatorY01(t.south);return{lat:vi.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 pr=256,db=3,F8=32768;class qA{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(re(i,t.east,i,t.west).x),r=Math.abs(re(t.north,n,t.south,n).z),a=O8(i,Math.max(s,r)),{tiles:c}=KA(n,i,a,db),l=db*pr,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=pr,c.height=pr;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,pr,pr),u=(t.x-e.x)*pr,d=(t.y-e.y)*pr;for(let f=0;f<pr;f++)for(let p=0;p<pr;p++){const m=(f*pr+p)*4,g=h[m]*256+h[m+1]+h[m+2]/256-F8,v=u+p,M=d+f;i[M*n+v]=g}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=$A(e,t,i),l=(a-n.x)*pr,h=(c-n.y)*pr,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],w=s[p*r+u],y=s[p*r+f],x=v+(M-v)*m,b=w+(y-w)*m;return x+(b-x)*g}}class km{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const M=i+2+v*12;s.set(e.getUint16(M,!0),{type:e.getUint16(M+2,!0),count:e.getUint32(M+4,!0),value:e.getUint32(M+8,!0)})}const r=(v,M)=>{const w=s.get(v);if(w===void 0){if(M===void 0)throw new Error(`TIFF without tag ${v}`);return M}return w.type===3?w.value&65535:w.value},a=v=>{const M=s.get(v);if(M===void 0)throw new Error(`TIFF without tag ${v}`);const w=M.type===3?2:4,y=[];if(M.count*w<=4){const x=new DataView(new ArrayBuffer(4));x.setUint32(0,M.value,!0);for(let b=0;b<M.count;b++)y.push(w===2?x.getUint16(b*2,!0):x.getUint32(0,!0))}else for(let x=0;x<M.count;x++)y.push(w===2?e.getUint16(M.value+x*2,!0):e.getUint32(M.value+x*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 km(c,l,h,d?new Float32Array(m.buffer):m)}}class Uo extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class U8{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 ze{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??ze.WMS,this.wfs=t.wfsEndpoint??ze.WFS}static radius(t){return Math.min(t,ze.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,ze.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=ze.lidarRadius(e),n=Math.ceil(2*i/ze.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,ze.HEIGHT_LAYER),this.raster(t,i,n,ze.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new Uo("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===ze.NO_DATA))throw new Uo("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 U8(a,c,l,n,h)}}async laserDate(t){return ze.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return ze.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=ze.radius(e),n=Math.min(ze.MAX_PHOTO_PIXELS,Math.ceil(2*i/ze.METRES_PER_PIXEL)),s=await this.raster(t,i,n,ze.PHOTO_LAYER);if(s.samples<3)throw new Uo("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=ze.radius(e),s=n/ze.METRES_PER_DEGREE,r=n/(ze.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,ze.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:ze.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=ze.MAX_WHOLE_M/ze.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,m]=ze.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')`,ze.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/ze.METRES_PER_DEGREE,r=e/(ze.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 Uo("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new Uo("unreachable",`The survey answered ${c.status}`);try{return km.parse(await c.arrayBuffer())}catch(l){throw new Uo("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 Uo("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new Uo("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class Yo{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=>re(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>re(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/Yo.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=Yo.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);m.distanceM>Yo.NEAR_M||Yo.angleBetween(d,m.heading)<=Yo.ALIGNED_DEG&&(r+=h/u)}}return r>=Yo.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 Ne{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??Ne.WMS,this.timeoutMs=t.timeoutMs??Ne.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Ne.MAX_WINDOW_M,this.geoplatform=new ze({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(!ze.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(re(n.lat,t.east,n.lat,t.west).x),r=Math.abs(re(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/Ne.METRES_PER_DEGREE,north:t.north+c.y/Ne.METRES_PER_DEGREE,west:t.west-c.x/(Ne.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Ne.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=m=>Math.min(Ne.MAX_PIXELS,Math.max(Ne.MIN_PIXELS,Math.ceil(m/Ne.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)>Ne.COARSE_METRES_PER_PIXEL;for(const m of p?[...Ne.LAYERS].reverse():Ne.LAYERS)try{const g=await this.heights(l,u,m);m===Ne.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<Ne.MESH_FROM_VERTICES||t.height<Ne.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Ne.FINE_SPACING_M),c=Math.max(r-1,Math.min(Ne.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 km.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>Ne.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>Yo.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,Ne.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(g,[v,M,w])=>s.values[g*s.samples]===v&&s.values[g*s.samples+1]===M&&s.values[g*s.samples+2]===w,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let g=0;g<l.length;g++)r(g,Ne.DECK)&&(l[g]=1,h=!0);if(!h)return;const u=Ne.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 w=-u;w<=u;w++)for(let y=-u;y<=u;y++){const x=v+y,b=M+w;if(x<0||b<0||x>=a||b>=c)continue;const E=b*a+x;l[E]===0&&r(E,Ne.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,Ne.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>Ne.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)*Ne.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Ne.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 w=Math.floor(v/h),y=Math.floor(M/u);if(w<0||y<0||w>=s||y>=r)return;const x=e[y*s+w];return Number.isFinite(x)&&x>Ne.NO_DATA_BELOW?x:void 0},p=Ne.DECK_HALF_WIDTH_M,m=Ne.DECK_APPROACH_M,g=(v,M)=>{const w=Math.hypot(v.x-M.x,v.y-M.y)||1,y={x:(v.x-M.x)/w,y:(v.y-M.y)/w},x=[0,m/2,m].map(b=>f(v.x+y.x*b,v.y+y.y*b)).filter(b=>b!==void 0);return x.length>0?Math.max(...x):void 0};for(const v of Ne.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 w=M[M.length-1];if(w<1||w>Ne.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),x=g(v[v.length-1],v[v.length-2]);if(y===void 0||x===void 0)continue;const b=p+m,E=Math.max(0,Math.floor((Math.min(...v.map(I=>I.x))-b)/h)),S=Math.min(s-1,Math.ceil((Math.max(...v.map(I=>I.x))+b)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(I=>I.y))-b)/u)),_=Math.min(r-1,Math.ceil((Math.max(...v.map(I=>I.y))+b)/u));for(let I=A;I<=_;I++)for(let D=E;D<=S;D++){const O=Ne.nearestAlong(v,M,{x:(D+.5)*h,y:(I+.5)*u});if(O.distance>p||O.s<-m||O.s>w+m)continue;const P=y+(x-y)*Math.min(1,Math.max(0,O.s/w)),N=I*s+D;e[N]>=P||(t.values[N]=P)}}}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 w=-1;w<=1;w++){const y=g+w,x=v+M;y>=0&&x>=0&&y<i&&x<n&&(s[x*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 w=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,w,g,Math.max(1,u),Math.max(1,d)):this.bilinear(t,w,g),x=p*a+v;y===void 0?f++:(l[x]=y,h[x]=1)}}if(!(f===a*c||f/(a*c)>Ne.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<Ne.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<Ne.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 z8{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 f0=256,B8=5;async function ZA(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(re(n,o.east,n,o.west).x),a=Math.abs(re(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=H8(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=KA(s,n,l,h),f=h*f0,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 x=e(y),b=await i(x);if(!b.ok)throw new Error(`Imagery tile fetch failed (${b.status}): ${x}`);const E=await createImageBitmap(await b.blob());m.drawImage(E,(y.x-g.x)*f0,(y.y-g.y)*f0)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const M=document.createElement("canvas");M.width=v,M.height=v;const w=M.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(p,0,0,f,f,0,0,v,v),{source:M,width:v,height:v,bounds:d}}function H8(o,t,e){let i=P8(o,t/Math.max(1,e)),n=fb(o,i,t);for(;n>B8&&i>0;)i--,n=fb(o,i,t);return{zoom:i,gridSize:n,mPerPixel:XA(o,i)/f0}}function fb(o,t,e){const i=Math.ceil(e/2/XA(o,t));return Math.max(3,2*i+1)}class JA{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 ZA(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Hs{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=Hs.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=Hs.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[Hs.FRANCE_ENDPOINT,...e.filter(d=>d!==Hs.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=Hs.queue.then(t,t);return Hs.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Hs.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Hs.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,Hs.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class Ko{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 Hs(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Ko.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:Ko.surfaceOf(s),widthM:Ko.widthOf(s),...Ko.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:Ko.WIDTH_M[t.highway]??Ko.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 Kg="https://ufoathome.org/roads/index.json";class Th{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??Th.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(`
|
|
6816
|
-
`);let e=Th.shared.get(t);return e||(e=this.fetchFirstAvailable(),Th.shared.set(t,e),e.then(i=>{i.length===0&&Th.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.
|
|
6817
|
-
`);let e=Rh.shared.get(t);return e||(e=this.fetchFirstAvailable(),Rh.shared.set(t,e),e.then(i=>{i.length===0&&Rh.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.178.4")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==qg?[e,qg]:[qg]).map(i=>i+t)}}class Ns{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=Ns.key(t);let i=Ns.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Ns.asked.set(e,i),i.catch(()=>Ns.asked.delete(e))),structuredClone(await i)}static forget(){Ns.asked.clear()}static key(t){return`v${Ns.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Ns.openCache(),n=Ns.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<Ns.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Ns.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-Ns.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ns.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class nc{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 ze(t)}static covers(t){return ze.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>nc.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=nc.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=nc.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=nc.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]>nc.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 qn{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 Hs(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"~"^(${qn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${qn.ROUTES})$"];out body;`;return qn.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=qn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>re(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 qn.samples(a)){u++;const M=qn.waysAt(d,v);if(M.length===0)continue;const[w]=M;w.name&&c.set(w.name,(c.get(w.name)??0)+1),w.voltageV&&l.set(w.voltageV,(l.get(w.voltageV)??0)+1);for(const y of new Set(M.flatMap(x=>x.services)))h.set(y,(h.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,w)=>w[1]-M[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(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=qn.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=qn.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=qn.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=>re(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=qn.SAMPLE_M/2;a<n;a+=qn.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(qn.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<=qn.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 Ih{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 Hs(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Ih.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${qn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=qn.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=qn.voltageOf(r),l=Ih.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Ih.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:Ih.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 W8{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(!nc.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 pn{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=pn.key(t);let i=pn.asked.get(e)??pn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},pn.asked.set(e,i),n.catch(()=>pn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){pn.asked.clear(),pn.failedAt=-1/0}static key(t){return`v${pn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of pn.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 pn.openCache(),n=pn.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<pn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-pn.failedAt<pn.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(pn.failedAt=this.now(),s)return s;throw a}return i&&pn.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-pn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(pn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Zg="https://ufoathome.org/railways/index.json";class Dh{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??Dh.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(`
|
|
6818
|
-
`);let e=Dh.shared.get(t);return e||(e=this.fetchFirstAvailable(),Dh.shared.set(t,e),e.then(i=>{i.length===0&&Dh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.4")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Zg?[e,Zg]:[Zg]).map(i=>i+t)}}function jA(){return{elevation:QA(),imagery:t3(),roads:X8(),water:$8(),railways:Y8()}}function QA(){return new z8(new Ne,new qA)}function t3(){return new JA}function X8(){return new Th({fallback:new G8(new ic,new Ko)})}function $8(){return new Rh({fallback:new Ns(new V8(new vf,new Xc))})}function Y8(){return new Dh({fallback:new pn(new W8(new nc,new Ih))})}const K8=new Set,Pa="show-observer-map",Na="hide-milestones",nl="minified";class Ve extends HTMLElement{static get observedAttributes(){return["src",Pa,Na,nl]}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 vi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=bm.create();issues=[];issueCheck=0;sightingAudio=new hb;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new hb(t)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Ve.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");Ve.setIcon(this.moreButton,t?Kt.UNFOLDED:Kt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(t){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!t){this.fitControls();return}const e=document.createElement("button");e.type="button",e.id="video-button",e.innerHTML=Kt.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:i}=await at(async()=>{const{VideoButton:s}=await import("./VideoButton-C62NkJrH.js");return{VideoButton:s}},[],import.meta.url);if(this.videoElement!==e)return;const n=new i(t,e);this.videoButton=n,this.messages&&(n.messages=this.messages),this.stageElement.append(n.panel),n.open()}labelVideoButton(){const t=this.videoElement;!t||this.videoButton||(t.title=this.messages?.recordVideo??"",t.setAttribute("aria-label",t.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(t){t!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,t&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(t){const e=this.currentTime,i=t.caption&&this.sighting.milestones.length>0?Of(this.sighting.milestones,e):void 0,n=i?this.said.read(i.label)??"":void 0,s=this.canvas.getBoundingClientRect(),r=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:n,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...r&&s.width>0&&s.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-s.left)/s.width,top:(r.top-s.top)/s.height,width:r.width/s.width,height:r.height/s.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ve.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>=vi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=vi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ve.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=vi.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>${x8}</style>${w8}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new yu(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 Wc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Pa&&this.applyObserverMapDefault(),t===Na&&this.setMilestonesShown(!this.hasAttribute(Na)),t===nl){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(nl)}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(n3)))};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 Sr.recording(t)}get sightingData(){return dE(this.currentSighting)}set sightingData(t){const e=ar.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=YM(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;set titleShown(t){this.titleHidden=!t,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await at(async()=>{const{default:r}=await import("./sightingSchema-pBDQNwMz.js");return{default:r}},[],import.meta.url);n=new vr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],gf.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(q8,{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=gf.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(t){this.cited=[...t],this.refreshCitedMarks()}refreshCitedMarks(){const t=this.player.seekableDuration;this.citedMarks.replaceChildren(...(t>0?this.cited:[]).map(e=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const n=e.quote??"";return i.title=n,i.setAttribute("aria-label",n),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Ve.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(i3,{bubbles:!0,composed:!0,detail:{at:t/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;if(!this.referenceOpacityTouched&&t.length>0){const e=String(t[0].opacity);this.referenceOpacityInput.value!==e&&(this.referenceOpacityInput.value=e,this.severalReferences||this.dispatchReferenceView())}for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ve.setIcon(this.referencesButton,i?Kt.PICTURES_ON:Kt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Ve.setIcon(this.tracesButton,this.tracesShownState?Kt.TRACES_ON:Kt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?ud(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ve.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){if(t.buttons!==0){this.seekPreview.hidden=!0;return}const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ve.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?Of(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 yu(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=Ve.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?Of(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=Ur.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ve.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ve.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ve.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ve.EXPOSURE_STEP_PX),s=Math.min(Ve.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=_i.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(t,e){this.sayTimeMoved(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:K8;this.canvasRenderer.setStarPoints(_i.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?nr.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(aE(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 b8(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*Ve.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?Kt.PLAY:Kt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ve.icons.get(t)!==e&&(Ve.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},Ve.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(),Ve.setIcon(this.playPauseButton,t?Kt.PAUSE:Kt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Pa),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;Ve.setIcon(this.observerMapButton,t?Kt.MAP_ON:Kt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Qh.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=vi.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?vi.expand(t,Ve.OBSERVER_MAP_IMAGERY_AHEAD):t,n=vi.IMAGERY_PX*(e?1+2*Ve.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:t3();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?vi.expand(t,Ve.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=Ve.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},Ve.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Of(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?ud(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?Aa.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(_i.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,ud(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??"",Ve.setIcon(this.milestonesButton,this.milestonesShown?Kt.MILESTONES_ON:Kt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=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=Xr(i,t),{lat:s,lng:r}=$s(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=Aa.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return li.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=Ve.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ve.setIcon(this.miniMuteButton,this.mutedState?Kt.MUTED:Kt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Ve.setIcon(this.muteButton,Kt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Ve.setIcon(this.muteButton,this.mutedState?Kt.MUTED:Kt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ve.setIcon(this.fullscreenButton,t?Kt.EXIT_FULLSCREEN:Kt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Qn(Ws.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=vo(Ws.preferencesFor(this),Mo);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await IT.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.videoButton&&(this.videoButton.messages=t),this.labelVideoButton(),this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=rE(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?K1(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 zo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?mb(pb(this.realStartMs+i)):zo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?zo(t):zo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return zo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return zo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?zo(this.currentSighting.timeline.duration):this.canShowClockTime?mb(pb(this.realStartMs+this.realDurationMs)):zo(this.realDurationMs)}}function pb(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function mb(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 zo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const uM="rr0-ufo";function e3(){customElements.get(uM)||customElements.define(uM,Ve)}const i3="timechange",q8="recordingissues",n3="minifiedreset",Z8=`
|
|
6827
|
+
`);let e=Th.shared.get(t);return e||(e=this.fetchFirstAvailable(),Th.shared.set(t,e),e.then(i=>{i.length===0&&Th.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.179.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==Kg?[e,Kg]:[Kg]).map(i=>i+t)}}class ic{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 ze(t)}static covers(t){return ze.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>ic.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=ic.BY_NATURE[n]??ic.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=ic.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=ic.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 G8{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(ic.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class vf{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new ze(t)}static covers(t){return ze.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>vf.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=>vf.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 Xc{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new Hs(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 Xc.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=Xc.rings(a("inner"));for(const[l,h]of Xc.rings(a("outer")).entries()){const u=c.filter(d=>Xc.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 Xc.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 V8{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(vf.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const qg="https://ufoathome.org/water/index.json";class Rh{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??Rh.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(`
|
|
6828
|
+
`);let e=Rh.shared.get(t);return e||(e=this.fetchFirstAvailable(),Rh.shared.set(t,e),e.then(i=>{i.length===0&&Rh.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.179.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==qg?[e,qg]:[qg]).map(i=>i+t)}}class Ns{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=Ns.key(t);let i=Ns.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Ns.asked.set(e,i),i.catch(()=>Ns.asked.delete(e))),structuredClone(await i)}static forget(){Ns.asked.clear()}static key(t){return`v${Ns.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Ns.openCache(),n=Ns.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<Ns.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Ns.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-Ns.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ns.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class nc{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 ze(t)}static covers(t){return ze.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>nc.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=nc.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=nc.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=nc.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]>nc.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 qn{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 Hs(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"~"^(${qn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${qn.ROUTES})$"];out body;`;return qn.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=qn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>re(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 qn.samples(a)){u++;const M=qn.waysAt(d,v);if(M.length===0)continue;const[w]=M;w.name&&c.set(w.name,(c.get(w.name)??0)+1),w.voltageV&&l.set(w.voltageV,(l.get(w.voltageV)??0)+1);for(const y of new Set(M.flatMap(x=>x.services)))h.set(y,(h.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,w)=>w[1]-M[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(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=qn.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=qn.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=qn.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=>re(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=qn.SAMPLE_M/2;a<n;a+=qn.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(qn.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<=qn.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 Ih{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 Hs(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Ih.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${qn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=qn.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=qn.voltageOf(r),l=Ih.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Ih.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:Ih.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 W8{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(!nc.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 pn{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=pn.key(t);let i=pn.asked.get(e)??pn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},pn.asked.set(e,i),n.catch(()=>pn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){pn.asked.clear(),pn.failedAt=-1/0}static key(t){return`v${pn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of pn.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 pn.openCache(),n=pn.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<pn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-pn.failedAt<pn.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(pn.failedAt=this.now(),s)return s;throw a}return i&&pn.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-pn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(pn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Zg="https://ufoathome.org/railways/index.json";class Dh{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??Dh.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(`
|
|
6829
|
+
`);let e=Dh.shared.get(t);return e||(e=this.fetchFirstAvailable(),Dh.shared.set(t,e),e.then(i=>{i.length===0&&Dh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.179.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Zg?[e,Zg]:[Zg]).map(i=>i+t)}}function jA(){return{elevation:QA(),imagery:t3(),roads:X8(),water:$8(),railways:Y8()}}function QA(){return new z8(new Ne,new qA)}function t3(){return new JA}function X8(){return new Th({fallback:new G8(new ic,new Ko)})}function $8(){return new Rh({fallback:new Ns(new V8(new vf,new Xc))})}function Y8(){return new Dh({fallback:new pn(new W8(new nc,new Ih))})}const K8=new Set,Pa="show-observer-map",Na="hide-milestones",nl="minified";class Ve extends HTMLElement{static get observedAttributes(){return["src",Pa,Na,nl]}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 vi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=bm.create();issues=[];issueCheck=0;sightingAudio=new hb;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new hb(t)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Ve.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");Ve.setIcon(this.moreButton,t?Kt.UNFOLDED:Kt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(t){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!t){this.fitControls();return}const e=document.createElement("button");e.type="button",e.id="video-button",e.innerHTML=Kt.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:i}=await at(async()=>{const{VideoButton:s}=await import("./VideoButton-C62NkJrH.js");return{VideoButton:s}},[],import.meta.url);if(this.videoElement!==e)return;const n=new i(t,e);this.videoButton=n,this.messages&&(n.messages=this.messages),this.stageElement.append(n.panel),n.open()}labelVideoButton(){const t=this.videoElement;!t||this.videoButton||(t.title=this.messages?.recordVideo??"",t.setAttribute("aria-label",t.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(t){t!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,t&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(t){const e=this.currentTime,i=t.caption&&this.sighting.milestones.length>0?Of(this.sighting.milestones,e):void 0,n=i?this.said.read(i.label)??"":void 0,s=this.canvas.getBoundingClientRect(),r=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:n,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...r&&s.width>0&&s.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-s.left)/s.width,top:(r.top-s.top)/s.height,width:r.width/s.width,height:r.height/s.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ve.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>=vi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=vi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ve.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=vi.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>${x8}</style>${w8}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new yu(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 Wc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Pa&&this.applyObserverMapDefault(),t===Na&&this.setMilestonesShown(!this.hasAttribute(Na)),t===nl){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(nl)}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(n3)))};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 Sr.recording(t)}get sightingData(){return dE(this.currentSighting)}set sightingData(t){const e=ar.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=YM(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;set titleShown(t){this.titleHidden=!t,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await at(async()=>{const{default:r}=await import("./sightingSchema-pBDQNwMz.js");return{default:r}},[],import.meta.url);n=new vr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],gf.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(q8,{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=gf.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(t){this.cited=[...t],this.refreshCitedMarks()}refreshCitedMarks(){const t=this.player.seekableDuration;this.citedMarks.replaceChildren(...(t>0?this.cited:[]).map(e=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=ye.INTERVIEW,i.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const n=e.quote??"";return i.title=n,i.setAttribute("aria-label",n),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Ve.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(i3,{bubbles:!0,composed:!0,detail:{at:t/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;if(!this.referenceOpacityTouched&&t.length>0){const e=String(t[0].opacity);this.referenceOpacityInput.value!==e&&(this.referenceOpacityInput.value=e,this.severalReferences||this.dispatchReferenceView())}for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ve.setIcon(this.referencesButton,i?Kt.PICTURES_ON:Kt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Ve.setIcon(this.tracesButton,this.tracesShownState?Kt.TRACES_ON:Kt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?ud(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ve.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){if(t.buttons!==0){this.seekPreview.hidden=!0;return}const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ve.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?Of(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 yu(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=Ve.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?Of(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=Ur.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ve.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ve.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ve.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ve.EXPOSURE_STEP_PX),s=Math.min(Ve.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=_i.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(t,e){this.sayTimeMoved(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:K8;this.canvasRenderer.setStarPoints(_i.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?nr.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(aE(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 b8(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*Ve.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?Kt.PLAY:Kt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ve.icons.get(t)!==e&&(Ve.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},Ve.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(),Ve.setIcon(this.playPauseButton,t?Kt.PAUSE:Kt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Pa),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;Ve.setIcon(this.observerMapButton,t?Kt.MAP_ON:Kt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Qh.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=vi.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?vi.expand(t,Ve.OBSERVER_MAP_IMAGERY_AHEAD):t,n=vi.IMAGERY_PX*(e?1+2*Ve.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:t3();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?vi.expand(t,Ve.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=Ve.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},Ve.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Of(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?ud(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?Aa.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(_i.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,ud(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??"",Ve.setIcon(this.milestonesButton,this.milestonesShown?Kt.MILESTONES_ON:Kt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=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=Xr(i,t),{lat:s,lng:r}=$s(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=Aa.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return li.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=Ve.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ve.setIcon(this.miniMuteButton,this.mutedState?Kt.MUTED:Kt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Ve.setIcon(this.muteButton,Kt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Ve.setIcon(this.muteButton,this.mutedState?Kt.MUTED:Kt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ve.setIcon(this.fullscreenButton,t?Kt.EXIT_FULLSCREEN:Kt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Qn(Ws.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=vo(Ws.preferencesFor(this),Mo);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await IT.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.videoButton&&(this.videoButton.messages=t),this.labelVideoButton(),this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=rE(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?K1(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 zo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?mb(pb(this.realStartMs+i)):zo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?zo(t):zo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return zo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return zo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?zo(this.currentSighting.timeline.duration):this.canShowClockTime?mb(pb(this.realStartMs+this.realDurationMs)):zo(this.realDurationMs)}}function pb(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function mb(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 zo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const uM="rr0-ufo";function e3(){customElements.get(uM)||customElements.define(uM,Ve)}const i3="timechange",q8="recordingissues",n3="minifiedreset",Z8=`
|
|
6819
6830
|
varying vec3 vDir;
|
|
6820
6831
|
varying vec3 vWorldDir;
|
|
6821
6832
|
|
|
@@ -7917,7 +7928,7 @@ uniform float aerialTexelM;`).replace("#include <emissivemap_fragment>",`#if def
|
|
|
7917
7928
|
gl_FragColor.rgb = gl_FragColor.rgb * aerialTransmittance + fogColor * (1.0 - aerialTransmittance);
|
|
7918
7929
|
#endif
|
|
7919
7930
|
#endif
|
|
7920
|
-
#endif`}}class sa{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?sa.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=sa.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)*sa.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)*sa.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*sa.METRES_PER_DEGREE/(n-1),c=Math.ceil(sa.ROUTE_CLEARANCE_M/r),l=Math.ceil(sa.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 w=0;w<=M;w++){const y=Math.round(p+(g-p)*w/M),x=Math.round(m+(v-m)*w/M);for(let b=-l;b<=l;b++)for(let E=-c;E<=c;E++){const S=x+b,A=y+E;S<0||A<0||S>=n||A>=i||Math.hypot(E*r,b*a)<=sa.ROUTE_CLEARANCE_M&&(h[S*i+A]=1)}}}return h}}const wN=64,bb=wN+1,t1=2048,xN=900,bN=700/900,SN=0,EN=.01,AN=1500;function bd(o,t,e){return{north:$s(0,-e,o,t).lat,south:$s(0,e,o,t).lat,east:$s(e,0,o,t).lng,west:$s(-e,0,o,t).lng}}async function e1(o,t,e,i=xN,n,s){const r=i,a=i*bN,c=bd(o,t,r),l={width:bb,height:bb},h=s||i>We.ROADS_MAX_RADIUS_M?void 0:e.water?.getWater(c).catch(P=>(console.warn("Water unavailable, drawing none:",P),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,l,n),e.imagery.getImageryTexture(c,{width:t1,height:t1})]);let f;const p=h?await Promise.race([h,new Promise(P=>{f=setTimeout(()=>P(void 0),AN)})]):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");sm.fill(u.heights,u.width),p&&p.length>0&&sa.flatten(u,p,n?.route);const m=u.width,g=m-1,v=Math.floor(m/2),M=u.heights[v*m+v],w=s?.referenceElevationM??M,y=new Float32Array(m*m*3),x=new Float32Array(m*m*2),b=new Float32Array(m*m*4);for(let P=0;P<m;P++){const N=P/(m-1),k=c.north+(c.south-c.north)*N;for(let B=0;B<m;B++){const W=B/(m-1),Q=c.west+(c.east-c.west)*W,{x:Z,z:nt}=re(k,Q,o,t),ot=u.heights[P*m+B],Ut=Math.max(Math.abs(Z),Math.abs(nt)),Zt=s&&Ut<s.innerM?0:1-_N((Ut-a)/(r-a),0,1),jt=SN+EN+(ot-w),K=P*m+B;y[K*3]=Z,y[K*3+1]=jt,y[K*3+2]=nt;const lt=YA(d.bounds,Q,k);x[K*2]=lt.x,x[K*2+1]=lt.y,b[K*4]=1,b[K*4+1]=1,b[K*4+2]=1,b[K*4+3]=Zt}}const E=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let S=0;for(let P=0;P<g;P++)for(let N=0;N<g;N++){const k=P*m+N,B=k+1,W=k+m,Q=W+1;E[S++]=k,E[S++]=W,E[S++]=B,E[S++]=B,E[S++]=W,E[S++]=Q}const A=new be;A.setAttribute("position",new ye(y,3)),A.setAttribute("uv",new ye(x,2)),A.setAttribute("color",new ye(b,4)),A.setIndex(new ye(E,1)),A.computeVertexNormals();const _=new Tc(d.source);_.flipY=!1,_.colorSpace=Bn,_.anisotropy=8;const I=new Rr({map:_,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||nu.install(I);const D=re(o,d.bounds.east,o,d.bounds.west).x;yc.ground(I,Math.abs(D)/t1);const O=new yt(A,I);return O.receiveShadow=!s,O.castShadow=!s,{mesh:O,attribution:e.imagery.attribution,originElevationM:Number.isFinite(M)?M:void 0,...p?{water:p}:h?{waterLater:h}:{}}}class sm{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<sm.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<sm.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 _N(o,t,e){return Math.max(t,Math.min(e,o))}class we{static STEP_M=8;stepM=we.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 Ke;surveyed=new Ke;stated=new Ke;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(we.STEP_M,Math.max(1.5,t/2)):we.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=we.within(t,e,i,r);we.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const l=new Map,h=c.map(f=>f.points.map(p=>re(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)??we.batchFor(p.surface);l.set(p.surface,m);const g=u[f];this.appendPath(h[f],p.widthM,n,m,g?{lateralAt:(v,M,w,y)=>g(v,M,w,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,we.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;(we.markingsModule??=at(()=>import("./RoadMarkings-CNLt-BEg.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:we.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,we.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=we.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,we.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=re(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=re(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=re(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=we.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=we.clearOf(l,t.widthM/2,Math.max(-2.5,Math.min(we.STREET_MIDDLE_MOST_M,h))),d={rungs:a,across:(f,p,m,g)=>we.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 we.betweenWalls(t,u,v.leftM,v.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+we.LAMP_CLEARANCE_M);if(n(i))return i;const s=we.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<=we.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(we.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<we.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+we.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-we.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+we.SIDEWALK_WIDTH_M,h=-(n??-c+we.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=we.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...c-h>=we.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:h}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new ra(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:we.LIFT_M+we.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){we.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??we.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(){we.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(){we.empty(this.surveyed),we.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??we.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,w=v.z-g.z;const y=Math.hypot(M,w);y<1e-6?(M=1,w=0):(M/=y,w/=y);const x=s.lateralAt?s.lateralAt(r[m].x,r[m].z,M,w):{offsetM:l,halfM:a},b=x?Math.max(s.minHalfM??.5,x.halfM):a,E=x?.offsetM??l,S=-w*b,A=M*b,_={x:r[m].x+-w*E,z:r[m].z+M*E};u.push(x!==void 0&&x.halfM>0&&!s.skip?.(_.x,_.z)),d.push([{x:_.x+S,z:_.z+A},_,{x:_.x-S,z:_.z-A}]),f.push(b)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const v=d[m][g],M=d[m+1][g],w=i((v.x+M.x)/2,(v.z+M.z)/2)-(p[m][g]+p[m+1][g])/2;w>0&&(p[m][g]+=w,p[m+1][g]+=w)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=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 w=e(v,M)+we.LIFT_M;i.positions.push(v,w,M,v,w+we.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 be;r.setAttribute("position",new ye(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new ye(new Float32Array(e.edges),2)),r.setIndex(new ye(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??we.ALBEDO[t],l=new Rr({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?we.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(l,we.GRAIN_CONTRAST[t],a);const h=new yt(r,l);return h.name=`roads ${t}`,h.renderOrder=we.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>
|
|
7931
|
+
#endif`}}class sa{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?sa.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=sa.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)*sa.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)*sa.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*sa.METRES_PER_DEGREE/(n-1),c=Math.ceil(sa.ROUTE_CLEARANCE_M/r),l=Math.ceil(sa.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 w=0;w<=M;w++){const y=Math.round(p+(g-p)*w/M),x=Math.round(m+(v-m)*w/M);for(let b=-l;b<=l;b++)for(let E=-c;E<=c;E++){const S=x+b,A=y+E;S<0||A<0||S>=n||A>=i||Math.hypot(E*r,b*a)<=sa.ROUTE_CLEARANCE_M&&(h[S*i+A]=1)}}}return h}}const wN=64,bb=wN+1,t1=2048,xN=900,bN=700/900,SN=0,EN=.01,AN=1500;function bd(o,t,e){return{north:$s(0,-e,o,t).lat,south:$s(0,e,o,t).lat,east:$s(e,0,o,t).lng,west:$s(-e,0,o,t).lng}}async function e1(o,t,e,i=xN,n,s){const r=i,a=i*bN,c=bd(o,t,r),l={width:bb,height:bb},h=s||i>We.ROADS_MAX_RADIUS_M?void 0:e.water?.getWater(c).catch(P=>(console.warn("Water unavailable, drawing none:",P),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,l,n),e.imagery.getImageryTexture(c,{width:t1,height:t1})]);let f;const p=h?await Promise.race([h,new Promise(P=>{f=setTimeout(()=>P(void 0),AN)})]):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");sm.fill(u.heights,u.width),p&&p.length>0&&sa.flatten(u,p,n?.route);const m=u.width,g=m-1,v=Math.floor(m/2),M=u.heights[v*m+v],w=s?.referenceElevationM??M,y=new Float32Array(m*m*3),x=new Float32Array(m*m*2),b=new Float32Array(m*m*4);for(let P=0;P<m;P++){const N=P/(m-1),k=c.north+(c.south-c.north)*N;for(let B=0;B<m;B++){const W=B/(m-1),Q=c.west+(c.east-c.west)*W,{x:Z,z:nt}=re(k,Q,o,t),ot=u.heights[P*m+B],Ut=Math.max(Math.abs(Z),Math.abs(nt)),Zt=s&&Ut<s.innerM?0:1-_N((Ut-a)/(r-a),0,1),jt=SN+EN+(ot-w),K=P*m+B;y[K*3]=Z,y[K*3+1]=jt,y[K*3+2]=nt;const lt=YA(d.bounds,Q,k);x[K*2]=lt.x,x[K*2+1]=lt.y,b[K*4]=1,b[K*4+1]=1,b[K*4+2]=1,b[K*4+3]=Zt}}const E=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let S=0;for(let P=0;P<g;P++)for(let N=0;N<g;N++){const k=P*m+N,B=k+1,W=k+m,Q=W+1;E[S++]=k,E[S++]=W,E[S++]=B,E[S++]=B,E[S++]=W,E[S++]=Q}const A=new be;A.setAttribute("position",new we(y,3)),A.setAttribute("uv",new we(x,2)),A.setAttribute("color",new we(b,4)),A.setIndex(new we(E,1)),A.computeVertexNormals();const _=new Tc(d.source);_.flipY=!1,_.colorSpace=Bn,_.anisotropy=8;const I=new Rr({map:_,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||nu.install(I);const D=re(o,d.bounds.east,o,d.bounds.west).x;yc.ground(I,Math.abs(D)/t1);const O=new yt(A,I);return O.receiveShadow=!s,O.castShadow=!s,{mesh:O,attribution:e.imagery.attribution,originElevationM:Number.isFinite(M)?M:void 0,...p?{water:p}:h?{waterLater:h}:{}}}class sm{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<sm.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<sm.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 _N(o,t,e){return Math.max(t,Math.min(e,o))}class xe{static STEP_M=8;stepM=xe.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 Ke;surveyed=new Ke;stated=new Ke;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(xe.STEP_M,Math.max(1.5,t/2)):xe.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=xe.within(t,e,i,r);xe.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const l=new Map,h=c.map(f=>f.points.map(p=>re(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)??xe.batchFor(p.surface);l.set(p.surface,m);const g=u[f];this.appendPath(h[f],p.widthM,n,m,g?{lateralAt:(v,M,w,y)=>g(v,M,w,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,xe.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;(xe.markingsModule??=at(()=>import("./RoadMarkings-CNLt-BEg.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:xe.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,xe.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=xe.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,xe.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=re(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=re(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=re(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=xe.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=xe.clearOf(l,t.widthM/2,Math.max(-2.5,Math.min(xe.STREET_MIDDLE_MOST_M,h))),d={rungs:a,across:(f,p,m,g)=>xe.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 xe.betweenWalls(t,u,v.leftM,v.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+xe.LAMP_CLEARANCE_M);if(n(i))return i;const s=xe.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<=xe.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(xe.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<xe.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+xe.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-xe.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+xe.SIDEWALK_WIDTH_M,h=-(n??-c+xe.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=xe.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...c-h>=xe.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:h}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new ra(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:xe.LIFT_M+xe.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){xe.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??xe.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(){xe.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(){xe.empty(this.surveyed),xe.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??xe.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,w=v.z-g.z;const y=Math.hypot(M,w);y<1e-6?(M=1,w=0):(M/=y,w/=y);const x=s.lateralAt?s.lateralAt(r[m].x,r[m].z,M,w):{offsetM:l,halfM:a},b=x?Math.max(s.minHalfM??.5,x.halfM):a,E=x?.offsetM??l,S=-w*b,A=M*b,_={x:r[m].x+-w*E,z:r[m].z+M*E};u.push(x!==void 0&&x.halfM>0&&!s.skip?.(_.x,_.z)),d.push([{x:_.x+S,z:_.z+A},_,{x:_.x-S,z:_.z-A}]),f.push(b)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const v=d[m][g],M=d[m+1][g],w=i((v.x+M.x)/2,(v.z+M.z)/2)-(p[m][g]+p[m+1][g])/2;w>0&&(p[m][g]+=w,p[m+1][g]+=w)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=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 w=e(v,M)+xe.LIFT_M;i.positions.push(v,w,M,v,w+xe.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 be;r.setAttribute("position",new we(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new we(new Float32Array(e.edges),2)),r.setIndex(new we(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??xe.ALBEDO[t],l=new Rr({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?xe.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(l,xe.GRAIN_CONTRAST[t],a);const h=new yt(r,l);return h.name=`roads ${t}`,h.renderOrder=xe.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>
|
|
7921
7932
|
varying vec2 vRoadXZ;
|
|
7922
7933
|
uniform vec2 uRoadOrigin;
|
|
7923
7934
|
#ifdef ROAD_VERGE
|
|
@@ -8080,7 +8091,7 @@ void main() {
|
|
|
8080
8091
|
float blur = max(vNearBlur, vHaze);
|
|
8081
8092
|
gl_FragColor = vec4(color, tex.a * uOpacity * vNearFade * (1.0 - blur * ${ON.toFixed(2)}));
|
|
8082
8093
|
}
|
|
8083
|
-
`;function FN(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}const UN=.14,_b=2.25;let Ep;function zN(){if(Ep)return Ep;const o=128,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createImageData(o,o),n=o/2,s=o*UN,r=o-s;for(let a=0;a<o;a++)for(let c=0;c<o;c++){const l=c+.5-n,h=a+.5<s?a+.5-s:a+.5>r?a+.5-r:0,u=Math.hypot(l,h),d=Math.exp(-(u*u)/(2*_b*_b)),f=(a*o+c)*4;i.data[f]=255,i.data[f+1]=255,i.data[f+2]=255,i.data[f+3]=Math.round(255*Math.min(1,d))}return e.putImageData(i,0,0),Ep=new Tc(t),Ep}function BN(o){const t=FN(o.seed),e=new Float32Array(o.count*3),i=new Float32Array(o.count),n=o.radiusM;for(let l=0;l<o.count;l++){const h=t()*Math.PI*2,u=Math.sqrt(t())*o.radiusM;e[l*3]=Math.cos(h)*u,e[l*3+1]=t()*o.heightM,e[l*3+2]=Math.sin(h)*u,i[l]=.85+t()*.3}const s=new be;s.setAttribute("position",new ye(e,3)),s.setAttribute("aSpeed",new ye(i,1)),s.setDrawRange(0,o.visibleCount);const r={uTime:{value:0},uOverallSpeed:{value:o.overallSpeed},uPixelSize:{value:o.pixelSize},uOpacity:{value:o.opacity},uColor:{value:o.color},uUvSquash:{value:1},uSpeedStreak:{value:o.speedStreak},uWindOffset:{value:new tt(0,0)},uDropVelocity:{value:new T(0,-1,0)},uAspect:{value:1},uHeight:{value:o.heightM},uBottomY:{value:o.bottomYM},uHalfWidth:{value:n},uTexture:{value:zN()},uNearFocusDistance:{value:o.nearFocusDistanceM},uHazeDistance:{value:o.hazeDistanceM},uHazeColor:{value:o.hazeColor}},a=new De({uniforms:r,vertexShader:LN,fragmentShader:kN,transparent:!0,depthWrite:!1,depthTest:!0}),c=new ir(s,a);return c.frustumCulled=!1,{points:c,uniforms:r}}class Sl{static S10_MAG_PER_ARCSEC2=10+2.5*Math.log10(3600*3600);static toMagPerArcsec2(t){return Sl.S10_MAG_PER_ARCSEC2-2.5*Math.log10(Math.max(t,1e-12))}static fromMagPerArcsec2(t){return 10**(.4*(Sl.S10_MAG_PER_ARCSEC2-t))}static latitudeOfRowCoord(t){const e=2*t-1;return 90*Math.sign(e)*e*e}static rowCoordOfLatitude(t){return(Math.sign(t)*Math.sqrt(Math.min(Math.abs(t),90)/90)+1)/2}static angleOfColumnCoord(t){return 180*t*t}static columnCoordOfAngle(t){return Math.sqrt(Math.min(Math.max(t,0),180)/180)}}class Ue{static LONGITUDE_STEPS=256;static LATITUDE_STEPS=128;static SUN_RADIUS_KPC=8.2;static SUN_HEIGHT_KPC=.02;static DISK_SCALE_LENGTH_KPC=2.6;static DISK_SCALE_HEIGHT_KPC=.3;static BULGE_SCALE_KPC=.5;static BULGE_FLATTENING=.6;static BULGE_TO_LOCAL_DISK=20;static DUST_SCALE_LENGTH_KPC=3.5;static DUST_SCALE_HEIGHT_KPC=.1;static EXTINCTION_MAG_PER_KPC=.8;static NEAR_LIMIT_KPC=.01;static FAR_LIMIT_KPC=40;static STEPS=192;static OPAQUE_MAG=15;static PEAK_MAG_PER_ARCSEC2=21;static PEAK_RADIANCE=6.278;static PEAK_LONGITUDE_DEG=0;static PEAK_LATITUDE_DEG=4.5;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*Ue.anchor()}static anchor(){return Sl.fromMagPerArcsec2(Ue.PEAK_MAG_PER_ARCSEC2)/Ue.PEAK_RADIANCE}radianceTowards(t,e){return this.trace(t,e).light}extinctionTowards(t,e){return this.trace(t,e).extinctionMag}trace(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=Math.cos(n)*Math.sin(i),a=Math.sin(n);let c=0,l=0,h=0;const u=Math.log(Ue.NEAR_LIMIT_KPC),d=Math.log(Ue.FAR_LIMIT_KPC)-u;for(let f=0;f<Ue.STEPS;f++){const p=Math.exp(u+d*f/(Ue.STEPS-1)),m=p-h;h=p;const g=p-m/2,v=Ue.SUN_RADIUS_KPC+g*s,M=g*r,w=Ue.SUN_HEIGHT_KPC+g*a,y=Math.hypot(v,M),x=Math.exp(-(y-Ue.SUN_RADIUS_KPC)/Ue.DISK_SCALE_LENGTH_KPC-Math.abs(w)/Ue.DISK_SCALE_HEIGHT_KPC),b=Math.hypot(y,w/Ue.BULGE_FLATTENING),E=Ue.BULGE_TO_LOCAL_DISK*Math.exp(-b/Ue.BULGE_SCALE_KPC);if(c+=(x+E)*m*10**(-.4*l),l+=Ue.EXTINCTION_MAG_PER_KPC*Math.exp(-(y-Ue.SUN_RADIUS_KPC)/Ue.DUST_SCALE_LENGTH_KPC-(Math.abs(w)-Ue.SUN_HEIGHT_KPC)/Ue.DUST_SCALE_HEIGHT_KPC)*m,l>Ue.OPAQUE_MAG)break}return{light:c,extinctionMag:l}}values=new Float32Array(Ue.LONGITUDE_STEPS*Ue.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Ue.LATITUDE_STEPS}walk(t){const e=Ue.LONGITUDE_STEPS,i=Math.min(Ue.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Sl.latitudeOfRowCoord((this.walked+.5)/Ue.LATITUDE_STEPS);for(let s=0;s<e;s++)this.values[this.walked*e+s]=this.radianceTowards(360*(s+.5)/e,n)}}harvest(){let t=Number.POSITIVE_INFINITY;for(const n of this.values)n<t&&(t=n);const e=Ue.anchor(),i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-t)*e;return{width:Ue.LONGITUDE_STEPS,height:Ue.LATITUDE_STEPS,data:i}}}class Wi{static LONGITUDE_STEPS=128;static LATITUDE_STEPS=96;static RADIAL_FALLOFF=1.3;static FAN_EXPONENT=2.6;static SUBLIMATION_AU=.1;static NEAR_LIMIT_AU=.004;static FAR_LIMIT_AU=8;static STEPS=224;static LOBE_ASYMMETRY=[.7,-.2,-.81];static LOBE_WEIGHT=[.665,.33,.00541];static RIGHT_ANGLE_S10=200;static POLE_S10=77;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*this.anchor()}anchored;anchor(){return this.anchored===void 0&&(this.anchored=Wi.RIGHT_ANGLE_S10/this.radianceTowards(90,0)),this.anchored}radianceTowards(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=-Math.cos(n)*Math.sin(i),a=Math.sin(n),c=-s;let l=0,h=0;const u=Math.log(Wi.NEAR_LIMIT_AU),d=Math.log(Wi.FAR_LIMIT_AU)-u;for(let f=0;f<Wi.STEPS;f++){const p=Math.exp(u+d*f/(Wi.STEPS-1)),m=p-h;h=p;const g=p-m/2,v=1+g*s,M=g*r,w=g*a,y=Math.hypot(v,M,w);if(y<Wi.SUBLIMATION_AU)continue;const x=w/y,b=y**-1.3*Math.exp(-2.6*Math.abs(x)),E=(c-g)/y;l+=b*this.scattering(E)*m/(y*y)}return l}scattering(t){let e=0;for(let i=0;i<Wi.LOBE_ASYMMETRY.length;i++){const n=Wi.LOBE_ASYMMETRY[i],s=1+n*n-2*n*t;e+=Wi.LOBE_WEIGHT[i]*(1-n*n)/(4*Math.PI*s**1.5)}return e}values=new Float32Array(Wi.LONGITUDE_STEPS*Wi.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Wi.LATITUDE_STEPS}walk(t){const e=Wi.LONGITUDE_STEPS,i=Math.min(Wi.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Sl.latitudeOfRowCoord((this.walked+.5)/Wi.LATITUDE_STEPS);for(let s=0;s<e;s++){const r=Sl.angleOfColumnCoord((s+.5)/e);this.values[this.walked*e+s]=this.radianceTowards(r,n)}}}harvest(){const t=this.anchor();let e=Number.POSITIVE_INFINITY;for(const n of this.values)n<e&&(e=n);const i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-e)*t;return{width:Wi.LONGITUDE_STEPS,height:Wi.LATITUDE_STEPS,data:i}}}class _t{static get NANOLAMBERTS_PER_S10(){return _t.toNanolamberts(10+2.5*Math.log10(3600*3600))}static nanolambertsOfS10(t){return t*_t.NANOLAMBERTS_PER_S10}static TWILIGHT=[{sunAltitudeDeg:90,magPerArcsec2:3.5},{sunAltitudeDeg:10,magPerArcsec2:4.2},{sunAltitudeDeg:0,magPerArcsec2:7.5},...Array.from({length:15},(t,e)=>{const i=-4-e;return{sunAltitudeDeg:i,magPerArcsec2:_t.patatV(i)}}),{sunAltitudeDeg:-24,magPerArcsec2:22}];static patatV(t){const e=90-t-95;return 11.84+1.518*e-.057*e*e}static moonlessMagPerArcsec2(t){const e=_t.TWILIGHT;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t<=n.sunAltitudeDeg&&t>=s.sunAltitudeDeg){const r=(n.sunAltitudeDeg-t)/(n.sunAltitudeDeg-s.sunAltitudeDeg);return n.magPerArcsec2+(s.magPerArcsec2-n.magPerArcsec2)*r}}return t>0?e[0].magPerArcsec2:e[e.length-1].magPerArcsec2}static toNanolamberts(t){return 34.08*Math.exp(_t.NANOLAMBERT_OFFSET-_t.PER_MAGNITUDE*t)}static fromNanolamberts(t){return(_t.NANOLAMBERT_OFFSET-Math.log(Math.max(t,1e-6)/34.08))/_t.PER_MAGNITUDE}static NANOLAMBERT_OFFSET=20.7233;static PER_MAGNITUDE=Math.LN10/2.5;static airMass(t){const e=Math.cos(Math.max(t,0)*Math.PI/180);return 1/Math.sqrt(Math.max(1-.96*e*e,.001))}static EXTINCTION_PER_AIR_MASS=.172;static scatteringAt(t){const e=Math.min(Math.max(t,0),180)*Math.PI/180;return 10**5.36*(1.06+Math.cos(e)**2)+10**(6.15-Math.min(t,180)/40)}static scatteredFraction(t){return 1-10**(-.4*_t.EXTINCTION_PER_AIR_MASS*_t.airMass(t))}static AIRGLOW_MAG_PER_ARCSEC2=22;static twilightExcessNanolamberts(t){return Math.max(0,_t.toNanolamberts(_t.moonlessMagPerArcsec2(t))-_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2))}static twilightOutput(t){const e=_t.scatteringAt(90-t)*_t.scatteredFraction(90);return _t.twilightExcessNanolamberts(t)/e}static moonNanolamberts(t,e,i,n){return _t.scatteringAt(i)*_t.moonOutput(t,e)*_t.scatteredFraction(n)}static moonOutput(t,e){if(e<=0)return 0;const i=Math.min(Math.abs(t),180);return 10**(-.4*(3.84+.026*i+4e-9*i**4))*10**(-.4*_t.EXTINCTION_PER_AIR_MASS*_t.airMass(e))}static phaseAngleOf(t){return Math.acos(Math.min(Math.max(2*t-1,-1),1))*180/Math.PI}static magPerArcsec2(t,e,i,n){const s=_t.scatteredFraction(i),r=_t.scatteringAt(t.separationDeg)*_t.twilightOutput(t.altitudeDeg)*s,a=_t.scatteringAt(e.separationDeg)*_t.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*s;return _t.fromNanolamberts(_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2)+r+a+_t.artificialNanolamberts(n,i))}static artificialZenithNanolamberts(t){return t===void 0||!Number.isFinite(t)?0:Math.max(0,_t.toNanolamberts(t)-_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2))}static artificialNanolamberts(t,e){const i=_t.artificialZenithNanolamberts(t);return i>0?i*_t.artificialShape(e):0}static artificialShape(t){return _t.scatteredFraction(t)/_t.scatteredFraction(90)}static nakedEyeLimit(t){return 7.93-5*Math.log10(10**(4.316-t/5)+1)}static starLossMagnitudes(t,e,i){const n=_t.moonlessMagPerArcsec2(t),s=_t.fromNanolamberts(_t.toNanolamberts(n)+_t.scatteringAt(90-e.altitudeDeg)*_t.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*_t.scatteredFraction(90)+_t.artificialZenithNanolamberts(i));return Math.max(0,_t.nakedEyeLimit(n)-_t.nakedEyeLimit(s))}}class rm{static HALF_FLOAT_MAX=65504;static fromMap(t,e){const i=Gn.toHalfFloat(1);for(let n=0;n<t.data.length;n++)e[n*4]=Gn.toHalfFloat(Math.min(rm.HALF_FLOAT_MAX,_t.nanolambertsOfS10(t.data[n]))),e[n*4+3]=i}}class sc{static pool=typeof Worker>"u"?null:void 0;static with(t,e){const i=sc.pool;if(i===null){e();return}if(i){t(i);return}at(async()=>{const{OffThreadTracer:n}=await import("./OffThreadTracer-ByPLWaYU.js");return{OffThreadTracer:n}},[],import.meta.url).then(({OffThreadTracer:n})=>{sc.pool=n.get(),sc.pool?t(sc.pool):e()},()=>{sc.pool=null,e()})}}class qo{static RADIUS=890;static TOO_BRIGHT_MAG_PER_ARCSEC2=16;static MILKY_WAY_TINT=[.9,.94,1];static ZODIACAL_TINT=[1,.97,.9];object;material;maps=Sd.shared;milkyWayTexture;zodiacalTexture;milkyWayTexels;zodiacalTexels;repaint;constructor(){this.milkyWayTexels=this.maps.milkyWayTexels,this.milkyWayTexture=qo.buildTexture(this.milkyWayTexels,Ue.LONGITUDE_STEPS,Ue.LATITUDE_STEPS,bc),this.zodiacalTexels=this.maps.zodiacalTexels,this.zodiacalTexture=qo.buildTexture(this.zodiacalTexels,Wi.LONGITUDE_STEPS,Wi.LATITUDE_STEPS,Qi),this.material=new De({uniforms:{uMilkyWay:{value:this.milkyWayTexture},uZodiacal:{value:this.zodiacalTexture},uGalactic:{value:new de},uEclipticPole:{value:new T(0,1,0)},uSunLongitude:{value:new T(1,0,0)},uMoonDirection:{value:new T(0,-1,0)},uMoonOutput:{value:0},uSunDirection:{value:new T(0,-1,0)},uTwilightOutput:{value:0},uAirglowNanolamberts:{value:_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2)},uArtificialNanolamberts:{value:0},uSkyColor:{value:new T(0,0,0)},uMilkyWayTint:{value:new T(...qo.MILKY_WAY_TINT)},uZodiacalTint:{value:new T(...qo.ZODIACAL_TINT)},uReady:{value:0},uEncodeDestination:{value:1}},vertexShader:`
|
|
8094
|
+
`;function FN(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}const UN=.14,_b=2.25;let Ep;function zN(){if(Ep)return Ep;const o=128,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createImageData(o,o),n=o/2,s=o*UN,r=o-s;for(let a=0;a<o;a++)for(let c=0;c<o;c++){const l=c+.5-n,h=a+.5<s?a+.5-s:a+.5>r?a+.5-r:0,u=Math.hypot(l,h),d=Math.exp(-(u*u)/(2*_b*_b)),f=(a*o+c)*4;i.data[f]=255,i.data[f+1]=255,i.data[f+2]=255,i.data[f+3]=Math.round(255*Math.min(1,d))}return e.putImageData(i,0,0),Ep=new Tc(t),Ep}function BN(o){const t=FN(o.seed),e=new Float32Array(o.count*3),i=new Float32Array(o.count),n=o.radiusM;for(let l=0;l<o.count;l++){const h=t()*Math.PI*2,u=Math.sqrt(t())*o.radiusM;e[l*3]=Math.cos(h)*u,e[l*3+1]=t()*o.heightM,e[l*3+2]=Math.sin(h)*u,i[l]=.85+t()*.3}const s=new be;s.setAttribute("position",new we(e,3)),s.setAttribute("aSpeed",new we(i,1)),s.setDrawRange(0,o.visibleCount);const r={uTime:{value:0},uOverallSpeed:{value:o.overallSpeed},uPixelSize:{value:o.pixelSize},uOpacity:{value:o.opacity},uColor:{value:o.color},uUvSquash:{value:1},uSpeedStreak:{value:o.speedStreak},uWindOffset:{value:new tt(0,0)},uDropVelocity:{value:new T(0,-1,0)},uAspect:{value:1},uHeight:{value:o.heightM},uBottomY:{value:o.bottomYM},uHalfWidth:{value:n},uTexture:{value:zN()},uNearFocusDistance:{value:o.nearFocusDistanceM},uHazeDistance:{value:o.hazeDistanceM},uHazeColor:{value:o.hazeColor}},a=new De({uniforms:r,vertexShader:LN,fragmentShader:kN,transparent:!0,depthWrite:!1,depthTest:!0}),c=new ir(s,a);return c.frustumCulled=!1,{points:c,uniforms:r}}class Sl{static S10_MAG_PER_ARCSEC2=10+2.5*Math.log10(3600*3600);static toMagPerArcsec2(t){return Sl.S10_MAG_PER_ARCSEC2-2.5*Math.log10(Math.max(t,1e-12))}static fromMagPerArcsec2(t){return 10**(.4*(Sl.S10_MAG_PER_ARCSEC2-t))}static latitudeOfRowCoord(t){const e=2*t-1;return 90*Math.sign(e)*e*e}static rowCoordOfLatitude(t){return(Math.sign(t)*Math.sqrt(Math.min(Math.abs(t),90)/90)+1)/2}static angleOfColumnCoord(t){return 180*t*t}static columnCoordOfAngle(t){return Math.sqrt(Math.min(Math.max(t,0),180)/180)}}class Ue{static LONGITUDE_STEPS=256;static LATITUDE_STEPS=128;static SUN_RADIUS_KPC=8.2;static SUN_HEIGHT_KPC=.02;static DISK_SCALE_LENGTH_KPC=2.6;static DISK_SCALE_HEIGHT_KPC=.3;static BULGE_SCALE_KPC=.5;static BULGE_FLATTENING=.6;static BULGE_TO_LOCAL_DISK=20;static DUST_SCALE_LENGTH_KPC=3.5;static DUST_SCALE_HEIGHT_KPC=.1;static EXTINCTION_MAG_PER_KPC=.8;static NEAR_LIMIT_KPC=.01;static FAR_LIMIT_KPC=40;static STEPS=192;static OPAQUE_MAG=15;static PEAK_MAG_PER_ARCSEC2=21;static PEAK_RADIANCE=6.278;static PEAK_LONGITUDE_DEG=0;static PEAK_LATITUDE_DEG=4.5;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*Ue.anchor()}static anchor(){return Sl.fromMagPerArcsec2(Ue.PEAK_MAG_PER_ARCSEC2)/Ue.PEAK_RADIANCE}radianceTowards(t,e){return this.trace(t,e).light}extinctionTowards(t,e){return this.trace(t,e).extinctionMag}trace(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=Math.cos(n)*Math.sin(i),a=Math.sin(n);let c=0,l=0,h=0;const u=Math.log(Ue.NEAR_LIMIT_KPC),d=Math.log(Ue.FAR_LIMIT_KPC)-u;for(let f=0;f<Ue.STEPS;f++){const p=Math.exp(u+d*f/(Ue.STEPS-1)),m=p-h;h=p;const g=p-m/2,v=Ue.SUN_RADIUS_KPC+g*s,M=g*r,w=Ue.SUN_HEIGHT_KPC+g*a,y=Math.hypot(v,M),x=Math.exp(-(y-Ue.SUN_RADIUS_KPC)/Ue.DISK_SCALE_LENGTH_KPC-Math.abs(w)/Ue.DISK_SCALE_HEIGHT_KPC),b=Math.hypot(y,w/Ue.BULGE_FLATTENING),E=Ue.BULGE_TO_LOCAL_DISK*Math.exp(-b/Ue.BULGE_SCALE_KPC);if(c+=(x+E)*m*10**(-.4*l),l+=Ue.EXTINCTION_MAG_PER_KPC*Math.exp(-(y-Ue.SUN_RADIUS_KPC)/Ue.DUST_SCALE_LENGTH_KPC-(Math.abs(w)-Ue.SUN_HEIGHT_KPC)/Ue.DUST_SCALE_HEIGHT_KPC)*m,l>Ue.OPAQUE_MAG)break}return{light:c,extinctionMag:l}}values=new Float32Array(Ue.LONGITUDE_STEPS*Ue.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Ue.LATITUDE_STEPS}walk(t){const e=Ue.LONGITUDE_STEPS,i=Math.min(Ue.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Sl.latitudeOfRowCoord((this.walked+.5)/Ue.LATITUDE_STEPS);for(let s=0;s<e;s++)this.values[this.walked*e+s]=this.radianceTowards(360*(s+.5)/e,n)}}harvest(){let t=Number.POSITIVE_INFINITY;for(const n of this.values)n<t&&(t=n);const e=Ue.anchor(),i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-t)*e;return{width:Ue.LONGITUDE_STEPS,height:Ue.LATITUDE_STEPS,data:i}}}class Wi{static LONGITUDE_STEPS=128;static LATITUDE_STEPS=96;static RADIAL_FALLOFF=1.3;static FAN_EXPONENT=2.6;static SUBLIMATION_AU=.1;static NEAR_LIMIT_AU=.004;static FAR_LIMIT_AU=8;static STEPS=224;static LOBE_ASYMMETRY=[.7,-.2,-.81];static LOBE_WEIGHT=[.665,.33,.00541];static RIGHT_ANGLE_S10=200;static POLE_S10=77;surfaceBrightnessS10(t,e){return this.radianceTowards(t,e)*this.anchor()}anchored;anchor(){return this.anchored===void 0&&(this.anchored=Wi.RIGHT_ANGLE_S10/this.radianceTowards(90,0)),this.anchored}radianceTowards(t,e){const i=t*Math.PI/180,n=e*Math.PI/180,s=-Math.cos(n)*Math.cos(i),r=-Math.cos(n)*Math.sin(i),a=Math.sin(n),c=-s;let l=0,h=0;const u=Math.log(Wi.NEAR_LIMIT_AU),d=Math.log(Wi.FAR_LIMIT_AU)-u;for(let f=0;f<Wi.STEPS;f++){const p=Math.exp(u+d*f/(Wi.STEPS-1)),m=p-h;h=p;const g=p-m/2,v=1+g*s,M=g*r,w=g*a,y=Math.hypot(v,M,w);if(y<Wi.SUBLIMATION_AU)continue;const x=w/y,b=y**-1.3*Math.exp(-2.6*Math.abs(x)),E=(c-g)/y;l+=b*this.scattering(E)*m/(y*y)}return l}scattering(t){let e=0;for(let i=0;i<Wi.LOBE_ASYMMETRY.length;i++){const n=Wi.LOBE_ASYMMETRY[i],s=1+n*n-2*n*t;e+=Wi.LOBE_WEIGHT[i]*(1-n*n)/(4*Math.PI*s**1.5)}return e}values=new Float32Array(Wi.LONGITUDE_STEPS*Wi.LATITUDE_STEPS);walked=0;get done(){return this.walked>=Wi.LATITUDE_STEPS}walk(t){const e=Wi.LONGITUDE_STEPS,i=Math.min(Wi.LATITUDE_STEPS,this.walked+t);for(;this.walked<i;this.walked++){const n=Sl.latitudeOfRowCoord((this.walked+.5)/Wi.LATITUDE_STEPS);for(let s=0;s<e;s++){const r=Sl.angleOfColumnCoord((s+.5)/e);this.values[this.walked*e+s]=this.radianceTowards(r,n)}}}harvest(){const t=this.anchor();let e=Number.POSITIVE_INFINITY;for(const n of this.values)n<e&&(e=n);const i=new Float32Array(this.values.length);for(let n=0;n<i.length;n++)i[n]=(this.values[n]-e)*t;return{width:Wi.LONGITUDE_STEPS,height:Wi.LATITUDE_STEPS,data:i}}}class _t{static get NANOLAMBERTS_PER_S10(){return _t.toNanolamberts(10+2.5*Math.log10(3600*3600))}static nanolambertsOfS10(t){return t*_t.NANOLAMBERTS_PER_S10}static TWILIGHT=[{sunAltitudeDeg:90,magPerArcsec2:3.5},{sunAltitudeDeg:10,magPerArcsec2:4.2},{sunAltitudeDeg:0,magPerArcsec2:7.5},...Array.from({length:15},(t,e)=>{const i=-4-e;return{sunAltitudeDeg:i,magPerArcsec2:_t.patatV(i)}}),{sunAltitudeDeg:-24,magPerArcsec2:22}];static patatV(t){const e=90-t-95;return 11.84+1.518*e-.057*e*e}static moonlessMagPerArcsec2(t){const e=_t.TWILIGHT;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t<=n.sunAltitudeDeg&&t>=s.sunAltitudeDeg){const r=(n.sunAltitudeDeg-t)/(n.sunAltitudeDeg-s.sunAltitudeDeg);return n.magPerArcsec2+(s.magPerArcsec2-n.magPerArcsec2)*r}}return t>0?e[0].magPerArcsec2:e[e.length-1].magPerArcsec2}static toNanolamberts(t){return 34.08*Math.exp(_t.NANOLAMBERT_OFFSET-_t.PER_MAGNITUDE*t)}static fromNanolamberts(t){return(_t.NANOLAMBERT_OFFSET-Math.log(Math.max(t,1e-6)/34.08))/_t.PER_MAGNITUDE}static NANOLAMBERT_OFFSET=20.7233;static PER_MAGNITUDE=Math.LN10/2.5;static airMass(t){const e=Math.cos(Math.max(t,0)*Math.PI/180);return 1/Math.sqrt(Math.max(1-.96*e*e,.001))}static EXTINCTION_PER_AIR_MASS=.172;static scatteringAt(t){const e=Math.min(Math.max(t,0),180)*Math.PI/180;return 10**5.36*(1.06+Math.cos(e)**2)+10**(6.15-Math.min(t,180)/40)}static scatteredFraction(t){return 1-10**(-.4*_t.EXTINCTION_PER_AIR_MASS*_t.airMass(t))}static AIRGLOW_MAG_PER_ARCSEC2=22;static twilightExcessNanolamberts(t){return Math.max(0,_t.toNanolamberts(_t.moonlessMagPerArcsec2(t))-_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2))}static twilightOutput(t){const e=_t.scatteringAt(90-t)*_t.scatteredFraction(90);return _t.twilightExcessNanolamberts(t)/e}static moonNanolamberts(t,e,i,n){return _t.scatteringAt(i)*_t.moonOutput(t,e)*_t.scatteredFraction(n)}static moonOutput(t,e){if(e<=0)return 0;const i=Math.min(Math.abs(t),180);return 10**(-.4*(3.84+.026*i+4e-9*i**4))*10**(-.4*_t.EXTINCTION_PER_AIR_MASS*_t.airMass(e))}static phaseAngleOf(t){return Math.acos(Math.min(Math.max(2*t-1,-1),1))*180/Math.PI}static magPerArcsec2(t,e,i,n){const s=_t.scatteredFraction(i),r=_t.scatteringAt(t.separationDeg)*_t.twilightOutput(t.altitudeDeg)*s,a=_t.scatteringAt(e.separationDeg)*_t.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*s;return _t.fromNanolamberts(_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2)+r+a+_t.artificialNanolamberts(n,i))}static artificialZenithNanolamberts(t){return t===void 0||!Number.isFinite(t)?0:Math.max(0,_t.toNanolamberts(t)-_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2))}static artificialNanolamberts(t,e){const i=_t.artificialZenithNanolamberts(t);return i>0?i*_t.artificialShape(e):0}static artificialShape(t){return _t.scatteredFraction(t)/_t.scatteredFraction(90)}static nakedEyeLimit(t){return 7.93-5*Math.log10(10**(4.316-t/5)+1)}static starLossMagnitudes(t,e,i){const n=_t.moonlessMagPerArcsec2(t),s=_t.fromNanolamberts(_t.toNanolamberts(n)+_t.scatteringAt(90-e.altitudeDeg)*_t.moonOutput(e.phaseAngleDeg,e.altitudeDeg)*_t.scatteredFraction(90)+_t.artificialZenithNanolamberts(i));return Math.max(0,_t.nakedEyeLimit(n)-_t.nakedEyeLimit(s))}}class rm{static HALF_FLOAT_MAX=65504;static fromMap(t,e){const i=Gn.toHalfFloat(1);for(let n=0;n<t.data.length;n++)e[n*4]=Gn.toHalfFloat(Math.min(rm.HALF_FLOAT_MAX,_t.nanolambertsOfS10(t.data[n]))),e[n*4+3]=i}}class sc{static pool=typeof Worker>"u"?null:void 0;static with(t,e){const i=sc.pool;if(i===null){e();return}if(i){t(i);return}at(async()=>{const{OffThreadTracer:n}=await import("./OffThreadTracer-ByPLWaYU.js");return{OffThreadTracer:n}},[],import.meta.url).then(({OffThreadTracer:n})=>{sc.pool=n.get(),sc.pool?t(sc.pool):e()},()=>{sc.pool=null,e()})}}class qo{static RADIUS=890;static TOO_BRIGHT_MAG_PER_ARCSEC2=16;static MILKY_WAY_TINT=[.9,.94,1];static ZODIACAL_TINT=[1,.97,.9];object;material;maps=Sd.shared;milkyWayTexture;zodiacalTexture;milkyWayTexels;zodiacalTexels;repaint;constructor(){this.milkyWayTexels=this.maps.milkyWayTexels,this.milkyWayTexture=qo.buildTexture(this.milkyWayTexels,Ue.LONGITUDE_STEPS,Ue.LATITUDE_STEPS,bc),this.zodiacalTexels=this.maps.zodiacalTexels,this.zodiacalTexture=qo.buildTexture(this.zodiacalTexels,Wi.LONGITUDE_STEPS,Wi.LATITUDE_STEPS,Qi),this.material=new De({uniforms:{uMilkyWay:{value:this.milkyWayTexture},uZodiacal:{value:this.zodiacalTexture},uGalactic:{value:new de},uEclipticPole:{value:new T(0,1,0)},uSunLongitude:{value:new T(1,0,0)},uMoonDirection:{value:new T(0,-1,0)},uMoonOutput:{value:0},uSunDirection:{value:new T(0,-1,0)},uTwilightOutput:{value:0},uAirglowNanolamberts:{value:_t.toNanolamberts(_t.AIRGLOW_MAG_PER_ARCSEC2)},uArtificialNanolamberts:{value:0},uSkyColor:{value:new T(0,0,0)},uMilkyWayTint:{value:new T(...qo.MILKY_WAY_TINT)},uZodiacalTint:{value:new T(...qo.ZODIACAL_TINT)},uReady:{value:0},uEncodeDestination:{value:1}},vertexShader:`
|
|
8084
8095
|
varying vec3 vDirection;
|
|
8085
8096
|
void main() {
|
|
8086
8097
|
vDirection = normalize((modelMatrix * vec4(position, 1.0)).xyz - cameraPosition);
|
|
@@ -8913,7 +8924,7 @@ ${Vt.OUTPUT_PROJECTION_GLSL}`)}}class rs{constructor(t,e){this.width=t,this.heig
|
|
|
8913
8924
|
vec3 laid = overlay.a > 0.001 ? finish(vec3(0.0), vec4(overlay.rgb / overlay.a, 1.0)) : vec3(0.0);
|
|
8914
8925
|
gl_FragColor = vec4(mix(shown, laid, overlay.a), 1.0);
|
|
8915
8926
|
}
|
|
8916
|
-
`,blending:Ys,depthTest:!1,depthWrite:!1}),this.quad=new yt(new vs(2,2),this.copyMaterial),this.quadScene.add(this.quad)}setFilmPrint(t,e,i,n=!1){const s=this.developMaterial.uniforms;if(s.uMonochrome.value=n?1:0,s.uPrintOn.value=t?1:0,!t)return;const r=Sa.frame(t,Sa.frameAt(t,e));s.uPrintContrast.value=t.contrast,s.uPrintTint.value.set(...t.tint),s.uPrintSoftness.value=t.softness,s.uPrintWeave.value.set(...r.weave),s.uPrintGrain.value=t.grain,s.uPrintSeed.value=r.seed,s.uPrintAspect.value=i,s.uPrintSpecks.value.forEach((c,l)=>{const h=r.specks[l];c.set(h?.u??0,h?.v??0,h?.radius??0,h?.kept??1)})}develop(t,e,i,n=1,s,r=!0){const a=t.getRenderTarget();this.readable=r,this.copyMaterial.uniforms.uSource.value=e.scene.texture,this.copyMaterial.uniforms.uGain.value=n,this.draw(t,this.copyMaterial,this.mips);const c=this.ghostMaterial.uniforms;c.uSize.value.set(this.mips.width,this.mips.height);const l=Math.min(i.ghosts.length,Di.MAX_GHOSTS);c.uCount.value=l;for(let m=0;m<l;m++){const g=i.ghosts[m];c.uScale.value[m]=g.scale||1,c.uShare.value[m]=g.share,c.uBlur.value[m]=g.blur,c.uKind.value[m]=g.cause==="drops"?2:ke.scatters(g)?1:0,c.uOffset.value[m].set(g.offset?.[0]??0,g.offset?.[1]??0),c.uTint.value[m].set(...g.tint??[1,1,1])}const h=i.ghosts.slice(0,l).find(m=>m.cause==="drops");h&&this.blurHalo(t,h.blur),c.uBlades.value=i.blades,c.uBladeAngle.value=i.bladeAngleRad,c.uDrops.value=i.drops,c.uImpacts.value=i.impacts;const u=c.uHistory.value;for(let m=0;m<u.length;m++)u[m]=i.history[m]??0;c.uStill.value=i.still?1:0,c.uRunning.value=i.running;const d=i.placed.slice(0,Di.MAX_PLACED_DROPS);c.uPlacedCount.value=d.length,d.forEach((m,g)=>c.uPlaced.value[g].set(m.x,1-m.y,m.radius)),c.uBright.value.set(((s?.x??0)+1)/2,((s?.y??0)+1)/2),c.uBrightRadius.value=s?.radius??0;const f=s?.flux??[0,0,0];c.uBrightFlux.value.set(f[0]*n,f[1]*n,f[2]*n),this.draw(t,this.ghostMaterial,this.ghostLayer);const p=this.developMaterial.uniforms;p.uSource.value=e.scene.texture,p.uOverlay.value=e.overlay.texture,p.uGain.value=n,p.uKept.value=1-i.scattered,this.draw(t,this.developMaterial,a)}pickAt(t,e,i,n,s,r){const a=this.mips.width,c=this.mips.height,l=(f,p)=>({x:Math.round((f+1)/2*a),y:Math.round((p+1)/2*c)}),h=l(e,i),u=this.window(t,h.x,h.y,0);if(!u)return;let d;for(const f of n.ghosts){const p=ke.sourceOf(f,{x:e,y:i});if(Math.abs(p.x)>=1||Math.abs(p.y)>=1)continue;const m=Math.max(2,Math.round(f.blur*c/Math.abs(f.scale))),g=Math.min(1+p.x,1-p.x)/2*a/c,v=Math.min(1+p.y,1-p.y)/2,M=Math.max(2*f.blur*c/Math.abs(f.scale),2)/c,w=Di.smoothstep(0,M,g)*Di.smoothstep(0,M,v),y=l(p.x,p.y),x=this.window(t,y.x,y.y,m);if(!x)continue;const b=w*f.share*x.mean/(f.scale*f.scale),E=.18*b*s;E<Di.VISIBLE_RESPONSE||b<.3*u.mean||(!d||E>d.score)&&(d={score:E,hit:{ghost:f,source:{x:x.brightest.x/a*2-1,y:x.brightest.y/c*2-1}}})}if(r&&r.flux[1]>0){const f=a/c;for(const p of n.ghosts){if(ke.scatters(p))continue;const m=p.scale,[g,v]=p.offset??[0,0],M=2*g+m*r.x,w=2*v+m*r.y,y=Math.max(p.blur+Math.abs(m)*r.radius,1.5/c);if(Math.hypot((e-M)/2*f,(i-w)/2)>y)continue;const b=.18*p.share*r.flux[1]/(Math.PI*.81*y*y)*s;b<Di.VISIBLE_RESPONSE||(!d||b>d.score)&&(d={score:b,hit:{ghost:p,source:{x:r.x,y:r.y},beyond:!0}})}}return d?.hit}holdsPictureAt(t,e,i){if(!this.readable)return!1;const n=this.window(t,Math.round((e+1)/2*this.mips.width),Math.round((i+1)/2*this.mips.height),4);return n!==void 0&&n.mean>0}dropAt(t,e,i){const n=Math.round((e+1)/2*this.ghostLayer.width),s=Math.round((i+1)/2*this.ghostLayer.height);if(n<0||s<0||n>=this.ghostLayer.width||s>=this.ghostLayer.height)return 0;const r=new Uint16Array(4);return t.readRenderTargetPixels(this.ghostLayer,n,s,1,1,r),Di.half(r[3])}window(t,e,i,n){const s=Math.max(1,Math.ceil(n/24)),r={x:Math.max(0,e-n),y:Math.max(0,i-n)},a={x:Math.min(this.mips.width-1,e+n),y:Math.min(this.mips.height-1,i+n)};if(r.x>a.x||r.y>a.y)return;const c=a.x-r.x+1,l=a.y-r.y+1,h=new Uint16Array(c*l*4);t.readRenderTargetPixels(this.mips,r.x,r.y,c,l,h);let u=0,d=0,f=-1,p={x:e,y:i};for(let m=r.y;m<=a.y;m+=s){const g=(m-r.y)*c*4;for(let v=0;v<c;v+=s){const M=.2126*Di.half(h[g+v*4])+.7152*Di.half(h[g+v*4+1])+.0722*Di.half(h[g+v*4+2]);u+=M,d++,M>f&&(f=M,p={x:r.x+v,y:m})}}return{mean:d>0?u/d:0,brightest:p}}draw(t,e,i){this.quad.material=e,t.setRenderTarget(i),t.render(this.quadScene,this.quadCamera)}static half(t){const e=t>>10&31,i=t&1023,n=t&32768?-1:1;return e===0?n*i*2**-24:e===31?0:n*(1+i/1024)*2**(e-15)}static smoothstep(t,e,i){const n=Math.max(0,Math.min(1,(i-t)/(e-t)));return n*n*(3-2*n)}blurHalo(t,e){const i=this.halo,n=Math.max(.5,e*i.height/2),s=this.haloMaterial.uniforms;s.uSource.value=this.mips.texture,s.uLod.value=Di.HALO_LEVEL,s.uStep.value.set(n/i.width,n/i.height),this.draw(t,this.haloMaterial,i)}static haloSize(t,e){const i=2**Di.HALO_LEVEL;return[Math.max(1,Math.floor(t/i)),Math.max(1,Math.floor(e/i))]}resize(t,e){const i=Math.max(1,t),n=Math.max(1,e);(this.mips.width!==Math.ceil(i/2)||this.mips.height!==Math.ceil(n/2))&&(this.readable=!1),this.frame.scene.setSize(i,n),this.frame.overlay.setSize(i,n),this.mips.setSize(Math.ceil(i/2),Math.ceil(n/2)),this.ghostLayer.setSize(Math.ceil(i/2),Math.ceil(n/2));const s=Di.haloSize(Math.ceil(i/2),Math.ceil(n/2));this.halo.setSize(s[0],s[1])}dispose(){this.frame.scene.dispose(),this.frame.overlay.dispose(),this.mips.dispose(),this.ghostLayer.dispose(),this.halo.dispose(),this.haloMaterial.dispose(),this.copyMaterial.dispose(),this.ghostMaterial.dispose(),this.developMaterial.dispose(),this.quad.geometry.dispose(),this.quadScene.clear()}}class Ks{static IDENTITY=[1,0,0,0,1,0,0,0,1];static NONE={colorMatrix:Ks.IDENTITY,contrastGain:1};static combine(t,e){const[i,n,s,r,a,c,l,h,u]=t.colorMatrix,[d,f,p,m,g,v,M,w,y]=e.colorMatrix;return{colorMatrix:[d*i+f*r+p*l,d*n+f*a+p*h,d*s+f*c+p*u,m*i+g*r+v*l,m*n+g*a+v*h,m*s+g*c+v*u,M*i+w*r+y*l,M*n+w*a+y*h,M*s+w*c+y*u],contrastGain:t.contrastGain*e.contrastGain}}static isNone(t){return t.contrastGain===1&&t.colorMatrix.every((e,i)=>e===Ks.IDENTITY[i])}}class ni{static MIN_RATIO=1;static STEP=.25;static MIN_SHARE_OF_DISPLAY=.75;static GPU_LATE_MS=12;static GPU_ROOM_MS=6;static INTERVAL_LATE_MS=21;static LOWER_COOLDOWN_MS=750;static RAISE_COOLDOWN_MS=2e3;static PROBE_WATCH_MS=2e3;static PROBE_EVERY_MS=6e3;static PROBE_BACKOFF_MS=3e4;ratio;maxRatio;timer;intervalMs;lastChangeMs=-1/0;nextProbeMs=0;probe;constructor(t,e){this.maxRatio=ni.clamp(t),this.ratio=this.maxRatio,this.timer=e?am.create(e):void 0}get pixelRatio(){return this.ratio}static SETTLE_MS=400;static SUSTAINED_MS=100;lastEditMs=-1/0;editStreakStartMs=-1/0;wasChanging=!1;noteChange(t){t-this.lastEditMs>ni.SETTLE_MS&&(this.editStreakStartMs=t),this.lastEditMs=t}changing(t){return t-this.lastEditMs<=ni.SETTLE_MS&&this.lastEditMs-this.editStreakStartMs>=ni.SUSTAINED_MS}ratioFor(t,e){return this.changing(t)?this.wasChanging?(this.update(t,e),this.ratio):(this.wasChanging=!0,this.reset(),this.ratio):(this.wasChanging=!1,this.maxRatio)}get timesGpu(){return this.timer!==void 0}set maximum(t){this.maxRatio=ni.clamp(t),this.ratio>this.maxRatio&&(this.ratio=this.maxRatio),this.ratio<this.minimum&&(this.ratio=Math.min(this.maxRatio,this.minimum))}get minimum(){const t=Math.floor(this.maxRatio*ni.MIN_SHARE_OF_DISPLAY/ni.STEP)*ni.STEP;return Math.max(ni.MIN_RATIO,t)}get maximum(){return this.maxRatio}beginDrawing(){this.timer?.begin()}endDrawing(){this.timer?.end()}reset(){this.intervalMs=void 0,this.probe=void 0,this.timer?.reset()}update(t,e){const i=this.timer?.poll();if(!(this.timer&&i===void 0))return i!==void 0?this.followGpu(t,i):this.followIntervals(t,e)}followGpu(t,e){if(e>ni.GPU_LATE_MS)return this.lower(t,ni.LOWER_COOLDOWN_MS);if(e<ni.GPU_ROOM_MS)return this.raise(t,ni.RAISE_COOLDOWN_MS)}followIntervals(t,e){if(!(e>0)||e>1e3)return;this.intervalMs=this.intervalMs===void 0?e:this.intervalMs*.9+e*.1;const i=this.intervalMs>ni.INTERVAL_LATE_MS;if(this.probe){if(i)return this.ratio=this.probe.ratioBefore,this.probe=void 0,this.lastChangeMs=t,this.nextProbeMs=t+ni.PROBE_BACKOFF_MS,this.ratio;t-this.probe.sinceMs>=ni.PROBE_WATCH_MS&&(this.probe=void 0,this.nextProbeMs=t+ni.PROBE_EVERY_MS);return}if(i){const n=this.lower(t,ni.LOWER_COOLDOWN_MS);return n!==void 0&&(this.nextProbeMs=t+ni.PROBE_EVERY_MS),n}if(this.ratio<this.maxRatio&&t>=this.nextProbeMs&&t-this.lastChangeMs>=ni.RAISE_COOLDOWN_MS){const n=this.ratio,s=this.raise(t,0);return s!==void 0&&(this.probe={sinceMs:t,ratioBefore:n}),s}}lower(t,e){if(!(this.ratio<=this.minimum||t-this.lastChangeMs<e))return this.ratio=Math.max(this.minimum,ni.clamp(this.ratio-ni.STEP)),this.lastChangeMs=t,this.ratio}raise(t,e){if(!(this.ratio>=this.maxRatio||t-this.lastChangeMs<e))return this.ratio=Math.min(this.maxRatio,ni.clamp(this.ratio+ni.STEP)),this.lastChangeMs=t,this.ratio}static clamp(t){return Number.isFinite(t)?Math.max(ni.MIN_RATIO,Math.round(t/ni.STEP)*ni.STEP):ni.MIN_RATIO}}class am{constructor(t,e){this.gl=t,this.extension=e}static IN_FLIGHT_MAX=8;static create(t){if(!(t instanceof WebGL2RenderingContext))return;const e=t.getExtension("EXT_disjoint_timer_query_webgl2");return e?new am(t,e):void 0}pending=[];active;smoothedMs;begin(){if(!(this.active||this.pending.length>=am.IN_FLIGHT_MAX))try{const t=this.gl.createQuery();if(!t)return;this.gl.beginQuery(this.extension.TIME_ELAPSED_EXT,t),this.active=t}catch{this.active=void 0}}end(){if(this.active){try{this.gl.endQuery(this.extension.TIME_ELAPSED_EXT),this.pending.push(this.active)}catch{}this.active=void 0}}poll(){const t=this.gl;try{for(let e=0;e<this.pending.length;e++){const i=this.pending[e];if(!t.getQueryParameter(i,t.QUERY_RESULT_AVAILABLE))continue;if(!t.getParameter(this.extension.GPU_DISJOINT_EXT)){const s=t.getQueryParameter(i,t.QUERY_RESULT)/1e6;this.smoothedMs=this.smoothedMs===void 0?s:this.smoothedMs*.8+s*.2}t.deleteQuery(i),this.pending.splice(e,1),e--}}catch{this.pending.length=0}return this.smoothedMs}reset(){this.smoothedMs=void 0}}class Ee{static ICE_INDEX_RED=1.3067;static ICE_INDEX_BLUE=1.317;static SIDE_PRISM_ANGLE_DEG=60;static END_PRISM_ANGLE_DEG=90;static get PARHELIA_MAX_SUN_ALTITUDE_DEG(){const t=Ee.ICE_INDEX_RED,e=Math.sqrt((4-t*t)/3);return Math.asin(Math.min(1,e))*180/Math.PI}static minimumDeviationDeg(t,e){const i=t*Math.PI/180,n=e*Math.sin(i/2);return n>1?Number.NaN:(2*Math.asin(n)-i)*180/Math.PI}static effectiveIndex(t,e){const i=e*Math.PI/180,n=Math.cos(i);return n<=0?Number.POSITIVE_INFINITY:Math.sqrt(t*t-Math.sin(i)**2)/n}static parheliaAzimuthDeg(t,e=Ee.ICE_INDEX_RED){const i=Ee.minimumDeviationDeg(Ee.SIDE_PRISM_ANGLE_DEG,Ee.effectiveIndex(e,t));return Number.isFinite(i)?i:void 0}static parheliaDistanceDeg(t,e=Ee.ICE_INDEX_RED){const i=Ee.parheliaAzimuthDeg(t,e);if(i===void 0)return;const n=t*Math.PI/180,s=Math.sin(n)**2,r=Math.cos(n)**2*Math.cos(i*Math.PI/180);return Math.acos(Math.max(-1,Math.min(1,s+r)))*180/Math.PI}static get PLATE_END_FACE_LIMIT_DEG(){const t=Ee.ICE_INDEX_RED;return Math.asin(Math.min(1,Math.sqrt(t*t-1)))*180/Math.PI}static circumzenithalAltitudeDeg(t,e=Ee.ICE_INDEX_RED){if(t<0||t>90-Ee.PLATE_END_FACE_LIMIT_DEG)return;const i=Math.cos(t*Math.PI/180),n=Math.sqrt(e*e-i*i);if(!(n>=1))return Math.asin(n)*180/Math.PI}static DECK_HEIGHT_M=8e3;static deckLitUntilDeg(t){return Math.acos(6371e3/(6371e3+Math.max(0,t)))*180/Math.PI}static halo22(){return Ee.ringOf("halo22",Ee.SIDE_PRISM_ANGLE_DEG)}static halo46(){return Ee.ringOf("halo46",Ee.END_PRISM_ANGLE_DEG)}static ringOf(t,e){const i=Ee.minimumDeviationDeg(e,Ee.ICE_INDEX_RED),n=Ee.minimumDeviationDeg(e,Ee.ICE_INDEX_BLUE);return{id:t,angleDeg:(i+n)/2,redAngleDeg:i,blueAngleDeg:n}}static strength(t,e,i=90,n=0){const s=Math.max(0,Math.min(1,t)),r=Math.max(0,1-Math.max(0,Math.min(1,e))),a=i>=0?1:n<=0?0:Math.max(0,1+i/n);return s*r*a}static formsAt(t,e=0){if(t<=-e)return[];const i=[Ee.halo22(),Ee.halo46()],n=t>0?Ee.parheliaDistanceDeg(t):void 0;n!==void 0&&i.push({id:"parhelia",angleDeg:n,redAngleDeg:n,blueAngleDeg:Ee.parheliaDistanceDeg(t,Ee.ICE_INDEX_BLUE)}),i.push({id:"tangentArc",angleDeg:Ee.halo22().angleDeg}),t>0&&i.push({id:"parhelicCircle",angleDeg:t});const s=Ee.circumzenithalAltitudeDeg(t);return s!==void 0&&i.push({id:"circumzenithal",angleDeg:s}),t>Ee.PLATE_END_FACE_LIMIT_DEG&&i.push({id:"circumhorizontal"}),t<Ee.PILLAR_MAX_SOURCE_ALTITUDE_DEG&&i.push({id:"pillar"}),i}static PILLAR_MAX_SOURCE_ALTITUDE_DEG=20}class tr{static get WATER_INDEX_RED(){return Fn.indexAt(Fn.RED_NM)}static get WATER_INDEX_BLUE(){return Fn.indexAt(Fn.BLUE_NM)}static radiusDeg(t,e){const i=(e*e-1)/(t*t-1);if(i<0||i>1)return Number.NaN;const n=Math.acos(Math.sqrt(i)),s=Math.asin(Math.sin(n)/e),r=2*(n-s)+(t-1)*(Math.PI-2*s),a=2*Math.PI;let c=r%a;return c<0&&(c+=a),c>Math.PI&&(c=a-c),180-c*180/Math.PI}static primary(){return tr.bowOf("primary",2,0)}static secondary(){return tr.bowOf("secondary",3,0)}static bowOf(t,e,i){const n=tr.radiusDeg(e,tr.WATER_INDEX_RED),s=tr.radiusDeg(e,tr.WATER_INDEX_BLUE),r=(n+s)/2;return{id:t,radiusDeg:r,redRadiusDeg:n,violetRadiusDeg:s,topAltitudeDeg:r-i}}static alexandersBandDeg(){return{fromDeg:tr.primary().redRadiusDeg,toDeg:tr.secondary().redRadiusDeg}}static formsAt(t){return t<0?[]:[tr.bowOf("primary",2,t),tr.bowOf("secondary",3,t)].filter(e=>e.topAltitudeDeg>0)}static FULL_MOON_MAGNITUDE=-12.7;static moonlightShare(t){return Math.min(1,10**(-.4*(t-tr.FULL_MOON_MAGNITUDE)))}static strength(t,e,i){if(i<=0)return 0;const n=Math.max(0,Math.min(1,t)),s=Math.max(0,1-Math.max(0,Math.min(1,e)));return n*s}}class er{constructor(t){this.radius=t;const e=er.SEGMENTS*er.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const i=new be;i.setAttribute("position",new ye(this.positions,3)),i.setAttribute("color",new ye(this.colors,3)),i.setDrawRange(0,0),this.object=new yt(i,La.material()),this.object.frustumCulled=!1,La.track(this.object)}static POINTS=24;static SEGMENTS=er.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(er.ACROSS-1)*6;static HEAD_HALF_WIDTH_DEG=.15;static SPREAD_FRACTION=.05;static FADE_POWER=1.8;object;positions;colors;head;tip;brightness=0;set(t,e,i){this.head=t&&Ei(t.altitudeDeg,t.azimuthDeg,1),this.tip=e&&Ei(e.altitudeDeg,e.azimuthDeg,1),this.brightness=i,this.rebuild()}rebuild(){const t=this.object.geometry,e=this.head,i=this.tip;if(!e||!i||this.brightness<=0){t.setDrawRange(0,0);return}const n=this.angleBetween(e,i);if(n<=0){t.setDrawRange(0,0);return}const s=n*er.SPREAD_FRACTION*Math.PI/180,r=h=>this.scale(this.slerp(e,i,h),this.radius),a=h=>this.radius*(er.HEAD_HALF_WIDTH_DEG*Math.PI/180+s*h),c=h=>this.brightness*(1-h)**er.FADE_POWER;let l=0;for(let h=1;h<er.POINTS;h++){const u=(h-1)/er.SEGMENTS,d=h/er.SEGMENTS;l=this.pushBand(l,r(u),r(d),a(u),a(d),c(u),c(d))}t.setDrawRange(0,l),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}pushBand(t,e,i,n,s,r,a){const c=this.normalise(this.cross(this.normalise(e),this.normalise(this.subtract(i,e))));for(let l=0;l<er.ACROSS-1;l++){const h=l-1,u=l,d=this.across(e,c,n,h),f=this.across(i,c,s,h),p=this.across(e,c,n,u),m=this.across(i,c,s,u),g=(v,M)=>v===0?M:0;t=this.push(t,d,g(h,r)),t=this.push(t,f,g(h,a)),t=this.push(t,p,g(u,r)),t=this.push(t,f,g(h,a)),t=this.push(t,m,g(u,a)),t=this.push(t,p,g(u,r))}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i){const n=t*3;this.positions[n]=e.x,this.positions[n+1]=e.y,this.positions[n+2]=e.z;const s=Bt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.55,this.colors[n+1]=s*.75,this.colors[n+2]=s,t+1}slerp(t,e,i){const n=this.angleBetweenRadians(t,e);if(n<1e-9)return t;const s=Math.sin(n),r=Math.sin((1-i)*n)/s,a=Math.sin(i*n)/s;return{x:t.x*r+e.x*a,y:t.y*r+e.y*a,z:t.z*r+e.z*a}}angleBetween(t,e){return this.angleBetweenRadians(t,e)*180/Math.PI}angleBetweenRadians(t,e){const i=t.x*e.x+t.y*e.y+t.z*e.z;return Math.acos(Math.min(1,Math.max(-1,i)))}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class WN{object=new Ke;radius;tiers;drawn=[];constructor(t){this.radius=t,this.object.name="satellites",this.tiers=iu.map(e=>{const i=new ir(new be,Vt.material(e.size));return Vt.track(i),i.frustumCulled=!1,this.object.add(i),i})}set(t,e,i,n){const s=this.tiers.map(()=>[]);this.drawn=[];for(const r of t){if(r.magnitude>e)continue;const a=i(r.position);if(a<=0)continue;const c=r.magnitude-2.5*Math.log10(a);if(c>e)continue;const l=Ch(c,e),h=Py(l),{x:u,y:d,z:f}=Ei(r.position.altitudeDeg,r.position.azimuthDeg,this.radius),[p,m,g]=n(r.position,c);s[h].push({x:u,y:d,z:f,r:p,g:m,b:g,seed:r.norad*.6180339887%1}),this.drawn.push({satellite:r,direction:new T(u,d,f).normalize()})}this.tiers.forEach((r,a)=>{const c=s[a],l=new Float32Array(c.length*3),h=new Float32Array(c.length*3),u=new Float32Array(c.length);c.forEach((f,p)=>{l.set([f.x,f.y,f.z],p*3),h.set([f.r,f.g,f.b],p*3),u[p]=f.seed}),r.geometry.dispose();const d=new be;d.setAttribute("position",new ye(l,3)),d.setAttribute("color",new ye(h,3)),d.setAttribute("seed",new ye(u,1)),r.geometry=d})}get count(){return this.drawn.length}nearest(t,e){let i,n=e;for(const s of this.drawn){const r=s.direction.dot(t);r>n&&(n=r,i=s.satellite)}return i}dispose(){for(const t of this.tiers)t.geometry.dispose(),t.material.dispose();this.object.removeFromParent(),this.drawn=[]}}class Um{constructor(t){this.state=t}next(){this.state=this.state+1831565813|0;let t=this.state;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}between(t,e){return t+this.next()*(e-t)}}class br{static MIN_DURATION_MS=250;static MAX_DURATION_MS=1400;static schedule(t){const{ratePerHour:e,durationMs:i,velocityKmS:n,seed:s}=t;if(e<=0||i<=0)return[];const r=e*i/36e5,a=new Um(s),c=Math.floor(r),l=c+(a.next()<r-c?1:0),h=[];for(let u=0;u<l;u++){const d=Math.min(1,Math.max(0,(n-20)/52)),f=br.MAX_DURATION_MS-d*(br.MAX_DURATION_MS-br.MIN_DURATION_MS),p=a.between(5,70);h.push({t:a.between(0,i),durationMs:f*a.between(.7,1.3),fromRadiantDeg:p,bearingDeg:a.between(0,360),lengthDeg:Math.sin(p*Math.PI/180)*a.between(8,40)*(.6+d),brightness:a.next()**3}),h.sort((m,g)=>m.t-g.t)}return h}static FAINTEST_MAGNITUDE=6.5;static BRIGHTEST_MAGNITUDE=-4;static magnitudeOf(t){return br.FAINTEST_MAGNITUDE-(br.FAINTEST_MAGNITUDE-br.BRIGHTEST_MAGNITUDE)*t.brightness}static aliveAt(t,e){return t.filter(i=>e>=i.t&&e<=i.t+i.durationMs).map(i=>({meteor:i,progress:(e-i.t)/i.durationMs}))}}class Zo{object=new Ke;radius;core;glow;flashKey;static CORE_WIDTH_DEG=.06;static GLOW_WIDTH_DEG=.5;static SEGMENTS=28;static CORE_RELATIVE=1e3;constructor(t){this.radius=t,this.object.name="lightning-bolt",this.core=new Is({color:15659775,transparent:!0,opacity:0,blending:Cn,depthWrite:!1,fog:!1}),this.glow=new Is({color:10466559,transparent:!0,opacity:0,blending:Cn,depthWrite:!1,fog:!1}),this.object.visible=!1,this.object.renderOrder=5.95}set(t,e,i){if(!t||!t.cloudToGround||e<=.01){this.object.visible=!1;return}const n=`${t.channelSeed}:${Math.round(i)}`;n!==this.flashKey&&this.build(t,i,n),this.core.color.setHex(15659775).multiplyScalar(Zo.CORE_RELATIVE*Math.min(1,e*1.4)),this.glow.color.setHex(10466559).multiplyScalar(.1*Zo.CORE_RELATIVE*e*.35),this.core.opacity=1,this.glow.opacity=1,this.object.visible=!0}build(t,e,i){this.flashKey=i;for(const l of[...this.object.children])l.geometry.dispose(),this.object.remove(l);const n=new Um(t.channelSeed),s=Math.atan2(e,t.distanceM)*180/Math.PI,r=this.channel(n,t.azimuthDeg,s,0,1),a=[r],c=1+Math.floor(n.next()*2);for(let l=0;l<c;l++){const h=r[Math.floor(n.between(.15,.5)*r.length)];a.push(this.channel(n,h.azimuthDeg,h.altitudeDeg,h.altitudeDeg*n.between(.3,.7),.5))}for(const l of a)this.object.add(new yt(this.ribbon(l,Zo.GLOW_WIDTH_DEG),this.glow)),this.object.add(new yt(this.ribbon(l,Zo.CORE_WIDTH_DEG),this.core))}channel(t,e,i,n,s){const r=[],a=i-n;let c=e;for(let l=0;l<=Zo.SEGMENTS;l++){const h=i-a*l/Zo.SEGMENTS;r.push({azimuthDeg:c,altitudeDeg:h}),c+=t.between(-1,1)*a*.06*s}return r}ribbon(t,e){const i=new Float32Array(t.length*2*3),n=[],s=this.radius*Math.tan(e*Math.PI/180)/2,r=t.map(c=>{const{x:l,y:h,z:u}=Ei(c.altitudeDeg,c.azimuthDeg,this.radius);return new T(l,h,u)});r.forEach((c,l)=>{const h=r[Math.min(l+1,r.length-1)],u=r[Math.max(l-1,0)],f=h.clone().sub(u).normalize().cross(c.clone().normalize()).normalize().multiplyScalar(s);if(i.set([c.x+f.x,c.y+f.y,c.z+f.z],l*6),i.set([c.x-f.x,c.y-f.y,c.z-f.z],l*6+3),l<r.length-1){const p=l*2;n.push(p,p+1,p+2,p+1,p+3,p+2)}});const a=new be;return a.setAttribute("position",new ye(i,3)),a.setIndex(n),a}dispose(){for(const t of this.object.children)t.geometry.dispose();this.core.dispose(),this.glow.dispose(),this.object.removeFromParent()}}class gn{static MIN_INTERVAL_S=8;static MAX_INTERVAL_S=25;static SEVERE_MIN_INTERVAL_S=2;static SEVERE_MAX_INTERVAL_S=8;static CLOUD_TO_GROUND_FRACTION=.25;static MIN_DISTANCE_M=1e3;static MAX_DISTANCE_M=15e3;static INTERSTROKE_MS=60;static STROKE_DECAY_MS=40;static SOUND_SPEED_M_S=343;static schedule(t){const e=new Um(t.seed),i=[],{minS:n,maxS:s}=gn.intervalFor(t.intensity??.5);let r=e.between(0,s)*1e3;for(;r<t.durationMs;){const a=e.next()<gn.CLOUD_TO_GROUND_FRACTION,c=gn.MIN_DISTANCE_M,l=gn.MAX_DISTANCE_M,h=Math.sqrt(e.between(c*c,l*l)),u=a?1+Math.floor(e.next()*4):1,d=[];let f=0;for(let p=0;p<u;p++)d.push({offsetMs:f,intensity:p===0?1:e.between(.4,.9)}),f+=gn.INTERSTROKE_MS*e.between(.5,1.6);i.push({t:r,azimuthDeg:e.between(0,360),distanceM:h,cloudToGround:a,strokes:d,channelSeed:Math.floor(e.next()*2**31)}),r+=e.between(n,s)*1e3}return i}static intervalFor(t){const e=Math.min(1,Math.max(0,(t-.5)/.5));return{minS:gn.MIN_INTERVAL_S-e*(gn.MIN_INTERVAL_S-gn.SEVERE_MIN_INTERVAL_S),maxS:gn.MAX_INTERVAL_S-e*(gn.MAX_INTERVAL_S-gn.SEVERE_MAX_INTERVAL_S)}}static brightnessAt(t,e){let i=0;for(const n of t.strokes){const s=e-t.t-n.offsetMs;s<0||s>gn.STROKE_DECAY_MS*6||(i+=n.intensity*Math.exp(-s/gn.STROKE_DECAY_MS))}return Math.min(1,i)}static endOf(t){const e=t.strokes[t.strokes.length-1];return t.t+e.offsetMs+gn.STROKE_DECAY_MS*6}static thunderDelayMs(t){return t.distanceM/gn.SOUND_SPEED_M_S*1e3}}class Ph{static ODD_RADIUS_WEDGES_DEG=[28,56,80];static STANDS_OUT=1.5;static NEIGHBOURHOOD_DEG=2.5;static oddRadiiDeg(){const t=(Ee.ICE_INDEX_RED+Ee.ICE_INDEX_BLUE)/2;return Ph.ODD_RADIUS_WEDGES_DEG.map(e=>Ee.minimumDeviationDeg(e,t)).filter(e=>Number.isFinite(e))}static at(t,e,i,n){const s=Math.PI/180,r=t,a=Math.abs(i),c=Math.sin(r*s)*Math.sin(e*s)+Math.cos(r*s)*Math.cos(e*s)*Math.cos(a*s),l=Math.acos(Math.max(-1,Math.min(1,c)))/s,h=Math.atan2(Math.sin(a*s)*Math.cos(e*s),Math.cos(r*s)*Math.sin(e*s)-Math.sin(r*s)*Math.cos(e*s)*Math.cos(a*s))/s,u=Math.abs(e-r),d=()=>{const M=n(e,a);if(!(M>0))return!1;const w=Ph.NEIGHBOURHOOD_DEG,y=1/Math.max(.2,Math.cos(e*s)),x=[n(e+w,a),n(e-w,a),n(e,a+w*y),n(e,Math.max(0,a-w*y))].sort((b,E)=>b-E);return M>x[1]*Ph.STANDS_OUT},f=()=>{const M=w=>{const y=l*s,x=w*s,b=Math.cos(y)*Math.cos(r*s)-Math.sin(y)*Math.cos(x)*Math.sin(r*s),E=Math.sin(y)*Math.sin(x),S=Math.cos(y)*Math.sin(r*s)+Math.sin(y)*Math.cos(x)*Math.cos(r*s);return n(Math.asin(Math.max(-1,Math.min(1,S)))/s,Math.abs(Math.atan2(E,b)/s))};return(M(70)+M(110)+M(250)+M(290))/4},p=(M,w=0)=>{if(d())return w>0&&!(n(e,a)>f()*w)?void 0:M};if(r>0&&r<Ee.PARHELIA_MAX_SUN_ALTITUDE_DEG&&u<2.5){const M=Ee.parheliaAzimuthDeg(r);if(M!==void 0&&a>=M-1.2&&a<=M+7){const w=p({id:"parhelion",angleDeg:Ee.parheliaDistanceDeg(r)},2.5);if(w)return w}}if(r>0&&u<2.5&&Math.abs(a-120)<4){const M=p({id:"parhelion120",angleDeg:120},0);if(M)return M}const m=Ee.circumzenithalAltitudeDeg(r);if(m!==void 0&&e>m-2&&e<m+4){const M=p({id:"circumzenithal",angleDeg:m});if(M)return M}if(r>Ee.PLATE_END_FACE_LIMIT_DEG){const M=Ee.circumzenithalAltitudeDeg(90-r);if(M!==void 0){const w=90-M;if(e>w-4&&e<w+2){const y=p({id:"circumhorizontal",angleDeg:w});if(y)return y}}}if(a<3&&r>0){if(e>r+3&&e<r+25&&r<Ee.PILLAR_MAX_SOURCE_ALTITUDE_DEG){const M=p({id:"pillar"});if(M)return M}if(Math.abs(e+r)<3){const M=p({id:"subsun"});if(M)return M}}const g=Ee.halo22();if(l>g.redAngleDeg-.6&&l<g.blueAngleDeg+2.5){const M=Math.abs(h)<50,w=Math.abs(h)>130;if(M||w){const y=p({id:M?"upperTangentArc":"lowerTangentArc",angleDeg:g.angleDeg},1.5);if(y)return y}}for(const M of Ph.oddRadiiDeg())if(l>M-.6&&l<M+1.8){const w=p({id:"oddRadius",angleDeg:M});if(w)return w}if(l>g.redAngleDeg-.6&&l<g.blueAngleDeg+2.5){const M=p({id:"halo22",angleDeg:g.angleDeg});if(M)return M}const v=Ee.halo46();if(l>v.redAngleDeg-.6&&l<v.blueAngleDeg+3){const M=p({id:"halo46",angleDeg:v.angleDeg});if(M)return M}if(r>0&&u<1.2){const M=n(e,a),w=Math.max(n(e+3,a),n(e-3,a));if(M>0&&M>w*2)return{id:"parhelicCircle",angleDeg:r}}}}class Ls{static RED_NM=656.3;static BLUE_NM=435.8;static ANCHOR_RED=1.3067;static ANCHOR_BLUE=1.317;static B=(Ls.ANCHOR_BLUE-Ls.ANCHOR_RED)/(1/(Ls.BLUE_NM*Ls.BLUE_NM)-1/(Ls.RED_NM*Ls.RED_NM));static A=Ls.ANCHOR_RED-Ls.B/(Ls.RED_NM*Ls.RED_NM);static indexAt(t){return Ls.A+Ls.B/(t*t)}}class pa{static MAX_FACES=20;normals=new Float64Array(pa.MAX_FACES*3);offsets=new Float64Array(pa.MAX_FACES);faceCount=8;radius=1;set(t,e,i,n,s,r,a=0){let c=0,l=0,h=0;Math.abs(i)<.9?(c=-e,l=t,h=0):(c=0,l=-i,h=e);const u=Math.hypot(c,l,h)||1;c/=u,l/=u,h/=u;const d=e*h-i*l,f=i*c-t*h,p=t*l-e*c,m=s/2,g=r/2;for(let v=0;v<6;v++){const M=n+v*Math.PI/3,w=Math.cos(M),y=Math.sin(M);this.normals[v*3]=c*w+d*y,this.normals[v*3+1]=l*w+f*y,this.normals[v*3+2]=h*w+p*y,this.offsets[v]=m}if(this.normals[18]=t,this.normals[19]=e,this.normals[20]=i,this.offsets[6]=g,this.normals[21]=-t,this.normals[22]=-e,this.normals[23]=-i,this.offsets[7]=g,this.faceCount=8,a>0){const v=pa.PYRAMID_TILT,M=Math.cos(v),w=Math.sin(v),y=Math.min(g,a*m*Math.tan(v)),x=g-y,b=M*x+w*m;for(let E=0;E<6;E++){const S=E*3,A=(8+E)*3,_=(14+E)*3;this.normals[A]=M*t+w*this.normals[S],this.normals[A+1]=M*e+w*this.normals[S+1],this.normals[A+2]=M*i+w*this.normals[S+2],this.normals[_]=-M*t+w*this.normals[S],this.normals[_+1]=-M*e+w*this.normals[S+1],this.normals[_+2]=-M*i+w*this.normals[S+2],this.offsets[8+E]=b,this.offsets[14+E]=b}this.faceCount=pa.MAX_FACES}this.radius=Math.hypot(m*2/Math.sqrt(3),g)}static rollToward(t,e,i,n,s,r){let a,c,l;Math.abs(i)<.9?(a=-e,c=t,l=0):(a=0,c=-i,l=e);const h=Math.hypot(a,c,l)||1;a/=h,c/=h,l/=h;const u=e*l-i*c,d=i*a-t*l,f=t*c-e*a;return Math.atan2(n*u+s*d+r*f,n*a+s*c+r*l)}get aimRadius(){return this.radius}trace(t,e,i,n,s,r,a){let c=-e,l=t,h=0,u=Math.hypot(c,l,h);u<1e-6&&(c=1,l=0,h=0,u=1),c/=u,l/=u,h/=u;const d=e*h-i*l,f=i*c-t*h,p=t*l-e*c,m=c*n+d*s-t*this.radius*2,g=l*n+f*s-e*this.radius*2,v=h*n+p*s-i*this.radius*2;let M=-1,w=-1/0,y=1/0;for(let Z=0;Z<this.faceCount;Z++){const nt=this.normals[Z*3],ot=this.normals[Z*3+1],Ut=this.normals[Z*3+2],Zt=nt*t+ot*e+Ut*i,jt=this.offsets[Z]-(nt*m+ot*g+Ut*v);if(Zt>1e-9){const K=jt/Zt;K<y&&(y=K)}else if(Zt<-1e-9){const K=jt/Zt;K>w&&(w=K,M=Z)}else if(jt<0)return 0}if(M<0||w>=y)return 0;let x=0;const b=this.normals[M*3],E=this.normals[M*3+1],S=this.normals[M*3+2],A=-(b*t+E*e+S*i),_=im.reflectance(A,1,r);a[x].x=t+2*A*b,a[x].y=e+2*A*E,a[x].z=i+2*A*S,a[x].weight=_,x++;const I=1/r,D=Math.sqrt(Math.max(0,1-I*I*(1-A*A)));let O=I*t+(I*A-D)*b,P=I*e+(I*A-D)*E,N=I*i+(I*A-D)*S,k=m+t*w,B=g+e*w,W=v+i*w,Q=1-_;for(let Z=0;Z<pa.MAX_BOUNCES&&Q>pa.MIN_WEIGHT;Z++){let nt=-1,ot=1/0;for(let V=0;V<this.faceCount;V++){const Lt=this.normals[V*3],Xt=this.normals[V*3+1],kt=this.normals[V*3+2],Rt=Lt*O+Xt*P+kt*N;if(Rt<=1e-9)continue;const te=(this.offsets[V]-(Lt*k+Xt*B+kt*W))/Rt;te>1e-9&&te<ot&&(ot=te,nt=V)}if(nt<0)break;const Ut=this.normals[nt*3],Zt=this.normals[nt*3+1],jt=this.normals[nt*3+2],K=Ut*O+Zt*P+jt*N,lt=r*Math.sqrt(Math.max(0,1-K*K));if(k+=O*ot,B+=P*ot,W+=N*ot,lt<1){const V=Math.sqrt(Math.max(0,1-lt*lt)),Lt=im.reflectance(K,r,1);if(a[x].x=r*O-(r*K-V)*Ut,a[x].y=r*P-(r*K-V)*Zt,a[x].z=r*N-(r*K-V)*jt,a[x].weight=Q*(1-Lt),x++,x>=a.length)return x;Q*=Lt}const ct=2*K;O-=ct*Ut,P-=ct*Zt,N-=ct*jt}return x}static MAX_BOUNCES=6;static PYRAMID_TILT=62*Math.PI/180;static MIN_WEIGHT=1e-4}class qe{static AZIMUTH_BINS=512;static ALTITUDE_BINS=512;static DEFAULT_POPULATIONS=[{orientation:"tumbling",widthMicrons:50,lengthMicrons:50,share:.48},{orientation:"plate",widthMicrons:100,lengthMicrons:15,share:.27},{orientation:"column",widthMicrons:40,lengthMicrons:120,share:.18},{orientation:"parry",widthMicrons:40,lengthMicrons:120,share:.02},{orientation:"pyramidal",widthMicrons:40,lengthMicrons:120,share:.03,capFraction:.5},{orientation:"lowitz",widthMicrons:100,lengthMicrons:15,share:.02}];static DEFAULT_RARE_SHARE=n_;static populationsFor(t){const e=Math.min(.9,Math.max(0,t));if(Math.abs(e-qe.DEFAULT_RARE_SHARE)<1e-9)return qe.DEFAULT_POPULATIONS;const i=(1-e)/(1-qe.DEFAULT_RARE_SHARE);return qe.DEFAULT_POPULATIONS.map(n=>n.orientation==="pyramidal"||n.orientation==="lowitz"?{...n,share:n.share/qe.DEFAULT_RARE_SHARE*e}:{...n,share:n.share*i})}populations=qe.DEFAULT_POPULATIONS;populationTotal=1;static WORST_TILT_DEG=180;static BEST_TILT_DEG=.5;static SOURCE_RADIUS_DEG=.265;static UNDEVIATED_DEG=.6;crystal=new pa;emergent=Array.from({length:pa.MAX_BOUNCES+2},()=>({x:0,y:0,z:0,weight:0}));tally=new Float32Array(qe.AZIMUTH_BINS*qe.ALTITUDE_BINS*3);radiance=new Float32Array(qe.AZIMUTH_BINS*qe.ALTITUDE_BINS*3);scratch=new Float32Array(qe.AZIMUTH_BINS*qe.ALTITUDE_BINS*3);seed=1;spare=0;hasSpare=!1;altitude=0;tilt=0;alignment=0;traced=0;begin(t,e,i=2654435769,n=qe.DEFAULT_POPULATIONS){this.populations=n,this.populationTotal=n.reduce((r,a)=>r+a.share,0)||1,this.seed=i>>>0||1,this.hasSpare=!1,this.tally.fill(0),this.traced=0,this.altitude=t*Math.PI/180,this.alignment=Math.min(1,Math.max(0,e));const s=qe.WORST_TILT_DEG*(qe.BEST_TILT_DEG/qe.WORST_TILT_DEG)**this.alignment;this.tilt=s*Math.PI/180}trace(t){const e=qe.AZIMUTH_BINS,i=qe.ALTITUDE_BINS,n=this.tally,s=qe.SOURCE_RADIUS_DEG*Math.PI/180,r=Math.cos(qe.UNDEVIATED_DEG*Math.PI/180),a=this.altitude;for(let c=0;c<t;c++){const l=this.pickPopulation();this.orient(l,this.tilt);const h=this.random()*2*Math.PI,u=s*Math.sqrt(this.random()),d=a+u*Math.sin(h),f=u*Math.cos(h)/Math.max(.05,Math.cos(a)),p=-Math.cos(d)*Math.cos(f),m=-Math.cos(d)*Math.sin(f),g=-Math.sin(d),v=this.crystal.aimRadius,M=(this.random()*2-1)*v,w=(this.random()*2-1)*v,y=4*v*v,x=_n.SAMPLES[this.random()*_n.SAMPLES.length|0],b=this.crystal.trace(p,m,g,M,w,Ls.indexAt(x.wavelengthNm),this.emergent);for(let E=0;E<b;E++){const S=this.emergent[E],A=Math.hypot(S.x,S.y,S.z);if(A<1e-9||S.weight<=0)continue;const _=S.x/A,I=S.y/A,D=S.z/A;if(_*p+I*m+D*g>r)continue;const O=Math.asin(Math.max(-1,Math.min(1,-D))),P=Math.abs(Math.atan2(-I,-_)),N=Math.min(e-1,P/Math.PI*e|0),B=(Math.min(i-1,(O+Math.PI/2)/Math.PI*i|0)*e+N)*3,W=S.weight*y*_n.SAMPLES.length;n[B]+=W*x.r,n[B+1]+=W*x.g,n[B+2]+=W*x.b}}this.traced+=t}get tracedRays(){return this.traced}harvest(){const t=qe.AZIMUTH_BINS,e=qe.ALTITUDE_BINS;return this.toRadiance(t,e),this.smooth(t,e),{width:t,height:e,data:this.radiance,sourceAltitudeDeg:this.altitude*180/Math.PI,alignment:this.alignment,rays:this.traced}}compute(t,e,i,n,s){return this.begin(t,e,n,s),this.trace(i),this.harvest()}toRadiance(t,e){const i=2*Math.PI/t,n=Math.max(1,this.traced),s=4*qe.REFERENCE_MICRONS*qe.REFERENCE_MICRONS;for(let r=0;r<e;r++){const a=Math.sin(r/e*Math.PI-Math.PI/2),c=Math.sin((r+1)/e*Math.PI-Math.PI/2),l=1/(i*(c-a)*n*s);for(let h=0;h<t;h++){const u=(r*t+h)*3;this.radiance[u]=this.tally[u]*l,this.radiance[u+1]=this.tally[u+1]*l,this.radiance[u+2]=this.tally[u+2]*l}}}static REFERENCE_MICRONS=50;smooth(t,e){const i=this.scratch,n=this.radiance;i.set(n);for(let r=0;r<e;r++){const a=r*t*3;for(let c=0;c<3;c++){let l=i[a+c];for(let h=0;h<t;h++){const u=a+h*3+c,d=h+1<t?i[u+3]:i[u];n[u]=(l+2*i[u]+d)/4,l=i[u]}}}i.set(n);const s=t*3;for(let r=0;r<e;r++){const a=r>0?-s:0,c=r+1<e?s:0,l=r*s;for(let h=l;h<l+s;h++)n[h]=(i[h+a]+2*i[h]+i[h+c])/4}}pickPopulation(){const t=this.random()*this.populationTotal;let e=0;for(const i of this.populations)if(e+=i.share,t<=e)return i;return this.populations[this.populations.length-1]}orient(t,e){const i=this.random()*2*Math.PI;let n=this.random()*2*Math.PI,s=0,r=0,a=1;switch(t.orientation){case"pyramidal":case"tumbling":{a=this.random()*2-1;const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"plate":{a=this.spreadAboutAnAxis(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"column":case"parry":{a=this.spreadAboutAPlane(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i),t.orientation==="parry"&&(n=Math.PI/2+this.gaussian()*e);break}}if(t.orientation==="lowitz"){const c=this.spreadAboutAPlane(e),l=Math.sqrt(Math.max(0,1-c*c)),h=l*Math.cos(i),u=l*Math.sin(i),d=c;let f=-d*h,p=-d*u,m=1-d*d;const g=Math.hypot(f,p,m)||1;f/=g,p/=g,m/=g;const v=u*m-d*p,M=d*f-h*m,w=h*p-u*f,y=this.random()*2*Math.PI;s=f*Math.cos(y)+v*Math.sin(y),r=p*Math.cos(y)+M*Math.sin(y),a=m*Math.cos(y)+w*Math.sin(y),n=pa.rollToward(s,r,a,h,u,d)+Math.PI/6}this.crystal.set(s,r,a,n,t.widthMicrons,t.lengthMicrons,t.capFraction??0)}random(){this.seed=this.seed+1831565813>>>0;let t=this.seed;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}spreadAboutAnAxis(t){const e=1/Math.max(1e-6,t*t),i=Math.max(1e-12,this.random()),n=1+Math.log(i+(1-i)*Math.exp(-2*e))/e;return Math.max(-1,Math.min(1,n))}spreadAboutAPlane(t){for(let e=0;e<8;e++){const i=this.gaussian()*t;if(i>=-1&&i<=1)return i}return this.random()*2-1}gaussian(){if(this.hasSpare)return this.hasSpare=!1,this.spare;const t=Math.sqrt(-2*Math.log(Math.max(1e-12,this.random()))),e=2*Math.PI*this.random();return this.spare=t*Math.sin(e),this.hasSpare=!0,t*Math.cos(e)}}class XN{static fromRadiance(t,e){const i=Gn.toHalfFloat(1);for(let n=0,s=0;s<t.length;n+=4,s+=3)e[n]=Gn.toHalfFloat(t[s]),e[n+1]=Gn.toHalfFloat(t[s+1]),e[n+2]=Gn.toHalfFloat(t[s+2]),e[n+3]=i}}class Zi{static RADIUS=880;static RAYS=9e5;static RAYS_PER_BATCH=2e3;static BUDGET_MS=6;static URGENT_BUDGET_MS=40;static ALTITUDE_STEP_DEG=1;static ALIGNMENT_STEP=.05;static LEAP_ALTITUDE_DEG=5;static LEAP_ALIGNMENT=.25;static GAIN=.55;setCloudOffset(t){this.material.uniforms.uFieldOffset.value.copy(t)}object;material;sky=new qe;texture;texels;mappedAltitudeDeg=Number.NaN;mappedAlignment=Number.NaN;mappedRare=Number.NaN;tracing=!1;everDisplayed=!1;urgent=!1;workHandle;onRepaint;constructor(){const t=qe.AZIMUTH_BINS,e=qe.ALTITUDE_BINS;this.texels=new Uint16Array(t*e*4),this.texture=new Ds(this.texels,t,e,tn,Ye),this.texture.minFilter=Me,this.texture.magFilter=Me,this.texture.wrapS=Qi,this.texture.wrapT=Qi,this.texture.needsUpdate=!0,this.material=new De({uniforms:{uSource:{value:new T(0,1,0)},uUp:{value:new T(0,1,0)},uStrength:{value:0},uTint:{value:new T(1,.97,.92)},uIceCover:{value:0},uIceHeight:{value:1},uFieldOffset:{value:new T},uMap:{value:this.texture},uGain:{value:Zi.GAIN}},vertexShader:`
|
|
8927
|
+
`,blending:Ys,depthTest:!1,depthWrite:!1}),this.quad=new yt(new vs(2,2),this.copyMaterial),this.quadScene.add(this.quad)}setFilmPrint(t,e,i,n=!1){const s=this.developMaterial.uniforms;if(s.uMonochrome.value=n?1:0,s.uPrintOn.value=t?1:0,!t)return;const r=Sa.frame(t,Sa.frameAt(t,e));s.uPrintContrast.value=t.contrast,s.uPrintTint.value.set(...t.tint),s.uPrintSoftness.value=t.softness,s.uPrintWeave.value.set(...r.weave),s.uPrintGrain.value=t.grain,s.uPrintSeed.value=r.seed,s.uPrintAspect.value=i,s.uPrintSpecks.value.forEach((c,l)=>{const h=r.specks[l];c.set(h?.u??0,h?.v??0,h?.radius??0,h?.kept??1)})}develop(t,e,i,n=1,s,r=!0){const a=t.getRenderTarget();this.readable=r,this.copyMaterial.uniforms.uSource.value=e.scene.texture,this.copyMaterial.uniforms.uGain.value=n,this.draw(t,this.copyMaterial,this.mips);const c=this.ghostMaterial.uniforms;c.uSize.value.set(this.mips.width,this.mips.height);const l=Math.min(i.ghosts.length,Di.MAX_GHOSTS);c.uCount.value=l;for(let m=0;m<l;m++){const g=i.ghosts[m];c.uScale.value[m]=g.scale||1,c.uShare.value[m]=g.share,c.uBlur.value[m]=g.blur,c.uKind.value[m]=g.cause==="drops"?2:ke.scatters(g)?1:0,c.uOffset.value[m].set(g.offset?.[0]??0,g.offset?.[1]??0),c.uTint.value[m].set(...g.tint??[1,1,1])}const h=i.ghosts.slice(0,l).find(m=>m.cause==="drops");h&&this.blurHalo(t,h.blur),c.uBlades.value=i.blades,c.uBladeAngle.value=i.bladeAngleRad,c.uDrops.value=i.drops,c.uImpacts.value=i.impacts;const u=c.uHistory.value;for(let m=0;m<u.length;m++)u[m]=i.history[m]??0;c.uStill.value=i.still?1:0,c.uRunning.value=i.running;const d=i.placed.slice(0,Di.MAX_PLACED_DROPS);c.uPlacedCount.value=d.length,d.forEach((m,g)=>c.uPlaced.value[g].set(m.x,1-m.y,m.radius)),c.uBright.value.set(((s?.x??0)+1)/2,((s?.y??0)+1)/2),c.uBrightRadius.value=s?.radius??0;const f=s?.flux??[0,0,0];c.uBrightFlux.value.set(f[0]*n,f[1]*n,f[2]*n),this.draw(t,this.ghostMaterial,this.ghostLayer);const p=this.developMaterial.uniforms;p.uSource.value=e.scene.texture,p.uOverlay.value=e.overlay.texture,p.uGain.value=n,p.uKept.value=1-i.scattered,this.draw(t,this.developMaterial,a)}pickAt(t,e,i,n,s,r){const a=this.mips.width,c=this.mips.height,l=(f,p)=>({x:Math.round((f+1)/2*a),y:Math.round((p+1)/2*c)}),h=l(e,i),u=this.window(t,h.x,h.y,0);if(!u)return;let d;for(const f of n.ghosts){const p=ke.sourceOf(f,{x:e,y:i});if(Math.abs(p.x)>=1||Math.abs(p.y)>=1)continue;const m=Math.max(2,Math.round(f.blur*c/Math.abs(f.scale))),g=Math.min(1+p.x,1-p.x)/2*a/c,v=Math.min(1+p.y,1-p.y)/2,M=Math.max(2*f.blur*c/Math.abs(f.scale),2)/c,w=Di.smoothstep(0,M,g)*Di.smoothstep(0,M,v),y=l(p.x,p.y),x=this.window(t,y.x,y.y,m);if(!x)continue;const b=w*f.share*x.mean/(f.scale*f.scale),E=.18*b*s;E<Di.VISIBLE_RESPONSE||b<.3*u.mean||(!d||E>d.score)&&(d={score:E,hit:{ghost:f,source:{x:x.brightest.x/a*2-1,y:x.brightest.y/c*2-1}}})}if(r&&r.flux[1]>0){const f=a/c;for(const p of n.ghosts){if(ke.scatters(p))continue;const m=p.scale,[g,v]=p.offset??[0,0],M=2*g+m*r.x,w=2*v+m*r.y,y=Math.max(p.blur+Math.abs(m)*r.radius,1.5/c);if(Math.hypot((e-M)/2*f,(i-w)/2)>y)continue;const b=.18*p.share*r.flux[1]/(Math.PI*.81*y*y)*s;b<Di.VISIBLE_RESPONSE||(!d||b>d.score)&&(d={score:b,hit:{ghost:p,source:{x:r.x,y:r.y},beyond:!0}})}}return d?.hit}holdsPictureAt(t,e,i){if(!this.readable)return!1;const n=this.window(t,Math.round((e+1)/2*this.mips.width),Math.round((i+1)/2*this.mips.height),4);return n!==void 0&&n.mean>0}dropAt(t,e,i){const n=Math.round((e+1)/2*this.ghostLayer.width),s=Math.round((i+1)/2*this.ghostLayer.height);if(n<0||s<0||n>=this.ghostLayer.width||s>=this.ghostLayer.height)return 0;const r=new Uint16Array(4);return t.readRenderTargetPixels(this.ghostLayer,n,s,1,1,r),Di.half(r[3])}window(t,e,i,n){const s=Math.max(1,Math.ceil(n/24)),r={x:Math.max(0,e-n),y:Math.max(0,i-n)},a={x:Math.min(this.mips.width-1,e+n),y:Math.min(this.mips.height-1,i+n)};if(r.x>a.x||r.y>a.y)return;const c=a.x-r.x+1,l=a.y-r.y+1,h=new Uint16Array(c*l*4);t.readRenderTargetPixels(this.mips,r.x,r.y,c,l,h);let u=0,d=0,f=-1,p={x:e,y:i};for(let m=r.y;m<=a.y;m+=s){const g=(m-r.y)*c*4;for(let v=0;v<c;v+=s){const M=.2126*Di.half(h[g+v*4])+.7152*Di.half(h[g+v*4+1])+.0722*Di.half(h[g+v*4+2]);u+=M,d++,M>f&&(f=M,p={x:r.x+v,y:m})}}return{mean:d>0?u/d:0,brightest:p}}draw(t,e,i){this.quad.material=e,t.setRenderTarget(i),t.render(this.quadScene,this.quadCamera)}static half(t){const e=t>>10&31,i=t&1023,n=t&32768?-1:1;return e===0?n*i*2**-24:e===31?0:n*(1+i/1024)*2**(e-15)}static smoothstep(t,e,i){const n=Math.max(0,Math.min(1,(i-t)/(e-t)));return n*n*(3-2*n)}blurHalo(t,e){const i=this.halo,n=Math.max(.5,e*i.height/2),s=this.haloMaterial.uniforms;s.uSource.value=this.mips.texture,s.uLod.value=Di.HALO_LEVEL,s.uStep.value.set(n/i.width,n/i.height),this.draw(t,this.haloMaterial,i)}static haloSize(t,e){const i=2**Di.HALO_LEVEL;return[Math.max(1,Math.floor(t/i)),Math.max(1,Math.floor(e/i))]}resize(t,e){const i=Math.max(1,t),n=Math.max(1,e);(this.mips.width!==Math.ceil(i/2)||this.mips.height!==Math.ceil(n/2))&&(this.readable=!1),this.frame.scene.setSize(i,n),this.frame.overlay.setSize(i,n),this.mips.setSize(Math.ceil(i/2),Math.ceil(n/2)),this.ghostLayer.setSize(Math.ceil(i/2),Math.ceil(n/2));const s=Di.haloSize(Math.ceil(i/2),Math.ceil(n/2));this.halo.setSize(s[0],s[1])}dispose(){this.frame.scene.dispose(),this.frame.overlay.dispose(),this.mips.dispose(),this.ghostLayer.dispose(),this.halo.dispose(),this.haloMaterial.dispose(),this.copyMaterial.dispose(),this.ghostMaterial.dispose(),this.developMaterial.dispose(),this.quad.geometry.dispose(),this.quadScene.clear()}}class Ks{static IDENTITY=[1,0,0,0,1,0,0,0,1];static NONE={colorMatrix:Ks.IDENTITY,contrastGain:1};static combine(t,e){const[i,n,s,r,a,c,l,h,u]=t.colorMatrix,[d,f,p,m,g,v,M,w,y]=e.colorMatrix;return{colorMatrix:[d*i+f*r+p*l,d*n+f*a+p*h,d*s+f*c+p*u,m*i+g*r+v*l,m*n+g*a+v*h,m*s+g*c+v*u,M*i+w*r+y*l,M*n+w*a+y*h,M*s+w*c+y*u],contrastGain:t.contrastGain*e.contrastGain}}static isNone(t){return t.contrastGain===1&&t.colorMatrix.every((e,i)=>e===Ks.IDENTITY[i])}}class ni{static MIN_RATIO=1;static STEP=.25;static MIN_SHARE_OF_DISPLAY=.75;static GPU_LATE_MS=12;static GPU_ROOM_MS=6;static INTERVAL_LATE_MS=21;static LOWER_COOLDOWN_MS=750;static RAISE_COOLDOWN_MS=2e3;static PROBE_WATCH_MS=2e3;static PROBE_EVERY_MS=6e3;static PROBE_BACKOFF_MS=3e4;ratio;maxRatio;timer;intervalMs;lastChangeMs=-1/0;nextProbeMs=0;probe;constructor(t,e){this.maxRatio=ni.clamp(t),this.ratio=this.maxRatio,this.timer=e?am.create(e):void 0}get pixelRatio(){return this.ratio}static SETTLE_MS=400;static SUSTAINED_MS=100;lastEditMs=-1/0;editStreakStartMs=-1/0;wasChanging=!1;noteChange(t){t-this.lastEditMs>ni.SETTLE_MS&&(this.editStreakStartMs=t),this.lastEditMs=t}changing(t){return t-this.lastEditMs<=ni.SETTLE_MS&&this.lastEditMs-this.editStreakStartMs>=ni.SUSTAINED_MS}ratioFor(t,e){return this.changing(t)?this.wasChanging?(this.update(t,e),this.ratio):(this.wasChanging=!0,this.reset(),this.ratio):(this.wasChanging=!1,this.maxRatio)}get timesGpu(){return this.timer!==void 0}set maximum(t){this.maxRatio=ni.clamp(t),this.ratio>this.maxRatio&&(this.ratio=this.maxRatio),this.ratio<this.minimum&&(this.ratio=Math.min(this.maxRatio,this.minimum))}get minimum(){const t=Math.floor(this.maxRatio*ni.MIN_SHARE_OF_DISPLAY/ni.STEP)*ni.STEP;return Math.max(ni.MIN_RATIO,t)}get maximum(){return this.maxRatio}beginDrawing(){this.timer?.begin()}endDrawing(){this.timer?.end()}reset(){this.intervalMs=void 0,this.probe=void 0,this.timer?.reset()}update(t,e){const i=this.timer?.poll();if(!(this.timer&&i===void 0))return i!==void 0?this.followGpu(t,i):this.followIntervals(t,e)}followGpu(t,e){if(e>ni.GPU_LATE_MS)return this.lower(t,ni.LOWER_COOLDOWN_MS);if(e<ni.GPU_ROOM_MS)return this.raise(t,ni.RAISE_COOLDOWN_MS)}followIntervals(t,e){if(!(e>0)||e>1e3)return;this.intervalMs=this.intervalMs===void 0?e:this.intervalMs*.9+e*.1;const i=this.intervalMs>ni.INTERVAL_LATE_MS;if(this.probe){if(i)return this.ratio=this.probe.ratioBefore,this.probe=void 0,this.lastChangeMs=t,this.nextProbeMs=t+ni.PROBE_BACKOFF_MS,this.ratio;t-this.probe.sinceMs>=ni.PROBE_WATCH_MS&&(this.probe=void 0,this.nextProbeMs=t+ni.PROBE_EVERY_MS);return}if(i){const n=this.lower(t,ni.LOWER_COOLDOWN_MS);return n!==void 0&&(this.nextProbeMs=t+ni.PROBE_EVERY_MS),n}if(this.ratio<this.maxRatio&&t>=this.nextProbeMs&&t-this.lastChangeMs>=ni.RAISE_COOLDOWN_MS){const n=this.ratio,s=this.raise(t,0);return s!==void 0&&(this.probe={sinceMs:t,ratioBefore:n}),s}}lower(t,e){if(!(this.ratio<=this.minimum||t-this.lastChangeMs<e))return this.ratio=Math.max(this.minimum,ni.clamp(this.ratio-ni.STEP)),this.lastChangeMs=t,this.ratio}raise(t,e){if(!(this.ratio>=this.maxRatio||t-this.lastChangeMs<e))return this.ratio=Math.min(this.maxRatio,ni.clamp(this.ratio+ni.STEP)),this.lastChangeMs=t,this.ratio}static clamp(t){return Number.isFinite(t)?Math.max(ni.MIN_RATIO,Math.round(t/ni.STEP)*ni.STEP):ni.MIN_RATIO}}class am{constructor(t,e){this.gl=t,this.extension=e}static IN_FLIGHT_MAX=8;static create(t){if(!(t instanceof WebGL2RenderingContext))return;const e=t.getExtension("EXT_disjoint_timer_query_webgl2");return e?new am(t,e):void 0}pending=[];active;smoothedMs;begin(){if(!(this.active||this.pending.length>=am.IN_FLIGHT_MAX))try{const t=this.gl.createQuery();if(!t)return;this.gl.beginQuery(this.extension.TIME_ELAPSED_EXT,t),this.active=t}catch{this.active=void 0}}end(){if(this.active){try{this.gl.endQuery(this.extension.TIME_ELAPSED_EXT),this.pending.push(this.active)}catch{}this.active=void 0}}poll(){const t=this.gl;try{for(let e=0;e<this.pending.length;e++){const i=this.pending[e];if(!t.getQueryParameter(i,t.QUERY_RESULT_AVAILABLE))continue;if(!t.getParameter(this.extension.GPU_DISJOINT_EXT)){const s=t.getQueryParameter(i,t.QUERY_RESULT)/1e6;this.smoothedMs=this.smoothedMs===void 0?s:this.smoothedMs*.8+s*.2}t.deleteQuery(i),this.pending.splice(e,1),e--}}catch{this.pending.length=0}return this.smoothedMs}reset(){this.smoothedMs=void 0}}class Ee{static ICE_INDEX_RED=1.3067;static ICE_INDEX_BLUE=1.317;static SIDE_PRISM_ANGLE_DEG=60;static END_PRISM_ANGLE_DEG=90;static get PARHELIA_MAX_SUN_ALTITUDE_DEG(){const t=Ee.ICE_INDEX_RED,e=Math.sqrt((4-t*t)/3);return Math.asin(Math.min(1,e))*180/Math.PI}static minimumDeviationDeg(t,e){const i=t*Math.PI/180,n=e*Math.sin(i/2);return n>1?Number.NaN:(2*Math.asin(n)-i)*180/Math.PI}static effectiveIndex(t,e){const i=e*Math.PI/180,n=Math.cos(i);return n<=0?Number.POSITIVE_INFINITY:Math.sqrt(t*t-Math.sin(i)**2)/n}static parheliaAzimuthDeg(t,e=Ee.ICE_INDEX_RED){const i=Ee.minimumDeviationDeg(Ee.SIDE_PRISM_ANGLE_DEG,Ee.effectiveIndex(e,t));return Number.isFinite(i)?i:void 0}static parheliaDistanceDeg(t,e=Ee.ICE_INDEX_RED){const i=Ee.parheliaAzimuthDeg(t,e);if(i===void 0)return;const n=t*Math.PI/180,s=Math.sin(n)**2,r=Math.cos(n)**2*Math.cos(i*Math.PI/180);return Math.acos(Math.max(-1,Math.min(1,s+r)))*180/Math.PI}static get PLATE_END_FACE_LIMIT_DEG(){const t=Ee.ICE_INDEX_RED;return Math.asin(Math.min(1,Math.sqrt(t*t-1)))*180/Math.PI}static circumzenithalAltitudeDeg(t,e=Ee.ICE_INDEX_RED){if(t<0||t>90-Ee.PLATE_END_FACE_LIMIT_DEG)return;const i=Math.cos(t*Math.PI/180),n=Math.sqrt(e*e-i*i);if(!(n>=1))return Math.asin(n)*180/Math.PI}static DECK_HEIGHT_M=8e3;static deckLitUntilDeg(t){return Math.acos(6371e3/(6371e3+Math.max(0,t)))*180/Math.PI}static halo22(){return Ee.ringOf("halo22",Ee.SIDE_PRISM_ANGLE_DEG)}static halo46(){return Ee.ringOf("halo46",Ee.END_PRISM_ANGLE_DEG)}static ringOf(t,e){const i=Ee.minimumDeviationDeg(e,Ee.ICE_INDEX_RED),n=Ee.minimumDeviationDeg(e,Ee.ICE_INDEX_BLUE);return{id:t,angleDeg:(i+n)/2,redAngleDeg:i,blueAngleDeg:n}}static strength(t,e,i=90,n=0){const s=Math.max(0,Math.min(1,t)),r=Math.max(0,1-Math.max(0,Math.min(1,e))),a=i>=0?1:n<=0?0:Math.max(0,1+i/n);return s*r*a}static formsAt(t,e=0){if(t<=-e)return[];const i=[Ee.halo22(),Ee.halo46()],n=t>0?Ee.parheliaDistanceDeg(t):void 0;n!==void 0&&i.push({id:"parhelia",angleDeg:n,redAngleDeg:n,blueAngleDeg:Ee.parheliaDistanceDeg(t,Ee.ICE_INDEX_BLUE)}),i.push({id:"tangentArc",angleDeg:Ee.halo22().angleDeg}),t>0&&i.push({id:"parhelicCircle",angleDeg:t});const s=Ee.circumzenithalAltitudeDeg(t);return s!==void 0&&i.push({id:"circumzenithal",angleDeg:s}),t>Ee.PLATE_END_FACE_LIMIT_DEG&&i.push({id:"circumhorizontal"}),t<Ee.PILLAR_MAX_SOURCE_ALTITUDE_DEG&&i.push({id:"pillar"}),i}static PILLAR_MAX_SOURCE_ALTITUDE_DEG=20}class tr{static get WATER_INDEX_RED(){return Fn.indexAt(Fn.RED_NM)}static get WATER_INDEX_BLUE(){return Fn.indexAt(Fn.BLUE_NM)}static radiusDeg(t,e){const i=(e*e-1)/(t*t-1);if(i<0||i>1)return Number.NaN;const n=Math.acos(Math.sqrt(i)),s=Math.asin(Math.sin(n)/e),r=2*(n-s)+(t-1)*(Math.PI-2*s),a=2*Math.PI;let c=r%a;return c<0&&(c+=a),c>Math.PI&&(c=a-c),180-c*180/Math.PI}static primary(){return tr.bowOf("primary",2,0)}static secondary(){return tr.bowOf("secondary",3,0)}static bowOf(t,e,i){const n=tr.radiusDeg(e,tr.WATER_INDEX_RED),s=tr.radiusDeg(e,tr.WATER_INDEX_BLUE),r=(n+s)/2;return{id:t,radiusDeg:r,redRadiusDeg:n,violetRadiusDeg:s,topAltitudeDeg:r-i}}static alexandersBandDeg(){return{fromDeg:tr.primary().redRadiusDeg,toDeg:tr.secondary().redRadiusDeg}}static formsAt(t){return t<0?[]:[tr.bowOf("primary",2,t),tr.bowOf("secondary",3,t)].filter(e=>e.topAltitudeDeg>0)}static FULL_MOON_MAGNITUDE=-12.7;static moonlightShare(t){return Math.min(1,10**(-.4*(t-tr.FULL_MOON_MAGNITUDE)))}static strength(t,e,i){if(i<=0)return 0;const n=Math.max(0,Math.min(1,t)),s=Math.max(0,1-Math.max(0,Math.min(1,e)));return n*s}}class er{constructor(t){this.radius=t;const e=er.SEGMENTS*er.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const i=new be;i.setAttribute("position",new we(this.positions,3)),i.setAttribute("color",new we(this.colors,3)),i.setDrawRange(0,0),this.object=new yt(i,La.material()),this.object.frustumCulled=!1,La.track(this.object)}static POINTS=24;static SEGMENTS=er.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(er.ACROSS-1)*6;static HEAD_HALF_WIDTH_DEG=.15;static SPREAD_FRACTION=.05;static FADE_POWER=1.8;object;positions;colors;head;tip;brightness=0;set(t,e,i){this.head=t&&Ei(t.altitudeDeg,t.azimuthDeg,1),this.tip=e&&Ei(e.altitudeDeg,e.azimuthDeg,1),this.brightness=i,this.rebuild()}rebuild(){const t=this.object.geometry,e=this.head,i=this.tip;if(!e||!i||this.brightness<=0){t.setDrawRange(0,0);return}const n=this.angleBetween(e,i);if(n<=0){t.setDrawRange(0,0);return}const s=n*er.SPREAD_FRACTION*Math.PI/180,r=h=>this.scale(this.slerp(e,i,h),this.radius),a=h=>this.radius*(er.HEAD_HALF_WIDTH_DEG*Math.PI/180+s*h),c=h=>this.brightness*(1-h)**er.FADE_POWER;let l=0;for(let h=1;h<er.POINTS;h++){const u=(h-1)/er.SEGMENTS,d=h/er.SEGMENTS;l=this.pushBand(l,r(u),r(d),a(u),a(d),c(u),c(d))}t.setDrawRange(0,l),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}pushBand(t,e,i,n,s,r,a){const c=this.normalise(this.cross(this.normalise(e),this.normalise(this.subtract(i,e))));for(let l=0;l<er.ACROSS-1;l++){const h=l-1,u=l,d=this.across(e,c,n,h),f=this.across(i,c,s,h),p=this.across(e,c,n,u),m=this.across(i,c,s,u),g=(v,M)=>v===0?M:0;t=this.push(t,d,g(h,r)),t=this.push(t,f,g(h,a)),t=this.push(t,p,g(u,r)),t=this.push(t,f,g(h,a)),t=this.push(t,m,g(u,a)),t=this.push(t,p,g(u,r))}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i){const n=t*3;this.positions[n]=e.x,this.positions[n+1]=e.y,this.positions[n+2]=e.z;const s=Bt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.55,this.colors[n+1]=s*.75,this.colors[n+2]=s,t+1}slerp(t,e,i){const n=this.angleBetweenRadians(t,e);if(n<1e-9)return t;const s=Math.sin(n),r=Math.sin((1-i)*n)/s,a=Math.sin(i*n)/s;return{x:t.x*r+e.x*a,y:t.y*r+e.y*a,z:t.z*r+e.z*a}}angleBetween(t,e){return this.angleBetweenRadians(t,e)*180/Math.PI}angleBetweenRadians(t,e){const i=t.x*e.x+t.y*e.y+t.z*e.z;return Math.acos(Math.min(1,Math.max(-1,i)))}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class WN{object=new Ke;radius;tiers;drawn=[];constructor(t){this.radius=t,this.object.name="satellites",this.tiers=iu.map(e=>{const i=new ir(new be,Vt.material(e.size));return Vt.track(i),i.frustumCulled=!1,this.object.add(i),i})}set(t,e,i,n){const s=this.tiers.map(()=>[]);this.drawn=[];for(const r of t){if(r.magnitude>e)continue;const a=i(r.position);if(a<=0)continue;const c=r.magnitude-2.5*Math.log10(a);if(c>e)continue;const l=Ch(c,e),h=Py(l),{x:u,y:d,z:f}=Ei(r.position.altitudeDeg,r.position.azimuthDeg,this.radius),[p,m,g]=n(r.position,c);s[h].push({x:u,y:d,z:f,r:p,g:m,b:g,seed:r.norad*.6180339887%1}),this.drawn.push({satellite:r,direction:new T(u,d,f).normalize()})}this.tiers.forEach((r,a)=>{const c=s[a],l=new Float32Array(c.length*3),h=new Float32Array(c.length*3),u=new Float32Array(c.length);c.forEach((f,p)=>{l.set([f.x,f.y,f.z],p*3),h.set([f.r,f.g,f.b],p*3),u[p]=f.seed}),r.geometry.dispose();const d=new be;d.setAttribute("position",new we(l,3)),d.setAttribute("color",new we(h,3)),d.setAttribute("seed",new we(u,1)),r.geometry=d})}get count(){return this.drawn.length}nearest(t,e){let i,n=e;for(const s of this.drawn){const r=s.direction.dot(t);r>n&&(n=r,i=s.satellite)}return i}dispose(){for(const t of this.tiers)t.geometry.dispose(),t.material.dispose();this.object.removeFromParent(),this.drawn=[]}}class Um{constructor(t){this.state=t}next(){this.state=this.state+1831565813|0;let t=this.state;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}between(t,e){return t+this.next()*(e-t)}}class br{static MIN_DURATION_MS=250;static MAX_DURATION_MS=1400;static schedule(t){const{ratePerHour:e,durationMs:i,velocityKmS:n,seed:s}=t;if(e<=0||i<=0)return[];const r=e*i/36e5,a=new Um(s),c=Math.floor(r),l=c+(a.next()<r-c?1:0),h=[];for(let u=0;u<l;u++){const d=Math.min(1,Math.max(0,(n-20)/52)),f=br.MAX_DURATION_MS-d*(br.MAX_DURATION_MS-br.MIN_DURATION_MS),p=a.between(5,70);h.push({t:a.between(0,i),durationMs:f*a.between(.7,1.3),fromRadiantDeg:p,bearingDeg:a.between(0,360),lengthDeg:Math.sin(p*Math.PI/180)*a.between(8,40)*(.6+d),brightness:a.next()**3}),h.sort((m,g)=>m.t-g.t)}return h}static FAINTEST_MAGNITUDE=6.5;static BRIGHTEST_MAGNITUDE=-4;static magnitudeOf(t){return br.FAINTEST_MAGNITUDE-(br.FAINTEST_MAGNITUDE-br.BRIGHTEST_MAGNITUDE)*t.brightness}static aliveAt(t,e){return t.filter(i=>e>=i.t&&e<=i.t+i.durationMs).map(i=>({meteor:i,progress:(e-i.t)/i.durationMs}))}}class Zo{object=new Ke;radius;core;glow;flashKey;static CORE_WIDTH_DEG=.06;static GLOW_WIDTH_DEG=.5;static SEGMENTS=28;static CORE_RELATIVE=1e3;constructor(t){this.radius=t,this.object.name="lightning-bolt",this.core=new Is({color:15659775,transparent:!0,opacity:0,blending:Cn,depthWrite:!1,fog:!1}),this.glow=new Is({color:10466559,transparent:!0,opacity:0,blending:Cn,depthWrite:!1,fog:!1}),this.object.visible=!1,this.object.renderOrder=5.95}set(t,e,i){if(!t||!t.cloudToGround||e<=.01){this.object.visible=!1;return}const n=`${t.channelSeed}:${Math.round(i)}`;n!==this.flashKey&&this.build(t,i,n),this.core.color.setHex(15659775).multiplyScalar(Zo.CORE_RELATIVE*Math.min(1,e*1.4)),this.glow.color.setHex(10466559).multiplyScalar(.1*Zo.CORE_RELATIVE*e*.35),this.core.opacity=1,this.glow.opacity=1,this.object.visible=!0}build(t,e,i){this.flashKey=i;for(const l of[...this.object.children])l.geometry.dispose(),this.object.remove(l);const n=new Um(t.channelSeed),s=Math.atan2(e,t.distanceM)*180/Math.PI,r=this.channel(n,t.azimuthDeg,s,0,1),a=[r],c=1+Math.floor(n.next()*2);for(let l=0;l<c;l++){const h=r[Math.floor(n.between(.15,.5)*r.length)];a.push(this.channel(n,h.azimuthDeg,h.altitudeDeg,h.altitudeDeg*n.between(.3,.7),.5))}for(const l of a)this.object.add(new yt(this.ribbon(l,Zo.GLOW_WIDTH_DEG),this.glow)),this.object.add(new yt(this.ribbon(l,Zo.CORE_WIDTH_DEG),this.core))}channel(t,e,i,n,s){const r=[],a=i-n;let c=e;for(let l=0;l<=Zo.SEGMENTS;l++){const h=i-a*l/Zo.SEGMENTS;r.push({azimuthDeg:c,altitudeDeg:h}),c+=t.between(-1,1)*a*.06*s}return r}ribbon(t,e){const i=new Float32Array(t.length*2*3),n=[],s=this.radius*Math.tan(e*Math.PI/180)/2,r=t.map(c=>{const{x:l,y:h,z:u}=Ei(c.altitudeDeg,c.azimuthDeg,this.radius);return new T(l,h,u)});r.forEach((c,l)=>{const h=r[Math.min(l+1,r.length-1)],u=r[Math.max(l-1,0)],f=h.clone().sub(u).normalize().cross(c.clone().normalize()).normalize().multiplyScalar(s);if(i.set([c.x+f.x,c.y+f.y,c.z+f.z],l*6),i.set([c.x-f.x,c.y-f.y,c.z-f.z],l*6+3),l<r.length-1){const p=l*2;n.push(p,p+1,p+2,p+1,p+3,p+2)}});const a=new be;return a.setAttribute("position",new we(i,3)),a.setIndex(n),a}dispose(){for(const t of this.object.children)t.geometry.dispose();this.core.dispose(),this.glow.dispose(),this.object.removeFromParent()}}class gn{static MIN_INTERVAL_S=8;static MAX_INTERVAL_S=25;static SEVERE_MIN_INTERVAL_S=2;static SEVERE_MAX_INTERVAL_S=8;static CLOUD_TO_GROUND_FRACTION=.25;static MIN_DISTANCE_M=1e3;static MAX_DISTANCE_M=15e3;static INTERSTROKE_MS=60;static STROKE_DECAY_MS=40;static SOUND_SPEED_M_S=343;static schedule(t){const e=new Um(t.seed),i=[],{minS:n,maxS:s}=gn.intervalFor(t.intensity??.5);let r=e.between(0,s)*1e3;for(;r<t.durationMs;){const a=e.next()<gn.CLOUD_TO_GROUND_FRACTION,c=gn.MIN_DISTANCE_M,l=gn.MAX_DISTANCE_M,h=Math.sqrt(e.between(c*c,l*l)),u=a?1+Math.floor(e.next()*4):1,d=[];let f=0;for(let p=0;p<u;p++)d.push({offsetMs:f,intensity:p===0?1:e.between(.4,.9)}),f+=gn.INTERSTROKE_MS*e.between(.5,1.6);i.push({t:r,azimuthDeg:e.between(0,360),distanceM:h,cloudToGround:a,strokes:d,channelSeed:Math.floor(e.next()*2**31)}),r+=e.between(n,s)*1e3}return i}static intervalFor(t){const e=Math.min(1,Math.max(0,(t-.5)/.5));return{minS:gn.MIN_INTERVAL_S-e*(gn.MIN_INTERVAL_S-gn.SEVERE_MIN_INTERVAL_S),maxS:gn.MAX_INTERVAL_S-e*(gn.MAX_INTERVAL_S-gn.SEVERE_MAX_INTERVAL_S)}}static brightnessAt(t,e){let i=0;for(const n of t.strokes){const s=e-t.t-n.offsetMs;s<0||s>gn.STROKE_DECAY_MS*6||(i+=n.intensity*Math.exp(-s/gn.STROKE_DECAY_MS))}return Math.min(1,i)}static endOf(t){const e=t.strokes[t.strokes.length-1];return t.t+e.offsetMs+gn.STROKE_DECAY_MS*6}static thunderDelayMs(t){return t.distanceM/gn.SOUND_SPEED_M_S*1e3}}class Ph{static ODD_RADIUS_WEDGES_DEG=[28,56,80];static STANDS_OUT=1.5;static NEIGHBOURHOOD_DEG=2.5;static oddRadiiDeg(){const t=(Ee.ICE_INDEX_RED+Ee.ICE_INDEX_BLUE)/2;return Ph.ODD_RADIUS_WEDGES_DEG.map(e=>Ee.minimumDeviationDeg(e,t)).filter(e=>Number.isFinite(e))}static at(t,e,i,n){const s=Math.PI/180,r=t,a=Math.abs(i),c=Math.sin(r*s)*Math.sin(e*s)+Math.cos(r*s)*Math.cos(e*s)*Math.cos(a*s),l=Math.acos(Math.max(-1,Math.min(1,c)))/s,h=Math.atan2(Math.sin(a*s)*Math.cos(e*s),Math.cos(r*s)*Math.sin(e*s)-Math.sin(r*s)*Math.cos(e*s)*Math.cos(a*s))/s,u=Math.abs(e-r),d=()=>{const M=n(e,a);if(!(M>0))return!1;const w=Ph.NEIGHBOURHOOD_DEG,y=1/Math.max(.2,Math.cos(e*s)),x=[n(e+w,a),n(e-w,a),n(e,a+w*y),n(e,Math.max(0,a-w*y))].sort((b,E)=>b-E);return M>x[1]*Ph.STANDS_OUT},f=()=>{const M=w=>{const y=l*s,x=w*s,b=Math.cos(y)*Math.cos(r*s)-Math.sin(y)*Math.cos(x)*Math.sin(r*s),E=Math.sin(y)*Math.sin(x),S=Math.cos(y)*Math.sin(r*s)+Math.sin(y)*Math.cos(x)*Math.cos(r*s);return n(Math.asin(Math.max(-1,Math.min(1,S)))/s,Math.abs(Math.atan2(E,b)/s))};return(M(70)+M(110)+M(250)+M(290))/4},p=(M,w=0)=>{if(d())return w>0&&!(n(e,a)>f()*w)?void 0:M};if(r>0&&r<Ee.PARHELIA_MAX_SUN_ALTITUDE_DEG&&u<2.5){const M=Ee.parheliaAzimuthDeg(r);if(M!==void 0&&a>=M-1.2&&a<=M+7){const w=p({id:"parhelion",angleDeg:Ee.parheliaDistanceDeg(r)},2.5);if(w)return w}}if(r>0&&u<2.5&&Math.abs(a-120)<4){const M=p({id:"parhelion120",angleDeg:120},0);if(M)return M}const m=Ee.circumzenithalAltitudeDeg(r);if(m!==void 0&&e>m-2&&e<m+4){const M=p({id:"circumzenithal",angleDeg:m});if(M)return M}if(r>Ee.PLATE_END_FACE_LIMIT_DEG){const M=Ee.circumzenithalAltitudeDeg(90-r);if(M!==void 0){const w=90-M;if(e>w-4&&e<w+2){const y=p({id:"circumhorizontal",angleDeg:w});if(y)return y}}}if(a<3&&r>0){if(e>r+3&&e<r+25&&r<Ee.PILLAR_MAX_SOURCE_ALTITUDE_DEG){const M=p({id:"pillar"});if(M)return M}if(Math.abs(e+r)<3){const M=p({id:"subsun"});if(M)return M}}const g=Ee.halo22();if(l>g.redAngleDeg-.6&&l<g.blueAngleDeg+2.5){const M=Math.abs(h)<50,w=Math.abs(h)>130;if(M||w){const y=p({id:M?"upperTangentArc":"lowerTangentArc",angleDeg:g.angleDeg},1.5);if(y)return y}}for(const M of Ph.oddRadiiDeg())if(l>M-.6&&l<M+1.8){const w=p({id:"oddRadius",angleDeg:M});if(w)return w}if(l>g.redAngleDeg-.6&&l<g.blueAngleDeg+2.5){const M=p({id:"halo22",angleDeg:g.angleDeg});if(M)return M}const v=Ee.halo46();if(l>v.redAngleDeg-.6&&l<v.blueAngleDeg+3){const M=p({id:"halo46",angleDeg:v.angleDeg});if(M)return M}if(r>0&&u<1.2){const M=n(e,a),w=Math.max(n(e+3,a),n(e-3,a));if(M>0&&M>w*2)return{id:"parhelicCircle",angleDeg:r}}}}class Ls{static RED_NM=656.3;static BLUE_NM=435.8;static ANCHOR_RED=1.3067;static ANCHOR_BLUE=1.317;static B=(Ls.ANCHOR_BLUE-Ls.ANCHOR_RED)/(1/(Ls.BLUE_NM*Ls.BLUE_NM)-1/(Ls.RED_NM*Ls.RED_NM));static A=Ls.ANCHOR_RED-Ls.B/(Ls.RED_NM*Ls.RED_NM);static indexAt(t){return Ls.A+Ls.B/(t*t)}}class pa{static MAX_FACES=20;normals=new Float64Array(pa.MAX_FACES*3);offsets=new Float64Array(pa.MAX_FACES);faceCount=8;radius=1;set(t,e,i,n,s,r,a=0){let c=0,l=0,h=0;Math.abs(i)<.9?(c=-e,l=t,h=0):(c=0,l=-i,h=e);const u=Math.hypot(c,l,h)||1;c/=u,l/=u,h/=u;const d=e*h-i*l,f=i*c-t*h,p=t*l-e*c,m=s/2,g=r/2;for(let v=0;v<6;v++){const M=n+v*Math.PI/3,w=Math.cos(M),y=Math.sin(M);this.normals[v*3]=c*w+d*y,this.normals[v*3+1]=l*w+f*y,this.normals[v*3+2]=h*w+p*y,this.offsets[v]=m}if(this.normals[18]=t,this.normals[19]=e,this.normals[20]=i,this.offsets[6]=g,this.normals[21]=-t,this.normals[22]=-e,this.normals[23]=-i,this.offsets[7]=g,this.faceCount=8,a>0){const v=pa.PYRAMID_TILT,M=Math.cos(v),w=Math.sin(v),y=Math.min(g,a*m*Math.tan(v)),x=g-y,b=M*x+w*m;for(let E=0;E<6;E++){const S=E*3,A=(8+E)*3,_=(14+E)*3;this.normals[A]=M*t+w*this.normals[S],this.normals[A+1]=M*e+w*this.normals[S+1],this.normals[A+2]=M*i+w*this.normals[S+2],this.normals[_]=-M*t+w*this.normals[S],this.normals[_+1]=-M*e+w*this.normals[S+1],this.normals[_+2]=-M*i+w*this.normals[S+2],this.offsets[8+E]=b,this.offsets[14+E]=b}this.faceCount=pa.MAX_FACES}this.radius=Math.hypot(m*2/Math.sqrt(3),g)}static rollToward(t,e,i,n,s,r){let a,c,l;Math.abs(i)<.9?(a=-e,c=t,l=0):(a=0,c=-i,l=e);const h=Math.hypot(a,c,l)||1;a/=h,c/=h,l/=h;const u=e*l-i*c,d=i*a-t*l,f=t*c-e*a;return Math.atan2(n*u+s*d+r*f,n*a+s*c+r*l)}get aimRadius(){return this.radius}trace(t,e,i,n,s,r,a){let c=-e,l=t,h=0,u=Math.hypot(c,l,h);u<1e-6&&(c=1,l=0,h=0,u=1),c/=u,l/=u,h/=u;const d=e*h-i*l,f=i*c-t*h,p=t*l-e*c,m=c*n+d*s-t*this.radius*2,g=l*n+f*s-e*this.radius*2,v=h*n+p*s-i*this.radius*2;let M=-1,w=-1/0,y=1/0;for(let Z=0;Z<this.faceCount;Z++){const nt=this.normals[Z*3],ot=this.normals[Z*3+1],Ut=this.normals[Z*3+2],Zt=nt*t+ot*e+Ut*i,jt=this.offsets[Z]-(nt*m+ot*g+Ut*v);if(Zt>1e-9){const K=jt/Zt;K<y&&(y=K)}else if(Zt<-1e-9){const K=jt/Zt;K>w&&(w=K,M=Z)}else if(jt<0)return 0}if(M<0||w>=y)return 0;let x=0;const b=this.normals[M*3],E=this.normals[M*3+1],S=this.normals[M*3+2],A=-(b*t+E*e+S*i),_=im.reflectance(A,1,r);a[x].x=t+2*A*b,a[x].y=e+2*A*E,a[x].z=i+2*A*S,a[x].weight=_,x++;const I=1/r,D=Math.sqrt(Math.max(0,1-I*I*(1-A*A)));let O=I*t+(I*A-D)*b,P=I*e+(I*A-D)*E,N=I*i+(I*A-D)*S,k=m+t*w,B=g+e*w,W=v+i*w,Q=1-_;for(let Z=0;Z<pa.MAX_BOUNCES&&Q>pa.MIN_WEIGHT;Z++){let nt=-1,ot=1/0;for(let V=0;V<this.faceCount;V++){const Lt=this.normals[V*3],Xt=this.normals[V*3+1],kt=this.normals[V*3+2],Rt=Lt*O+Xt*P+kt*N;if(Rt<=1e-9)continue;const te=(this.offsets[V]-(Lt*k+Xt*B+kt*W))/Rt;te>1e-9&&te<ot&&(ot=te,nt=V)}if(nt<0)break;const Ut=this.normals[nt*3],Zt=this.normals[nt*3+1],jt=this.normals[nt*3+2],K=Ut*O+Zt*P+jt*N,lt=r*Math.sqrt(Math.max(0,1-K*K));if(k+=O*ot,B+=P*ot,W+=N*ot,lt<1){const V=Math.sqrt(Math.max(0,1-lt*lt)),Lt=im.reflectance(K,r,1);if(a[x].x=r*O-(r*K-V)*Ut,a[x].y=r*P-(r*K-V)*Zt,a[x].z=r*N-(r*K-V)*jt,a[x].weight=Q*(1-Lt),x++,x>=a.length)return x;Q*=Lt}const ct=2*K;O-=ct*Ut,P-=ct*Zt,N-=ct*jt}return x}static MAX_BOUNCES=6;static PYRAMID_TILT=62*Math.PI/180;static MIN_WEIGHT=1e-4}class qe{static AZIMUTH_BINS=512;static ALTITUDE_BINS=512;static DEFAULT_POPULATIONS=[{orientation:"tumbling",widthMicrons:50,lengthMicrons:50,share:.48},{orientation:"plate",widthMicrons:100,lengthMicrons:15,share:.27},{orientation:"column",widthMicrons:40,lengthMicrons:120,share:.18},{orientation:"parry",widthMicrons:40,lengthMicrons:120,share:.02},{orientation:"pyramidal",widthMicrons:40,lengthMicrons:120,share:.03,capFraction:.5},{orientation:"lowitz",widthMicrons:100,lengthMicrons:15,share:.02}];static DEFAULT_RARE_SHARE=n_;static populationsFor(t){const e=Math.min(.9,Math.max(0,t));if(Math.abs(e-qe.DEFAULT_RARE_SHARE)<1e-9)return qe.DEFAULT_POPULATIONS;const i=(1-e)/(1-qe.DEFAULT_RARE_SHARE);return qe.DEFAULT_POPULATIONS.map(n=>n.orientation==="pyramidal"||n.orientation==="lowitz"?{...n,share:n.share/qe.DEFAULT_RARE_SHARE*e}:{...n,share:n.share*i})}populations=qe.DEFAULT_POPULATIONS;populationTotal=1;static WORST_TILT_DEG=180;static BEST_TILT_DEG=.5;static SOURCE_RADIUS_DEG=.265;static UNDEVIATED_DEG=.6;crystal=new pa;emergent=Array.from({length:pa.MAX_BOUNCES+2},()=>({x:0,y:0,z:0,weight:0}));tally=new Float32Array(qe.AZIMUTH_BINS*qe.ALTITUDE_BINS*3);radiance=new Float32Array(qe.AZIMUTH_BINS*qe.ALTITUDE_BINS*3);scratch=new Float32Array(qe.AZIMUTH_BINS*qe.ALTITUDE_BINS*3);seed=1;spare=0;hasSpare=!1;altitude=0;tilt=0;alignment=0;traced=0;begin(t,e,i=2654435769,n=qe.DEFAULT_POPULATIONS){this.populations=n,this.populationTotal=n.reduce((r,a)=>r+a.share,0)||1,this.seed=i>>>0||1,this.hasSpare=!1,this.tally.fill(0),this.traced=0,this.altitude=t*Math.PI/180,this.alignment=Math.min(1,Math.max(0,e));const s=qe.WORST_TILT_DEG*(qe.BEST_TILT_DEG/qe.WORST_TILT_DEG)**this.alignment;this.tilt=s*Math.PI/180}trace(t){const e=qe.AZIMUTH_BINS,i=qe.ALTITUDE_BINS,n=this.tally,s=qe.SOURCE_RADIUS_DEG*Math.PI/180,r=Math.cos(qe.UNDEVIATED_DEG*Math.PI/180),a=this.altitude;for(let c=0;c<t;c++){const l=this.pickPopulation();this.orient(l,this.tilt);const h=this.random()*2*Math.PI,u=s*Math.sqrt(this.random()),d=a+u*Math.sin(h),f=u*Math.cos(h)/Math.max(.05,Math.cos(a)),p=-Math.cos(d)*Math.cos(f),m=-Math.cos(d)*Math.sin(f),g=-Math.sin(d),v=this.crystal.aimRadius,M=(this.random()*2-1)*v,w=(this.random()*2-1)*v,y=4*v*v,x=_n.SAMPLES[this.random()*_n.SAMPLES.length|0],b=this.crystal.trace(p,m,g,M,w,Ls.indexAt(x.wavelengthNm),this.emergent);for(let E=0;E<b;E++){const S=this.emergent[E],A=Math.hypot(S.x,S.y,S.z);if(A<1e-9||S.weight<=0)continue;const _=S.x/A,I=S.y/A,D=S.z/A;if(_*p+I*m+D*g>r)continue;const O=Math.asin(Math.max(-1,Math.min(1,-D))),P=Math.abs(Math.atan2(-I,-_)),N=Math.min(e-1,P/Math.PI*e|0),B=(Math.min(i-1,(O+Math.PI/2)/Math.PI*i|0)*e+N)*3,W=S.weight*y*_n.SAMPLES.length;n[B]+=W*x.r,n[B+1]+=W*x.g,n[B+2]+=W*x.b}}this.traced+=t}get tracedRays(){return this.traced}harvest(){const t=qe.AZIMUTH_BINS,e=qe.ALTITUDE_BINS;return this.toRadiance(t,e),this.smooth(t,e),{width:t,height:e,data:this.radiance,sourceAltitudeDeg:this.altitude*180/Math.PI,alignment:this.alignment,rays:this.traced}}compute(t,e,i,n,s){return this.begin(t,e,n,s),this.trace(i),this.harvest()}toRadiance(t,e){const i=2*Math.PI/t,n=Math.max(1,this.traced),s=4*qe.REFERENCE_MICRONS*qe.REFERENCE_MICRONS;for(let r=0;r<e;r++){const a=Math.sin(r/e*Math.PI-Math.PI/2),c=Math.sin((r+1)/e*Math.PI-Math.PI/2),l=1/(i*(c-a)*n*s);for(let h=0;h<t;h++){const u=(r*t+h)*3;this.radiance[u]=this.tally[u]*l,this.radiance[u+1]=this.tally[u+1]*l,this.radiance[u+2]=this.tally[u+2]*l}}}static REFERENCE_MICRONS=50;smooth(t,e){const i=this.scratch,n=this.radiance;i.set(n);for(let r=0;r<e;r++){const a=r*t*3;for(let c=0;c<3;c++){let l=i[a+c];for(let h=0;h<t;h++){const u=a+h*3+c,d=h+1<t?i[u+3]:i[u];n[u]=(l+2*i[u]+d)/4,l=i[u]}}}i.set(n);const s=t*3;for(let r=0;r<e;r++){const a=r>0?-s:0,c=r+1<e?s:0,l=r*s;for(let h=l;h<l+s;h++)n[h]=(i[h+a]+2*i[h]+i[h+c])/4}}pickPopulation(){const t=this.random()*this.populationTotal;let e=0;for(const i of this.populations)if(e+=i.share,t<=e)return i;return this.populations[this.populations.length-1]}orient(t,e){const i=this.random()*2*Math.PI;let n=this.random()*2*Math.PI,s=0,r=0,a=1;switch(t.orientation){case"pyramidal":case"tumbling":{a=this.random()*2-1;const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"plate":{a=this.spreadAboutAnAxis(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i);break}case"column":case"parry":{a=this.spreadAboutAPlane(e);const c=Math.sqrt(Math.max(0,1-a*a));s=c*Math.cos(i),r=c*Math.sin(i),t.orientation==="parry"&&(n=Math.PI/2+this.gaussian()*e);break}}if(t.orientation==="lowitz"){const c=this.spreadAboutAPlane(e),l=Math.sqrt(Math.max(0,1-c*c)),h=l*Math.cos(i),u=l*Math.sin(i),d=c;let f=-d*h,p=-d*u,m=1-d*d;const g=Math.hypot(f,p,m)||1;f/=g,p/=g,m/=g;const v=u*m-d*p,M=d*f-h*m,w=h*p-u*f,y=this.random()*2*Math.PI;s=f*Math.cos(y)+v*Math.sin(y),r=p*Math.cos(y)+M*Math.sin(y),a=m*Math.cos(y)+w*Math.sin(y),n=pa.rollToward(s,r,a,h,u,d)+Math.PI/6}this.crystal.set(s,r,a,n,t.widthMicrons,t.lengthMicrons,t.capFraction??0)}random(){this.seed=this.seed+1831565813>>>0;let t=this.seed;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}spreadAboutAnAxis(t){const e=1/Math.max(1e-6,t*t),i=Math.max(1e-12,this.random()),n=1+Math.log(i+(1-i)*Math.exp(-2*e))/e;return Math.max(-1,Math.min(1,n))}spreadAboutAPlane(t){for(let e=0;e<8;e++){const i=this.gaussian()*t;if(i>=-1&&i<=1)return i}return this.random()*2-1}gaussian(){if(this.hasSpare)return this.hasSpare=!1,this.spare;const t=Math.sqrt(-2*Math.log(Math.max(1e-12,this.random()))),e=2*Math.PI*this.random();return this.spare=t*Math.sin(e),this.hasSpare=!0,t*Math.cos(e)}}class XN{static fromRadiance(t,e){const i=Gn.toHalfFloat(1);for(let n=0,s=0;s<t.length;n+=4,s+=3)e[n]=Gn.toHalfFloat(t[s]),e[n+1]=Gn.toHalfFloat(t[s+1]),e[n+2]=Gn.toHalfFloat(t[s+2]),e[n+3]=i}}class Zi{static RADIUS=880;static RAYS=9e5;static RAYS_PER_BATCH=2e3;static BUDGET_MS=6;static URGENT_BUDGET_MS=40;static ALTITUDE_STEP_DEG=1;static ALIGNMENT_STEP=.05;static LEAP_ALTITUDE_DEG=5;static LEAP_ALIGNMENT=.25;static GAIN=.55;setCloudOffset(t){this.material.uniforms.uFieldOffset.value.copy(t)}object;material;sky=new qe;texture;texels;mappedAltitudeDeg=Number.NaN;mappedAlignment=Number.NaN;mappedRare=Number.NaN;tracing=!1;everDisplayed=!1;urgent=!1;workHandle;onRepaint;constructor(){const t=qe.AZIMUTH_BINS,e=qe.ALTITUDE_BINS;this.texels=new Uint16Array(t*e*4),this.texture=new Ds(this.texels,t,e,tn,Ye),this.texture.minFilter=Me,this.texture.magFilter=Me,this.texture.wrapS=Qi,this.texture.wrapT=Qi,this.texture.needsUpdate=!0,this.material=new De({uniforms:{uSource:{value:new T(0,1,0)},uUp:{value:new T(0,1,0)},uStrength:{value:0},uTint:{value:new T(1,.97,.92)},uIceCover:{value:0},uIceHeight:{value:1},uFieldOffset:{value:new T},uMap:{value:this.texture},uGain:{value:Zi.GAIN}},vertexShader:`
|
|
8917
8928
|
varying vec3 vDirection;
|
|
8918
8929
|
void main() {
|
|
8919
8930
|
vDirection = normalize((modelMatrix * vec4(position, 1.0)).xyz - cameraPosition);
|
|
@@ -8942,7 +8953,7 @@ ${Vt.OUTPUT_PROJECTION_GLSL}`)}}class rs{constructor(t,e){this.width=t,this.heig
|
|
|
8942
8953
|
if (ice <= 0.0) discard;
|
|
8943
8954
|
gl_FragColor = vec4(iceHaloLight(dir, ice), 1.0);
|
|
8944
8955
|
}
|
|
8945
|
-
`,transparent:!0,blending:Cn,depthWrite:!1,side:zi,fog:!1}),this.object=new yt(new hn(Zi.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(t){this.hostedByDeck=t,this.show(this.shown)}show(t){this.shown=t,this.object.visible=t&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=t?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(t){this.urgent=t}set onReady(t){this.onRepaint=t}update(t,e,i,n,s,r,a=qe.DEFAULT_RARE_SHARE){const c=this.material.uniforms;if(i<=0){c.uStrength.value=0,this.show(!1),this.stopWork();return}c.uSource.value.set(t.x,t.y,t.z).normalize(),c.uStrength.value=i,c.uTint.value.set(n[0],n[1],n[2]),c.uIceCover.value=s.cover,c.uIceHeight.value=s.layerHeight,this.show(this.everDisplayed),this.requestMap(e,r,a)}featureAt(t){const e=this.material.uniforms;if(!this.everDisplayed||!(e.uStrength.value>0)||this.mappedAltitudeDeg!==this.mappedAltitudeDeg)return;const i=e.uUp.value.clone().normalize(),n=e.uSource.value.clone().normalize(),s=Math.PI/180,r=Math.asin(Math.max(-1,Math.min(1,t.dot(i))))/s,a=Math.asin(Math.max(-1,Math.min(1,n.dot(i))))/s,c=g=>g.clone().sub(i.clone().multiplyScalar(g.dot(i))),l=c(n),h=c(t),u=l.length()<1e-4||h.length()<1e-4?0:Math.acos(Math.max(-1,Math.min(1,l.dot(h)/(l.length()*h.length()))))/s,d=qe.AZIMUTH_BINS,f=qe.ALTITUDE_BINS,p=this.texels,m=(g,v)=>{if(g<-90||g>90)return 0;const M=Math.min(d-1,Math.max(0,Math.floor(Math.min(180,Math.abs(v))/180*d))),w=Math.min(f-1,Math.max(0,Math.floor((g+90)/180*f)));return Zi.halfToFloat(p[(w*d+M)*4+1])};return Ph.at(a,r,u,m)}static halfToFloat(t){const e=t>>10&31,i=t&1023,n=t>>15?-1:1;return e===0?n*i*5960464477539063e-23:n*2**(e-15)*(1+i/1024)}requestMap(t,e,i){if(!(!(Math.abs(t-this.mappedAltitudeDeg)<Zi.ALTITUDE_STEP_DEG)||!(Math.abs(e-this.mappedAlignment)<Zi.ALIGNMENT_STEP)||!(Math.abs(i-this.mappedRare)<Zi.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(t,e,i)){this.next=void 0;return}if(!(!(Math.abs(t-this.pendingAltitudeDeg)<Zi.LEAP_ALTITUDE_DEG)||!(Math.abs(e-this.pendingAlignment)<Zi.LEAP_ALIGNMENT)||!(Math.abs(i-this.pendingRare)<Zi.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:t,alignment:e,rare:i};return}}this.next=void 0,this.pendingAltitudeDeg=t,this.pendingAlignment=e,this.pendingRare=i,this.stopWork(),this.tracing=!0,this.startTracing(t,e,i)}startTracing(t,e,i){const n=++this.ticket,s=()=>{n!==this.ticket||!this.tracing||(this.sky.begin(t,e,void 0,qe.populationsFor(i)),this.scheduleWork())};sc.with(r=>{n!==this.ticket||!this.tracing||(this.job=r.trace(t,e,i,Zi.RAYS,a=>{this.job=void 0,this.texels.set(a),this.display(),this.finishTracing()},s))},s)}ticket=0;job;pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;pendingRare=Number.NaN;next;tracingFor(t,e,i){return this.tracing&&Math.abs(t-this.pendingAltitudeDeg)<Zi.ALTITUDE_STEP_DEG&&Math.abs(e-this.pendingAlignment)<Zi.ALIGNMENT_STEP&&Math.abs(i-this.pendingRare)<Zi.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const t=()=>{if(this.workHandle=void 0,!this.tracing)return;const e=performance.now(),i=this.urgent?Zi.URGENT_BUDGET_MS:Zi.BUDGET_MS;do this.sky.trace(Zi.RAYS_PER_BATCH);while(this.sky.tracedRays<Zi.RAYS&&performance.now()-e<i);if(this.sky.tracedRays>=Zi.RAYS){this.publish(),this.finishTracing();return}this.workHandle=requestAnimationFrame(t)};this.workHandle=requestAnimationFrame(t)}finishTracing(){this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment,this.mappedRare=this.pendingRare;const t=this.next;t&&this.requestMap(t.sourceAltitudeDeg,t.alignment,t.rare)}stopWork(){this.ticket++,this.job?.cancel(),this.job=void 0,this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){XN.fromRadiance(this.sky.harvest().data,this.texels),this.display()}display(){this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class kn{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=kn.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(kn.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];heads=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const t=kn.MAX_CONCURRENT*kn.SEGMENTS*kn.VERTICES_PER_SEGMENT;this.positions=new Float32Array(t*3),this.colors=new Float32Array(t*3);const e=new be;e.setAttribute("position",new ye(this.positions,3)),e.setAttribute("color",new ye(this.colors,3)),e.setDrawRange(0,0),this.object=new yt(e,La.material()),this.object.frustumCulled=!1,La.track(this.object)}get schedule(){return this.meteors}setShower(t,e,i){this.meteors=t,this.radiantAltitudeDeg=e,this.radiantAzimuthDeg=i}update(t){const e=this.object.geometry;if(this.heads=[],this.meteors.length===0){e.setDrawRange(0,0);return}const i=br.aliveAt(this.meteors,t).slice(0,kn.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const a=this.radiantOf(s);if(!a)continue;const c=Ei(a.altitudeDeg,a.azimuthDeg,1),[l,h]=this.basisAround(c),u=s.fromRadiantDeg+r*s.lengthDeg,d=Math.max(s.fromRadiantDeg,u-s.lengthDeg*.6),f=Math.min(1,(1-r)*2.5),p=this.turn(l,h,s.bearingDeg),m=(.15+.85*s.brightness)*f,g=y=>m*y**1.6,v=y=>this.onSphere(c,p,d+(u-d)*y),M=v(1);f>0&&this.heads.push({...m3(M.x,M.y,M.z),magnitude:br.magnitudeOf(s)-2.5*Math.log10(f)});const w=y=>kn.RADIUS*((kn.MIN_HALF_WIDTH_DEG+kn.BRIGHT_HALF_WIDTH_DEG*s.brightness*y)*Math.PI/180);for(let y=1;y<kn.POINTS;y++){const x=(y-1)/kn.SEGMENTS,b=y/kn.SEGMENTS;n=this.pushRibbon(n,v(x),v(b),w(x),w(b),g(x),g(b))}}e.setDrawRange(0,n),e.getAttribute("position").needsUpdate=!0,e.getAttribute("color").needsUpdate=!0}midpointOf(t){const e=this.radiantOf(t);if(!e)return;const i=Ei(e.altitudeDeg,e.azimuthDeg,1),[n,s]=this.basisAround(i),r=this.turn(n,s,t.bearingDeg),a=this.onSphere(i,r,t.fromRadiantDeg+t.lengthDeg/2),c=Math.hypot(a.x,a.y,a.z)||1;return{altitudeDeg:Math.asin(a.y/c)*180/Math.PI,azimuthDeg:(Math.atan2(a.x,-a.z)*180/Math.PI+360)%360}}radiantOf(t){return t.radiant?t.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(t,e,i,n,s,r,a){const c=this.normalise(this.cross(this.normalise(e),this.normalise(this.subtract(i,e))));for(let l=0;l<kn.ACROSS-1;l++){const h=l-1,u=l,d=this.across(e,c,n,h),f=this.across(i,c,s,h),p=this.across(e,c,n,u),m=this.across(i,c,s,u),g=(v,M)=>v===0?M:0;t=this.push(t,d,g(h,r)),t=this.push(t,f,g(h,a)),t=this.push(t,p,g(u,r)),t=this.push(t,f,g(h,a)),t=this.push(t,m,g(u,a)),t=this.push(t,p,g(u,r))}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i){const n=t*3;this.positions[n]=e.x,this.positions[n+1]=e.y,this.positions[n+2]=e.z;const s=Bt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.9,this.colors[n+1]=s*.95,this.colors[n+2]=s,t+1}turn(t,e,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:t.x*s+e.x*r,y:t.y*s+e.y*r,z:t.z*s+e.z*r}}onSphere(t,e,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:(t.x*s+e.x*r)*kn.RADIUS,y:(t.y*s+e.y*r)*kn.RADIUS,z:(t.z*s+e.z*r)*kn.RADIUS}}basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(t,e));return[i,this.normalise(this.cross(t,i))]}subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class $n{static MEDIAN_BEDTIME=22+40/60;static MEDIAN_RISING=7;static BEDTIME_SPREAD_H=1.2;static RISING_SPREAD_H=.7;static ALWAYS_UP=.02;static LIT_WHEN_ALL_UP=.5;static UNKNOWN_HOUR=.16;static DUSK_DEG=-1;static NIGHT_DEG=-9;static awakeAt(t){const e=(t%24+24)%24,i=$n.normal(((e<12?e+24:e)-$n.MEDIAN_BEDTIME)/$n.BEDTIME_SPREAD_H),n=$n.normal((e-$n.MEDIAN_RISING)/$n.RISING_SPREAD_H),s=i*(e<12?1-n:1);return Math.max($n.ALWAYS_UP,1-s)}static shareAt(t){return t===void 0||!Number.isFinite(t)?$n.UNKNOWN_HOUR:$n.LIT_WHEN_ALL_UP*$n.awakeAt(t)}static darknessAt(t){return Math.max(0,Math.min(1,($n.DUSK_DEG-t)/($n.DUSK_DEG-$n.NIGHT_DEG)))}static share(t,e){return $n.darknessAt(t)*$n.shareAt(e)}static normal(t){const e=Math.abs(t)/Math.SQRT2,i=1/(1+.3275911*e),n=1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-e*e);return t>=0?.5*(1+n):.5*(1-n)}}class Nh{static STREETLIGHT_RIG="streetlamp";static rigOf(t){if(t.kind==="streetlight"&&!t.lights?.length)return Nh.STREETLIGHT_RIG;const e=t.lights?.map(i=>i.id).join()??"";return J0.forKind(t.kind).find(i=>i.create().map(n=>n.id).join()===e)?.id??""}static viewOf(t,e,i){const n=Xr(t,e),s=r=>Number(r.toFixed(2));return{title:t.title,eastM:s(n.eastM),northM:s(n.northM),saidPosition:t.track?t.track.find(r=>r.t===e)?.saidPosition:t.saidPosition,altitudeM:s(n.altitudeM),headingDeg:s(n.headingDeg??0),color:t.color,sizeM:t.sizeM?{...t.sizeM}:void 0,lit:Sm(t,e,i),headlights:lE(t,e),lightRig:Nh.rigOf(t),observerSide:t.observerSide,model:t.model?{...t.model}:void 0}}static apply(t,e,i,n){switch(i){case"title":return{...t,title:e.title};case"eastM":case"northM":case"saidPosition":case"altitudeM":case"headingDeg":return Nh.placed(t,e,n);case"color":return{...t,color:e.color};case"sizeM.widthM":case"sizeM.lengthM":case"sizeM.heightM":{const s=e.sizeM,r=s!==void 0&&(s.widthM!==void 0||s.lengthM!==void 0||s.heightM!==void 0);return{...t,sizeM:r?{widthM:s.widthM,lengthM:s.lengthM,heightM:s.heightM}:void 0}}case"lit":{const s=[...(t.litKeyframes??[]).filter(r=>r.t!==n),{t:n,lit:e.lit}].sort((r,a)=>r.t-a.t);return{...t,litKeyframes:s}}case"headlights":{const s=[...(t.headlightKeyframes??[]).filter(r=>r.t!==n),{t:n,mode:e.headlights}].sort((r,a)=>r.t-a.t);return{...t,headlightKeyframes:s}}case"lightRig":{if(t.kind==="streetlight"&&e.lightRig===Nh.STREETLIGHT_RIG)return{...t,lights:void 0};if(t.kind==="streetlight"&&!e.lightRig)return{...t,lights:void 0,lit:!1,litKeyframes:void 0};const s=J0.byId(e.lightRig===""?void 0:e.lightRig);return{...t,lights:s?s.create():void 0}}case"observerSide":return{...t,observerSide:du(t.kind)&&e.observerSide?e.observerSide:void 0};case"model.id":return{...t,model:e.model?.id?{id:e.model.id}:void 0};case"model":return{...t,model:e.model};default:return t}}static placed(t,e,i){const n=(e.headingDeg%360+360)%360,s=t.track??(e.altitudeM!==0?[]:void 0);if(s){const a={t:i,eastM:e.eastM,northM:e.northM,altitudeM:e.altitudeM,headingDeg:n};return e.saidPosition&&(a.saidPosition=e.saidPosition),{...t,track:[...s.filter(c=>c.t!==i),a].sort((c,l)=>c.t-l.t)}}const r={...t,eastM:e.eastM,northM:e.northM,headingDeg:n,saidPosition:e.saidPosition};return r.saidPosition||delete r.saidPosition,r}}class Ci{constructor(t,e={}){this.size=t,this.span=Math.min(t.lengthM,Math.max(0,e.spanM??t.lengthM)),this.bank=(t.lengthM-this.span)/2,this.deck=Math.min(t.heightM,e.deckThicknessM??Ci.DEFAULT_DECK_THICKNESS_M),this.railHeight=e.railing?.heightM??Ci.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,e.railing?.postSpacingM??Ci.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(e.railing?.rails??Ci.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(t){const e=Math.abs(t)-this.span/2;return e<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-e/this.bank))}build(){const{widthM:t,heightM:e}=this.size,i=this.span/2,n=[];if(this.span>0){n.push(Ci.box(t,this.deck,this.span,0,e-this.deck/2,0));for(const c of[-1,1]){const l=e-this.deck;l>0&&this.bank>0&&n.push(Ci.box(t+1,l,Ci.ABUTMENT_THICKNESS_M,0,l/2,c*(i-Ci.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(Ci.box(t,.04,this.span,0,e+.02,0));const r=[];for(const c of[-1,1])this.bank<=0||(r.push(this.embankment(c)),s.push(this.bankRoad(c)));const a=[];for(const c of[-1,1])a.push(...this.railing(c*(t/2-Ci.POST_SIDE_M)));return{concrete:Ci.merge(n),road:Ci.merge(s),earth:Ci.merge(r),railing:Ci.merge(a)}}embankment(t){const e=this.size.widthM/2,i=this.stations(t),n=[],s=(l,h,u,d)=>{n.push(l.x,l.y,l.z,h.x,h.y,h.z,u.x,u.y,u.z,l.x,l.y,l.z,u.x,u.y,u.z,d.x,d.y,d.z)},r=l=>{const h=this.roadAt(l),u=e+Ci.BANK_SLOPE*h;return{leftFoot:new T(-u,0,l),leftTop:new T(-e,h,l),rightTop:new T(e,h,l),rightFoot:new T(u,0,l)}};for(let l=1;l<i.length;l++){const h=r(i[l-1]),u=r(i[l]),d=t>0,f=(p,m,g,v)=>d?s(p,m,g,v):s(v,g,m,p);f(h.leftFoot,h.leftTop,u.leftTop,u.leftFoot),f(h.leftTop,h.rightTop,u.rightTop,u.leftTop),f(h.rightTop,h.rightFoot,u.rightFoot,u.rightTop)}const a=r(i[0]);t>0?s(a.leftFoot,a.rightFoot,a.rightTop,a.leftTop):s(a.leftTop,a.rightTop,a.rightFoot,a.leftFoot);const c=new be;return c.setAttribute("position",new pe(n,3)),c.computeVertexNormals(),c}bankRoad(t){const e=this.size.widthM/2,i=this.stations(t),n=[];for(let r=1;r<i.length;r++){const a=i[r-1],c=i[r],l=this.roadAt(a)+.02,h=this.roadAt(c)+.02,u=t>0?[[-e,l,a],[e,l,a],[e,h,c],[-e,h,c]]:[[-e,h,c],[e,h,c],[e,l,a],[-e,l,a]];for(const d of[0,2,1,0,3,2])n.push(...u[d])}const s=new be;return s.setAttribute("position",new pe(n,3)),s.computeVertexNormals(),s}stations(t){const e=[];for(let i=0;i<=Ci.BANK_STATIONS;i++)e.push(t*(this.span/2+this.bank*i/Ci.BANK_STATIONS));return e}railing(t){const e=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),n=[];for(let a=0;a<=i;a++)n.push(-e+this.size.lengthM*a/i);const s=[],r=Ci.POST_SIDE_M;for(const a of n)s.push(Ci.box(r,this.railHeight,r,t,this.roadAt(a)+this.railHeight/2,a));for(let a=1;a<=this.rails;a++){const c=this.railHeight*a/this.rails-Ci.RAIL_HEIGHT_M/2;for(let l=1;l<n.length;l++){const h=new T(t,this.roadAt(n[l-1])+c,n[l-1]),u=new T(t,this.roadAt(n[l])+c,n[l]);s.push(Ci.beam(h,u))}}return s}static box(t,e,i,n,s,r){return new en(t,e,i).translate(n,s,r)}static beam(t,e){const i=new T().subVectors(e,t),n=new en(Ci.RAIL_DEPTH_M,Ci.RAIL_HEIGHT_M,i.length()),s=new es().setFromUnitVectors(new T(0,0,1),i.clone().normalize()),r=new T().addVectors(t,e).multiplyScalar(.5);return n.applyMatrix4(new Gt().compose(r,s,new T(1,1,1)))}static merge(t){const e=t.map(c=>c.getIndex()?c.toNonIndexed():c),i=e.reduce((c,l)=>c+l.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const c of e){const l=c.getAttribute("position"),h=c.getAttribute("normal");n.set(l.array,r*3),h&&s.set(h.array,r*3),r+=l.count}const a=new be;a.setAttribute("position",new pe(n,3)),a.setAttribute("normal",new pe(s,3));for(const c of t)c.dispose();for(const c of e)c.dispose();return a}}class Pi{static OVERHANG_M=.25;static SLAB_M=.2;static MIN_RIDGE_M=.1;static DEFAULT_RISE_M=3;static normalised(t){const e=t.shape??"flat";return{shape:e,riseM:e==="flat"?0:Math.max(0,t.riseM??Pi.DEFAULT_RISE_M),ridge:t.ridge??"width",...t.color?{color:t.color}:{}}}static build(t,e,i){const n=Pi.normalised(t),s=n.shape==="gable"&&n.ridge==="depth",r=(s?i:e)/2+Pi.OVERHANG_M,a=(s?e:i)/2+Pi.OVERHANG_M,c=n.shape==="flat"||n.riseM<=0?Pi.slab(r,a):n.shape==="dome"?Pi.dome(r-Pi.OVERHANG_M,a-Pi.OVERHANG_M,r,a,n.riseM):Pi.pitched(n.shape,r,a,n.riseM);return s&&c.rotateY(Math.PI/2),c.computeVertexNormals(),c}static slab(t,e){const i=Pi.SLAB_M,n=[[-t,0,-e],[t,0,-e],[t,0,e],[-t,0,e]],s=n.map(([c,,l])=>[c,i,l]),r=[],a=(c,l,h,u)=>{r.push(c,l,h,c,h,u)};a(s[0],s[3],s[2],s[1]);for(let c=0;c<4;c++){const l=(c+1)%4;a(n[c],n[l],s[l],s[c])}return Pi.of(r)}static pitched(t,e,i,n){const s=(h,u)=>[h,0,u],r=t==="gable"?e:Math.max(Pi.MIN_RIDGE_M/2,e-i),a=[-r,n,0],c=[r,n,0],l=[];return l.push(s(-e,-i),s(e,-i),c,s(-e,-i),c,a),l.push(s(e,i),s(-e,i),a,s(e,i),a,c),l.push(s(-e,i),s(-e,-i),a),l.push(s(e,-i),s(e,i),c),l.push(s(-e,-i),s(-e,i),s(e,i),s(-e,-i),s(e,i),s(e,-i)),Pi.of(l)}static DOME_RINGS=12;static DOME_SECTORS=48;static dome(t,e,i,n,s){const r=Pi.slab(i,n).getAttribute("position").array,a=[];for(let l=0;l<r.length;l+=3)a.push([r[l],r[l+1],r[l+2]]);const c=(l,h)=>{const u=l/Pi.DOME_RINGS*(Math.PI/2),d=h/Pi.DOME_SECTORS*2*Math.PI,f=Math.cos(u);return[t*f*Math.cos(d),Pi.SLAB_M+s*Math.sin(u),e*f*Math.sin(d)]};for(let l=0;l<Pi.DOME_RINGS;l++)for(let h=0;h<Pi.DOME_SECTORS;h++){const u=h+1;a.push(c(l,h),c(l+1,u),c(l,u),c(l,h),c(l+1,h),c(l+1,u))}return Pi.of(a)}static of(t){const e=new be;return e.setAttribute("position",new pe(t.flat(),3)),e}}class yr{static SLAB_M=.6;static SLABS=4;static SIZE=512;static JOINT_M=.012;static made;static texture(){if(yr.made)return yr.made;const t=yr.SIZE,e=new Uint8Array(t*t*4);let i=23063;const n=()=>{i=i+1831565813|0;let f=Math.imul(i^i>>>15,1|i);return f=f+Math.imul(f^f>>>7,61|f)^f,((f^f>>>14)>>>0)/4294967296},s=yr.SLABS,r=t/s,a=Math.max(1,Math.round(yr.JOINT_M/yr.SLAB_M*r)),c=Array.from({length:s*s},()=>.9+.1*n()),l=s*8,h=Array.from({length:l*l},()=>n()),u=(f,p)=>h[(p%l+l)%l*l+(f%l+l)%l];for(let f=0;f<t;f++)for(let p=0;p<t;p++){const m=Math.floor(p/r),g=Math.floor(f/r),v=p-m*r,M=f-g*r,w=v<a||M<a,y=p/r*8,x=f/r*8,b=Math.floor(y),E=Math.floor(x),S=y-b,A=x-E,_=S*S*(3-2*S),I=A*A*(3-2*A),D=(u(b,E)*(1-_)+u(b+1,E)*_)*(1-I)+(u(b,E+1)*(1-_)+u(b+1,E+1)*_)*I,O=n(),P=w?.55:c[g*s+m]*(.9+.12*D)*(.88+.12*O),N=Math.min(255,Math.round(255*P)),k=(f*t+p)*4;e[k]=N,e[k+1]=N,e[k+2]=N,e[k+3]=255}const d=new Ds(e,t,t,tn,fs);return d.wrapS=d.wrapT=bc,d.minFilter=cr,d.generateMipmaps=!0,d.colorSpace=Bn,d.anisotropy=8,d.needsUpdate=!0,yr.made=d,d}static layOn(t){const e=t.getAttribute("position"),i=yr.SLAB_M*yr.SLABS,n=new Float32Array(e.count*2);for(let s=0;s<e.count;s++)n[s*2]=e.getX(s)/i,n[s*2+1]=e.getZ(s)/i;t.setAttribute("uv",new pe(n,2))}}class Ot{static UPPER=0;static GROUND_WINDOW=1;static GROUND_DOOR=2;static PLAIN=3;static TALL=4;static LANCET=5;static TILES=6;static TALL_SILL=.5;static TALL_HEAD=2.62;static BAY_M=3;static FLOOR_M=3;static PIXELS=96;static shared;static sharedEmissive;static texture(){if(!Ot.shared){const t=new Ds(Ot.pixels(),Ot.PIXELS*Ot.TILES,Ot.PIXELS,tn,fs);t.colorSpace=Bn,t.wrapS=Qi,t.wrapT=Qi,t.magFilter=Me,t.minFilter=cr,t.generateMipmaps=!0,t.needsUpdate=!0,Ot.shared=t}return Ot.shared}static emissive(){if(!Ot.sharedEmissive){const t=new Ds(Ot.glow(),Ot.PIXELS*Ot.TILES,Ot.PIXELS,tn,fs);t.colorSpace=Bn,t.wrapS=Qi,t.wrapT=Qi,t.magFilter=Me,t.minFilter=cr,t.generateMipmaps=!0,t.needsUpdate=!0,Ot.sharedEmissive=t}return Ot.sharedEmissive}static glow(){const t=Ot.PIXELS,e=t*Ot.TILES,i=new Uint8Array(e*t*4);for(let r=3;r<i.length;r+=4)i[r]=255;const n=t/Ot.BAY_M,s=[[Ot.UPPER,.9,2.3],[Ot.GROUND_WINDOW,.9,2.3],[Ot.TALL,Ot.TALL_SILL,Ot.TALL_HEAD]];for(const[r,a,c]of s)for(let l=Math.round(a*n);l<Math.round(c*n);l++)for(let h=Math.round(.9*n);h<Math.round(2.1*n);h++){if(Math.abs(h-1.5*n)<.03*n)continue;const u=(l*e+r*t+h)*4,[d,f,p]=Ot.roomLight((h/n-.9)/1.2,(l/n-a)/(c-a));i[u]=d,i[u+1]=f,i[u+2]=p}return i}static roomLight(t,e){const i=.35+.65*Math.pow(Math.max(0,Math.min(1,e)),.8),n=1-.45*Math.pow(Math.abs(2*t-1),3),s=Math.min(t,1-t)<.16,r=i*n*(s?.35:1),a=s?[255,225,195]:[255,255,255],c=Math.pow(r,1/2.2);return[Math.round(a[0]*c),Math.round(a[1]*c),Math.round(a[2]*c)]}static pixels(){const t=Ot.PIXELS,e=t*Ot.TILES,i=new Uint8Array(e*t*4).fill(255),n=t/Ot.BAY_M,s=(p,m,g,v,M,w)=>{for(let y=Math.round(g*n);y<Math.round(M*n);y++)for(let x=Math.round(m*n);x<Math.round(v*n);x++){const b=(y*e+p*t+x)*4;i[b]=w[0],i[b+1]=w[1],i[b+2]=w[2],i[b+3]=255}},r=[225,225,222],a=[34,42,54],c=[200,198,192];for(const p of[Ot.UPPER,Ot.GROUND_WINDOW])s(p,.9-.06,.9-.06,2.1+.06,2.3+.06,r),s(p,.9,.9,2.1,2.3,a),s(p,1.5-.02,.9,1.5+.02,2.3,r),s(p,.8,.84,2.2,.9-.06,c);s(Ot.GROUND_DOOR,1-.06,0,2+.06,2.1+.06,r),s(Ot.GROUND_DOOR,1,0,2,2.1,[58,62,56]);const l=[44,44,46],h=Ot.TALL;s(h,0,0,3,.09,[214,210,202]),s(h,.9-.08,Ot.TALL_SILL-.04,2.1+.08,Ot.TALL_HEAD+.1,r),s(h,.9,Ot.TALL_SILL,2.1,Ot.TALL_HEAD,a),s(h,1.5-.02,Ot.TALL_SILL,1.5+.02,Ot.TALL_HEAD,r),s(h,.82,Ot.TALL_SILL,2.18,Ot.TALL_SILL+.05,l),s(h,.82,Ot.TALL_SILL+.38,2.18,Ot.TALL_SILL+.43,l);for(let p=.86;p<2.15;p+=.13)s(h,p,Ot.TALL_SILL,p+.03,Ot.TALL_SILL+.4,l);const u=Ot.LANCET,d=2,f=2.34;s(u,1.2,.66,1.8,d,[40,44,54]);for(let p=d;p<f;p+=1/n){const m=.3*Math.sqrt(1-((p-d)/(f-d))**2);s(u,1.5-m,p,1.5+m,p+1/n,[40,44,54])}return i}}class Ad{static hash(t,e){const i=Math.sin(t*12.9898+e*78.233)*43758.5453;return i-Math.floor(i)}static LANCET_BAY_M=6;static LANCET_TIER_M=10;static build(t,e,i,n=!0,s=0,r,a=Ot.FLOOR_M){const c=[],l=[],h=[],u=t/2,d=e/2,f=r==="lancet",p=Math.max(1,Math.round(i/(f?Ad.LANCET_TIER_M:Math.max(a,1)))),m=i/p,g=f?Ad.LANCET_BAY_M:Ot.BAY_M,v=(y,x,b,E)=>{const S=Math.max(1,Math.round(b/g)),A=b/S;for(let _=0;_<p;_++)for(let I=0;I<S;I++){const D=E&&_===0&&I===Math.floor((S-1)/2),O=n?f?(p-1-_)%2===0?Ot.LANCET:Ot.PLAIN:D?Ot.GROUND_DOOR:r==="tall"?Ot.TALL:_>0?Ot.UPPER:Ot.GROUND_WINDOW:Ot.PLAIN,P=O===Ot.UPPER||O===Ot.GROUND_WINDOW||O===Ot.TALL?Ad.hash(s,c.length):2;for(let Ut=0;Ut<6;Ut++)h.push(P);const N=y[0]+x[0]*A*I,k=y[1]+x[1]*A*I,B=N+x[0]*A,W=k+x[1]*A,Q=_*m,Z=Q+m,nt=O/Ot.TILES+.002,ot=(O+1)/Ot.TILES-.002;c.push(N,Q,k,B,Q,W,B,Z,W,N,Q,k,B,Z,W,N,Z,k),l.push(nt,.002,ot,.002,ot,.998,nt,.002,ot,.998,nt,.998)}};v([u,-d],[-1,0],t,!0),v([-u,d],[1,0],t,!1),v([-u,-d],[0,1],e,!1),v([u,d],[0,-1],e,!1);const M=Ot.PLAIN/Ot.TILES+.01;c.push(-u,i,-d,-u,i,d,u,i,d,-u,i,-d,u,i,d,u,i,-d);for(let y=0;y<6;y++)l.push(M,.5),h.push(2);const w=new be;return w.setAttribute("position",new pe(c,3)),w.setAttribute("uv",new pe(l,2)),w.setAttribute("litRank",new pe(h,1)),w.computeVertexNormals(),w}}class al{constructor(t,e={}){this.size=t,this.structure=e}static DEFAULT_DIAMETER_M=.008;static POLE_RADIUS_M=.13;static POLE_ABOVE_M=.5;static NATURAL_SIZE=Object.freeze({widthM:1,lengthM:30,heightM:5});get strands(){const t=this.structure.strands;return!t||t.length===0?[{heightM:this.size.heightM,acrossM:0}]:t.map(e=>({heightM:e.heightM,acrossM:e.acrossM??0}))}get poleStations(){const t=this.size.lengthM/2;switch(this.structure.poles??"both"){case"start":return[t];case"end":return[-t];case"none":return[];default:return[-t,t]}}get poleHeightM(){return this.structure.poleHeightM??Math.max(...this.strands.map(t=>t.heightM))+al.POLE_ABOVE_M}build(){const t=this.structure.diameterM??al.DEFAULT_DIAMETER_M,e=this.strands.map(n=>{const s=new gs(t/2,t/2,this.size.lengthM,6);return s.rotateX(Math.PI/2),s.translate(n.acrossM,n.heightM,0),s}),i=this.poleStations.map(n=>{const s=new gs(al.POLE_RADIUS_M*.8,al.POLE_RADIUS_M,this.poleHeightM,8);return s.translate(0,this.poleHeightM/2,n),s});return{strands:e,poles:i}}}class mn{static TILE_M=2.4;static COLUMNS=6;static COURSES=10;static SIZE_PX=256;static FOUNDATION_M=.8;static pattern;static build(t){const e=new Ke,i=t.sizeM?.widthM??.6,n=t.sizeM?.heightM??1,s=t.sizeM?.lengthM??10,r=n+mn.FOUNDATION_M,a=new en(i,r,s);mn.layStones(a,i,r,s);const c=new Rr({map:mn.texture()}),l=new yt(a,c);return l.position.y=(n-mn.FOUNDATION_M)/2,l.castShadow=!0,l.receiveShadow=!0,l.userData={emissive:!1},e.add(l),e}static layStones(t,e,i,n){const s=t.getAttribute("uv");[[n,i],[n,i],[e,n],[e,n],[e,i],[e,i]].forEach(([a,c],l)=>{for(let h=l*4;h<l*4+4;h++)s.setXY(h,s.getX(h)*a/mn.TILE_M,s.getY(h)*c/mn.TILE_M)}),s.needsUpdate=!0}static texture(){if(mn.pattern)return mn.pattern;const t=mn.SIZE_PX,e=new Uint8Array(t*t*4),i=mn.seeds();for(let s=0;s<t;s++)for(let r=0;r<t;r++){const a=r/t,c=s/t;let l=1/0,h=1/0,u=i[0];for(const M of i)for(let w=-1;w<=1;w++)for(let y=-1;y<=1;y++){const x=(a-(M.x+w))*mn.COLUMNS,b=(c-(M.y+y))*mn.COURSES*.5,E=.8*Math.max(Math.abs(x),Math.abs(b))+.2*Math.hypot(x,b);E<l?(h=l,l=E,u=M):E<h&&(h=E)}const d=h-l,f=Math.min(d/.1,1),p=.8+.2*Math.min(d/.5,1),m=.94+.12*mn.noise(r,s),g=(.15+(u.tone-.15)*f)*(f>.999?p*m:1),v=(s*t+r)*4;e[v]=Math.round(255*g*u.warm),e[v+1]=Math.round(255*g),e[v+2]=Math.round(255*g*u.cool),e[v+3]=255}const n=new Ds(e,t,t,tn);return n.wrapS=n.wrapT=bc,n.colorSpace=Bn,n.magFilter=Me,n.minFilter=cr,n.generateMipmaps=!0,n.anisotropy=4,n.needsUpdate=!0,mn.pattern=n,n}static seeds(){let t=20260831;const e=()=>(t=t*1664525+1013904223>>>0,t/4294967296),i=[];for(let n=0;n<mn.COURSES;n++)for(let s=0;s<mn.COLUMNS;s++){const r=.34+e()*.24;i.push({x:(s+n%2*.5+.5+(e()-.5)*.35)/mn.COLUMNS,y:(n+.5+(e()-.5)*.3)/mn.COURSES,tone:r,warm:1+e()*.1,cool:.9+e()*.1})}return i}static noise(t,e){const i=Math.sin(t*12.9898+e*78.233)*43758.5453;return i-Math.floor(i)}}class Te{static HEAD_WIDTH_M=.34;static HEAD_DEPTH_M=.24;static HEAD_MARGIN_M=.18;static POLE_RADIUS_M=.055;static HOUSING=[.05,.05,.05];static POLE=[.16,.17,.17];static BAND_M=.5;static BAND_GAP_M=.5;static KERB_CLEAR_M=.25;static CROSSING_LIFT_M=.08;static PAINT=[.8,.8,.78];static SIGN_POLE_RADIUS_M=.03;static SIGN_CENTRE_Y_M=2.55;static SIGN_METAL=[.48,.49,.5];static SIGN_RED=[.62,.05,.05];static SIGN_WHITE=[.82,.82,.8];static trafficLight(t){const e=t?2:3,i=t?me.PEDESTRIAN_HEAD_Y_M:me.VEHICLE_HEAD_Y_M,n=me.LENS_SPACING_M,s=(e-1)*n+2*Te.HEAD_MARGIN_M,r=i-s/2+.05,a=[Te.part(new gs(Te.POLE_RADIUS_M,Te.POLE_RADIUS_M,r,8),Te.POLE,0,r/2,0),Te.part(new en(Te.HEAD_WIDTH_M,s,Te.HEAD_DEPTH_M),Te.HOUSING,0,i,0)];for(let c=0;c<e;c++){const l=i+((e-1)/2-c)*n;a.push(Te.part(new en(.26,.02,.16),Te.HOUSING,0,l+.12,-.2))}return Te.group(a)}static crossing(t,e){const i=Te.BAND_M,n=i+Te.BAND_GAP_M,s=Math.max(i,t-2*Te.KERB_CLEAR_M),r=Math.max(1,Math.floor((s+Te.BAND_GAP_M)/n)),a=-((r-1)*n)/2,c=[],l=[],h=Te.CROSSING_LIFT_M,u=e/2;for(let g=0;g<r;g++){const v=a+g*n-i/2,M=v+i;c.push(v,h,u,M,h,u,M,h,-u,v,h,u,M,h,-u,v,h,-u);for(let w=0;w<6;w++)l.push(0,1,0)}const d=new be;d.setAttribute("position",new pe(c,3)),d.setAttribute("normal",new pe(l,3));const f=new Rr({color:16777215});f.color.setRGB(...Te.PAINT),f.polygonOffset=!0,f.polygonOffsetFactor=-4,f.polygonOffsetUnits=-4;const p=new yt(d,f);p.userData={emissive:!1},p.receiveShadow=!0,p.castShadow=!1;const m=new Ke;return m.add(p),m}static drape(t,e){t.traverse(i=>{const n=i;if(!n.isMesh)return;const s=n.geometry.getAttribute("position"),r=n.userData.crossingRest??=Float32Array.from(s.array);for(let a=0;a<s.count;a++)s.setY(a,r[a*3+1]+e(r[a*3],r[a*3+2]));s.needsUpdate=!0,n.geometry.computeBoundingSphere(),n.geometry.computeBoundingBox()})}static roadSign(t){const e=Te.SIGN_CENTRE_Y_M,i=t?.face??"other",[n,s,r]=i==="stop"?[.38,8,Math.PI/8]:i==="give-way"?[.52,3,0]:i==="speed-limit"?[.325,24,0]:[0,0,0],a=e+(i==="other"?.3:n),c=Te.SIGN_POLE_RADIUS_M,l=[Te.part(new gs(c,c,a,6),Te.SIGN_METAL,0,a/2,0)],h=(u,d,f,p)=>{const m=new gs(u,u,d,s,1,!1,r);m.rotateX(Math.PI/2),l.push(Te.part(m,p,0,e,-f))};if(i==="other")l.push(Te.part(new en(.6,.6,.012),Te.SIGN_METAL,0,e,-.038)),l.push(Te.part(new en(.58,.58,.004),Te.SIGN_WHITE,0,e,-.047));else{h(n,.012,c+.008,Te.SIGN_METAL);const[u,d,f]=i==="stop"?[Te.SIGN_WHITE,Te.SIGN_RED,.92]:[Te.SIGN_RED,Te.SIGN_WHITE,i==="give-way"?.68:.77];h(n*.99,.004,c+.017,u),h(n*f,.003,c+.0205,d)}return Te.group(l)}static pedestrianFigure(t,e){const i=t==="standing"?[[-.17,.25],[.17,.25],[.17,-.08],[.1,-.08],[.1,-.5],[.02,-.5],[.02,-.12],[-.02,-.12],[-.02,-.5],[-.1,-.5],[-.1,-.08],[-.17,-.08]]:[[-.05,.26],[-.09,.22],[-.24,.05],[-.19,.01],[-.07,.13],[-.07,0],[-.18,-.22],[-.29,-.47],[-.22,-.5],[-.1,-.25],[-.01,-.07],[.09,-.27],[.13,-.5],[.21,-.48],[.16,-.24],[.07,0],[.07,.11],[.2,0],[.24,.05],[.08,.22],[.05,.26]],n=new eM(i.map(([a,c])=>new tt(a,c))),s=new eM;s.absarc(t==="standing"?0:-.02,.38,.1,0,2*Math.PI,!1);const r=new Ey([n,s],6);return r.scale(e,e,e),r.rotateY(Math.PI),r}static part(t,e,i,n,s){return{geometry:t,color:e,matrix:new Gt().makeTranslation(i,n,s)}}static group(t){const e=[],i=[],n=[];for(const{geometry:c,color:l,matrix:h}of t){const u=c.index?c.toNonIndexed():c;u.applyMatrix4(h);const d=u.getAttribute("position"),f=u.getAttribute("normal");for(let p=0;p<d.count;p++)e.push(d.getX(p),d.getY(p),d.getZ(p)),i.push(f.getX(p),f.getY(p),f.getZ(p)),n.push(...l);u!==c&&u.dispose(),c.dispose()}const s=new be;s.setAttribute("position",new pe(e,3)),s.setAttribute("normal",new pe(i,3)),s.setAttribute("color",new pe(n,3));const r=new yt(s,new Rr({color:16777215,vertexColors:!0}));r.userData={emissive:!1},r.castShadow=!0,r.receiveShadow=!0;const a=new Ke;return a.add(r),a}}class su{static MIN_K=1667;static MAX_K=25e3;static ofTemperature(t){const e=Math.min(su.MAX_K,Math.max(su.MIN_K,t)),i=e<=4e3?-266123900/e**3-234358.9/e**2+877.6956/e+.17991:-3025846900/e**3+21070379e-1/e**2+222.6347/e+.24039,n=e<=2222?-1.1063814*i**3-1.3481102*i**2+2.18555832*i-.20219683:e<=4e3?-.9549476*i**3-1.37418593*i**2+2.09137015*i-.16748867:3.081758*i**3-5.8733867*i**2+3.75112997*i-.37001483,s=i/n,r=(1-i-n)/n,a=[3.2406*s-1.5372-.4986*r,-.9689*s+1.8758+.0415*r,.0557*s-.204+1.057*r].map(l=>Math.max(0,l)),c=.2126*a[0]+.7152*a[1]+.0722*a[2];return[a[0]/c,a[1]/c,a[2]/c]}}const i1=Math.PI/180;function ti(o,t,e,i,n=!1,s){const r=n&&s?new Rr({color:new rt(...s),emissive:new rt(...e)}):n?new Is({color:new rt(...e)}):new Rr({color:new rt(...e)}),a=new yt(t,r);return a.position.y=i,a.userData={emissive:n},a.castShadow=!n,a.receiveShadow=!n,o.add(a),a}const n1=.25,$N=.002,YN=100,Tb=3e4,KN=1500,qN=.25,ZN=1e3,JN=.15;function jN(o){const t=/^#([0-9a-f]{6})$/i.exec(o);if(!t)return[1,1,1];const e=parseInt(t[1],16),i=n=>{const s=n/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4};return[i(e>>16&255),i(e>>8&255),i(e&255)]}const QN=[.62,.62,.6],tL=[1,.85,.5],eL=[.25,.25,.25],g3=[1,.97,.85],iL=[.55,.68,.72],nL=.12,ma=.03,ga=.05,v3={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function _s(o,t){return o?.[t]}function va(o,t,e,i,n,s,r,a){if(a===void 0)return;const c=new Is({color:new rt(...iL).multiplyScalar(nL),transparent:!0,opacity:a/100,depthWrite:!1}),l=new yt(new en(t,e,i),c);l.position.set(n,s,r),l.renderOrder=2,o.add(l)}const Mr=.05,s1=[.6,.58,.53],Rb=[.5,.5,.48];function Lh(o,t,e,i,n,s,r,a){const c=new Rr({color:new rt(...a),side:zi}),l=new yt(new en(t,e,i),c);l.position.set(n,s,r),o.add(l)}function sL(o,t,e,i,n,s,r,a,c){const l=(i-s)/2,h=(p,m,g,v)=>{p<=0||(t?Lh(o,p,m,Mr,g,a+v,r,c):Lh(o,Mr,m,p,r,a+v,g,c))};h(e,l,0,i/2-l/2),h(e,l,0,-(i/2-l/2));const u=[...n].sort((p,m)=>p.center-m.center);let d=-e/2;for(const p of u){const g=p.center-p.main/2-d;h(g,s,d+g/2,0),d=p.center+p.main/2}const f=e/2-d;h(f,s,d+f/2,0)}function M3(o,t,e,i,n,s,r,a,c,l){const h=(i+n)/2,u=n-i,d=(f,p,m,g)=>{f.length===0?p?Lh(o,m,u,Mr,0,h,g,s1):Lh(o,Mr,u,m,g,h,0,s1):sL(o,p,m,u,f,s,g,h,s1)};d(r,!0,t*2,-e+Mr),d(a,!0,t*2,e-Mr),d(c,!1,e*2,-t+Mr),d(l,!1,e*2,t-Mr),Lh(o,t*2,Mr,e*2,0,i+Mr,0,Rb),Lh(o,t*2,Mr,e*2,0,n-Mr,0,Rb)}function wM(o,t,e,i){switch(o){case"front":return{x:0,z:-(e-i)};case"behind":return{x:0,z:e-i};case"left":return{x:-(t-i),z:0};case"right":return{x:t-i,z:0};case"front-left":return{x:-(t-i),z:-ya};case"front-right":return{x:t-i,z:-ya};case"behind-left":return{x:-(t-i),z:ya};case"behind-right":return{x:t-i,z:ya}}}function y3(o,t,e,i,n,s,r,a){const c=SM();c.scale.setScalar(n),c.rotation.y=v3[e];const{x:l,z:h}=wM(t,s,r,a);c.position.set(l,i,h),o.add(c)}const xM=6,bM=6,Ma=3,Yu=1.4,Ku=Ma*.5,w3=1.2,x3=.35,rL=.75,aL=1.6;function Ib(o,t,e,i,n){const s=new Ke,r=Math.max(1,o+1),a=r*Ma;ti(s,new en(xM,a,bM),[.55,.54,.5],a/2);const c=xM/2,l=bM/2;for(let h=0;h<r;h++){const u=h*Ma+Ma/2;va(s,Yu,Ku,ga,0,u,-l-ma,_s(t,"front")),va(s,Yu,Ku,ga,0,u,l+ma,_s(t,"behind")),va(s,ga,Ku,Yu,-c-ma,u,0,_s(t,"left")),va(s,ga,Ku,Yu,c+ma,u,0,_s(t,"right"))}if(e){const h=Math.min(Math.max(i??0,0),r-1);y3(s,e,n??e,h*Ma,.72,c,l,w3);const u=d=>_s(t,d)!==void 0?[{main:Yu,center:0}]:[];M3(s,c,l,h*Ma,(h+1)*Ma,Ku,u("front"),u("behind"),u("left"),u("right"))}return s}function Db(){const o=new Ke,t=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[e,i,n,s]of t){const r=new hn(n,10,7);r.scale(1,.85,1),r.translate(e,0,i),ti(o,r,[.26,.28,.17],s)}return o}function oL(o){const t=new Ke,e=new Ci(dt.sizeOf(o),o.bridge).build();ti(t,e.concrete,[.6,.6,.58],0);const i=ti(t,e.road,[.2,.2,.21],0),n=ti(t,e.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=Tn;return ti(t,e.railing,[.5,.52,.55],0),t}function cL(o){const t=new Ke,e=new al(dt.sizeOf(o),o.wire).build();for(const i of e.strands)ti(t,i,[.1,.1,.11],0);for(const i of e.poles)ti(t,i,[.3,.24,.18],0);return t}function Cb(){const o=new Ke;return ti(o,new gs(.15,.22,2,8),[.32,.22,.14],1),ti(o,new bu(1.4,3,8),[.16,.32,.14],3.5),o}const Ob=.275,lL=.35,hL=.9,uL=34,dL=8,fL=1.4;function Pb(){const o=new Ke,t=new hn(Ob,7,3,0,Math.PI*2,0,Math.PI/2);t.scale(1,lL/Ob,1);const e=dt.repeatOnGrid(t,uL,hL,dL,fL),i=ti(o,e,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=e.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=t.getAttribute("position").count,t.dispose(),o}function Nb(){const o=new Ke,t=new hn(1,7,3,0,Math.PI*2,0,Math.PI/2);return ti(o,t,[.38,.36,.32],0),o}const pL=[.24,.22,.18],mL=[.14,.17,.08];function gL(){const o=new Ke,t=ti(o,new en(1,1,1),pL,.5),e=ti(o,new en(1,.03,1),mL,1.015);for(const i of[t,e])i.material.side=Tn;return e.castShadow=!1,nu.install(e.material,!0),o}function Lb(o,t,e){const i=new Ke;t!=="wall"&&ti(i,new gs(.05,.08,5,8),[.28,.28,.3],2.5);const n=ti(i,new hn(.25,12,8),o?dt.lampHue(e):[0,0,0],5.1,!0,QN);return p3.applyOpaque(n.material),i}const vL=[.08,.08,.08],Go=.8,mh=1,na=1.7,r1=.6,Nc=.46,Ap=1.5,ih=.8,ya=.5,ML=na;function kb(o,t,e,i){const n=new Ke;ti(n,new en(1.8,1.4,4.2),[.45,.14,.14],.7),ti(n,new en(Go*2,r1,mh*2),[.4,.12,.12],na);for(const r of[-1.4,1.4])for(const a of[-.95,.95]){const c=ti(n,new gs(.4,.4,.3,12),vL,.4);c.rotation.z=Math.PI/2,c.position.x=a,c.position.z=r}const s=o?g3:[0,0,0];for(const r of[-.7,.7])ti(n,new hn(.15,8,6),s,.7,!0,eL).position.set(r,.7,-2.1);if(va(n,Ap,Nc,ga,0,na,-mh-ma,_s(t,"front")),va(n,Ap,Nc,ga,0,na,mh+ma,_s(t,"behind")),va(n,ga,Nc,ih,-Go-ma,na,-ya,_s(t,"front-left")),va(n,ga,Nc,ih,-Go-ma,na,ya,_s(t,"behind-left")),va(n,ga,Nc,ih,Go+ma,na,-ya,_s(t,"front-right")),va(n,ga,Nc,ih,Go+ma,na,ya,_s(t,"behind-right")),e){y3(n,e,i??e,rL,.5,Go,mh,x3);const r=(l,h)=>{const u=[];return _s(t,l)!==void 0&&u.push({main:ih,center:-ya}),_s(t,h)!==void 0&&u.push({main:ih,center:ya}),u},a=_s(t,"front")!==void 0?[{main:Ap,center:0}]:[],c=_s(t,"behind")!==void 0?[{main:Ap,center:0}]:[];M3(n,Go,mh,na-r1/2,na+r1/2,Nc,a,c,r("front-left","behind-left"),r("front-right","behind-right"))}return n}const Fb=new Map;function Ub(o,t){if(!o)return;const e=[[o.lengthM,t.lengthM],[o.heightM,t.heightM],[o.widthM,t.widthM]];for(const[i,n]of e)if(i!==void 0&&n>1e-6)return i/n}function a1(o,t){return t>1e-6?o/t:1}const b3=[.95,.9,.82],zb=[.72,.74,.78];function Bb(){const o=new Ke;ti(o,new gs(.25,.3,1.5,10),zb,.75),ti(o,new hn(.26,10,8),zb,1.74);const t=ti(o,new bu(.07,.16,8),b3,1.74);return t.rotation.x=-Math.PI/2,t.position.z=-.22,o}function SM(){const o=new Ke;ti(o,new gs(.25,.3,1.5,10),[.3,.3,.35],.75),ti(o,new hn(.22,10,8),[.62,.52,.46],1.72);const t=ti(o,new bu(.07,.16,8),b3,1.72);return t.rotation.x=-Math.PI/2,t.position.z=-.2,o}const yL=17,Hb=18.5,o1=[.16,.16,.18];function Gb(){const o=new Ke,t=ti(o,new gs(1.8,1.8,Hb*2,10),o1,0);t.rotation.x=Math.PI/2,ti(o,new en(yL*2,.5,4.5),o1,0);const e=ti(o,new en(.4,5.5,4),o1,3);return e.position.z=-Hb+2,o}class dt{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound","terrace","wall","building","bridge"]);static groundUnderFootprint(t,e,i,n,s,r=0){const a=dt.sizeOf(t);if(r>a.heightM)return s(e,i);const c=(n??0)*Math.PI/180,l=t.kind==="bridge"?Math.min(a.lengthM,t.bridge?.spanM??a.lengthM):a.lengthM,h=Math.min(21,Math.max(2,Math.ceil(l/.75)+1)),u=Math.min(21,Math.max(2,Math.ceil(a.widthM/.75)+1)),d=dt.GROWS_FROM_GROUND.has(t.kind);let f=d?1/0:-1/0;for(let p=0;p<h;p++){const m=(p/(h-1)-.5)*l;for(let g=0;g<u;g++){const v=(g/(u-1)-.5)*a.widthM,M=e+Math.sin(c)*m+Math.cos(c)*v,w=i-Math.cos(c)*m+Math.sin(c)*v;f=d?Math.min(f,s(M,w)):Math.max(f,s(M,w))}}return Number.isFinite(f)?f:s(e,i)}static wireGround(t,e,i,n,s){const r=dt.sizeOf(t).lengthM/2,a=(n??0)*Math.PI/180,c=s(e+Math.sin(a)*r,i-Math.cos(a)*r),l=s(e-Math.sin(a)*r,i+Math.cos(a)*r);return{startY:l,dropM:c-l}}static shearWire(t,e,i){e<=0||t.traverse(n=>{const s=n;if(!s.isMesh)return;const r=s.geometry.getAttribute("position"),a=s.userData.wireRest??=Float32Array.from(r.array);for(let c=0;c<r.count;c++){const l=.5-a[c*3+2]/e;r.setY(c,a[c*3+1]+i*l)}r.needsUpdate=!0,s.geometry.computeBoundingSphere(),s.geometry.computeBoundingBox()})}static occupantView(t,e=t.headingDeg){const i=t.observerSide;if(!i)throw new Error("occupantView requires object.observerSide to be set");const{x:n,z:s}=t.kind==="vehicle"?wM(i,Go,mh,x3):wM(i,xM/2,bM/2,w3),r=t.kind==="vehicle"?ML:(t.occupiedFloor??0)*Ma+aL,a=(e??0)-v3[t.observerFacing??i]/i1,c=this.scaleFor(t);return{x:n*c.x,z:s*c.z,eyeY:r*c.y,headingDeg:a}}static BODY_NAME="decor-body";static bodyOf(t){return t.getObjectByName(dt.BODY_NAME)??t}static repeatOnGrid(t,e,i,n,s){const r=t.getAttribute("position"),a=t.getAttribute("normal"),c=t.getIndex();if(!c)throw new Error("repeatOnGrid needs an indexed geometry");const l=r.count,h=e*n,u=new Float32Array(l*h*3),d=new Float32Array(l*h*3),f=new Uint32Array(c.count*h),p=-((e-1)*i)/2,m=-((n-1)*s)/2;let g=0;for(let M=0;M<n;M++)for(let w=0;w<e;w++,g++){const y=m+M*s,x=p+w*i;for(let b=0;b<l;b++){const E=(g*l+b)*3;u[E]=r.getX(b)+y,u[E+1]=r.getY(b),u[E+2]=r.getZ(b)+x,d[E]=a.getX(b),d[E+1]=a.getY(b),d[E+2]=a.getZ(b)}for(let b=0;b<c.count;b++)f[g*c.count+b]=c.getX(b)+g*l}const v=new be;return v.setAttribute("position",new pe(u,3)),v.setAttribute("normal",new pe(d,3)),v.setIndex(new wy(f,1)),v}static fitTerrace(t,e,i){const n=dt.sizeOf(e),s=n.widthM/2,r=n.lengthM/2,a=i(0,0)+n.heightM,c=Math.min(16,Math.max(1,Math.ceil(n.lengthM/3))),l=dt.bodyOf(t).children.filter(y=>y.isMesh);if(l.length<2)return a;const h=Math.min(10,n.widthM/4),u=[-s];for(const y of[.25,.5,.75,1])u.push(-s+h*y);const d=Math.max(1,Math.ceil((n.widthM-2*h)/3));for(let y=1;y<d;y++)u.push(-s+h+(n.widthM-2*h)*y/d);for(const y of[1,.75,.5,.25,0])u.push(s-h*y);const f=y=>-r+n.lengthM*y/c,p=.8,m=(y,x)=>{const b=Math.min(1,Math.max(0,(s-Math.abs(y))/h)),E=b*b*(3-2*b);return E*a+(1-E)*Math.min(a,i(y,x))},g=[],v=(y,x)=>{const b=i(y[0],y[1])-p,E=i(x[0],x[1])-p,S=Math.max(m(y[0],y[1]),b),A=Math.max(m(x[0],x[1]),E);g.push(y[0],b,y[1],x[0],E,x[1],y[0],S,y[1]),g.push(x[0],E,x[1],x[0],A,x[1],y[0],S,y[1])};for(let y=0;y<u.length-1;y++)v([u[y],-r],[u[y+1],-r]),v([u[y],r],[u[y+1],r]);const M=[];for(let y=0;y<u.length-1;y++)for(let x=0;x<c;x++){const b=[u[y],f(x)],E=[u[y+1],f(x)],S=[u[y],f(x+1)],A=[u[y+1],f(x+1)];for(const[_,I,D]of[[b,S,E],[E,S,A]])for(const O of[_,I,D])M.push(O[0],m(O[0],O[1]),O[1])}const w=(y,x)=>{const b=new be;b.setAttribute("position",new pe(x,3)),b.computeVertexNormals(),y.geometry.dispose(),y.geometry=b,y.position.y=0};return w(l[0],g),w(l[1],M),a}static fitCropToGround(t,e){t.updateMatrixWorld(!0);const i=new T;t.traverse(n=>{const s=n,r=s.userData.cropBasePositions,a=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!a)return;const c=s.geometry.getAttribute("position"),l=new Gt().copy(s.matrixWorld).invert();for(let h=0;h<c.count;h+=a){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(s.matrixWorld),i.y=e(i.x,i.z),i.applyMatrix4(l);for(let u=h;u<h+a;u++)c.setY(u,r[u*3+1]+i.y)}c.needsUpdate=!0,s.geometry.computeBoundingBox(),s.geometry.computeBoundingSphere()})}static applyModelParameters(t,e,i){if(!(!e||!i))for(const[n,s]of Object.entries(i)){const r=e[n];if("materials"in s)typeof r=="string"&&dt.tint(t,s.materials,r);else if(typeof r=="boolean"){const a=s.nodes.map(l=>new RegExp(l)),c=r===(s.hideWhen??!0);t.traverse(l=>{a.some(h=>h.test(l.name))&&(l.visible=!c)})}}}static tint(t,e,i){const n=e.map(s=>new RegExp(s));t.traverse(s=>{const r=s;if(!r.isMesh)return;const a=r.userData.tintedMaterials??[],c=l=>{if(!l.color||!n.some(f=>f.test(l.name)))return l;const u=l.clone();u.color.set(i);const d=u.emissive?Math.max(u.emissive.r,u.emissive.g,u.emissive.b):0;return d>0&&(u.emissive.multiply(u.color),u.emissive.multiplyScalar(d/(Math.max(u.emissive.r,u.emissive.g,u.emissive.b)||1))),a.push(u),u};r.material=Array.isArray(r.material)?r.material.map(c):c(r.material),a.length>0&&(r.userData.tintedMaterials=a)})}static paint(t,e){t.traverse(i=>{const n=i,s=n.userData;if(!n.isMesh||s?.emissive)return;const r=n.material;r?.color&&r.color.set(e)})}static addRoof(t,e){const i=Pi.normalised(e.roof),n=dt.sizeOf(e),s=e.sizeM?.heightM===void 0?n.heightM:dt.wallHeightOf(e,n.heightM),r=dt.roofColor(i.color),a=Pi.build(i,n.widthM,n.lengthM);e.roof.material==="stone"&&yr.layOn(a);const c=ti(t,a,r,s),l=c.material;l.side=Tn,e.roof.material==="stone"&&(l.map=yr.texture(),l.bumpMap=l.map,l.bumpScale=dt.STONE_BUMP),c.name=dt.ROOF_NAME}static wallHeightOf(t,e){return Math.min(e,Math.max(Ma,e-(t.roof?Pi.normalised(t.roof).riseM:0)))}static roofColor(t){const e=/^#([0-9a-f]{6})$/i.exec(t??"")?.[1];if(!e)return[.45,.25,.2];const i=new rt(`#${e}`);return[i.r,i.g,i.b]}static ROOF_NAME="decor-roof";static STONE_BUMP=2;static PLASTER="#d3cab8";static hasFacade(t){return t.kind==="building"&&dt.facadeOf(t)!==void 0&&!t.observerSide&&t.sizeM?.widthM!==void 0&&t.sizeM.lengthM!==void 0&&t.sizeM.heightM!==void 0}static facadeOf(t){if(t.kind!=="building"||t.facade?.openings==="none")return;if(t.facade)return t.facade;const e=t.sizeM?.heightM;return e===void 0?void 0:e-(t.roof?Pi.normalised(t.roof).riseM:0)>=Ma?dt.HOUSE_FACADE:void 0}static isBare(t){return t.openings==="plain"||t.plain===!0}static HOUSE_FACADE={};static buildFacade(t){const e=new Ke,i=dt.sizeOf(t),n=dt.facadeOf(t),s=n.openings==="tall"||n.openings==="lancet"?n.openings:void 0,r=Ad.build(i.widthM,i.lengthM,dt.wallHeightOf(t,i.heightM),!dt.isBare(n),t.eastM*7.31+t.northM*3.17,s,n.storeyM);if(n.closedAtNight){const l=r.getAttribute("litRank");for(let h=0;h<l.count;h++)l.setX(h,l.getX(h)/dt.CLOSED_AT_NIGHT_SHARE)}const a=new Rr({color:new rt(n.color??dt.PLASTER),map:Ot.texture(),emissiveMap:Ot.emissive(),emissive:new rt(1,1,1)});a.onBeforeCompile=l=>{l.uniforms.uLitShare=dt.litWindowShare,l.uniforms.uWindowLuminance=dt.windowLuminance,l.vertexShader=`attribute float litRank;
|
|
8956
|
+
`,transparent:!0,blending:Cn,depthWrite:!1,side:zi,fog:!1}),this.object=new yt(new hn(Zi.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(t){this.hostedByDeck=t,this.show(this.shown)}show(t){this.shown=t,this.object.visible=t&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=t?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(t){this.urgent=t}set onReady(t){this.onRepaint=t}update(t,e,i,n,s,r,a=qe.DEFAULT_RARE_SHARE){const c=this.material.uniforms;if(i<=0){c.uStrength.value=0,this.show(!1),this.stopWork();return}c.uSource.value.set(t.x,t.y,t.z).normalize(),c.uStrength.value=i,c.uTint.value.set(n[0],n[1],n[2]),c.uIceCover.value=s.cover,c.uIceHeight.value=s.layerHeight,this.show(this.everDisplayed),this.requestMap(e,r,a)}featureAt(t){const e=this.material.uniforms;if(!this.everDisplayed||!(e.uStrength.value>0)||this.mappedAltitudeDeg!==this.mappedAltitudeDeg)return;const i=e.uUp.value.clone().normalize(),n=e.uSource.value.clone().normalize(),s=Math.PI/180,r=Math.asin(Math.max(-1,Math.min(1,t.dot(i))))/s,a=Math.asin(Math.max(-1,Math.min(1,n.dot(i))))/s,c=g=>g.clone().sub(i.clone().multiplyScalar(g.dot(i))),l=c(n),h=c(t),u=l.length()<1e-4||h.length()<1e-4?0:Math.acos(Math.max(-1,Math.min(1,l.dot(h)/(l.length()*h.length()))))/s,d=qe.AZIMUTH_BINS,f=qe.ALTITUDE_BINS,p=this.texels,m=(g,v)=>{if(g<-90||g>90)return 0;const M=Math.min(d-1,Math.max(0,Math.floor(Math.min(180,Math.abs(v))/180*d))),w=Math.min(f-1,Math.max(0,Math.floor((g+90)/180*f)));return Zi.halfToFloat(p[(w*d+M)*4+1])};return Ph.at(a,r,u,m)}static halfToFloat(t){const e=t>>10&31,i=t&1023,n=t>>15?-1:1;return e===0?n*i*5960464477539063e-23:n*2**(e-15)*(1+i/1024)}requestMap(t,e,i){if(!(!(Math.abs(t-this.mappedAltitudeDeg)<Zi.ALTITUDE_STEP_DEG)||!(Math.abs(e-this.mappedAlignment)<Zi.ALIGNMENT_STEP)||!(Math.abs(i-this.mappedRare)<Zi.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(t,e,i)){this.next=void 0;return}if(!(!(Math.abs(t-this.pendingAltitudeDeg)<Zi.LEAP_ALTITUDE_DEG)||!(Math.abs(e-this.pendingAlignment)<Zi.LEAP_ALIGNMENT)||!(Math.abs(i-this.pendingRare)<Zi.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:t,alignment:e,rare:i};return}}this.next=void 0,this.pendingAltitudeDeg=t,this.pendingAlignment=e,this.pendingRare=i,this.stopWork(),this.tracing=!0,this.startTracing(t,e,i)}startTracing(t,e,i){const n=++this.ticket,s=()=>{n!==this.ticket||!this.tracing||(this.sky.begin(t,e,void 0,qe.populationsFor(i)),this.scheduleWork())};sc.with(r=>{n!==this.ticket||!this.tracing||(this.job=r.trace(t,e,i,Zi.RAYS,a=>{this.job=void 0,this.texels.set(a),this.display(),this.finishTracing()},s))},s)}ticket=0;job;pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;pendingRare=Number.NaN;next;tracingFor(t,e,i){return this.tracing&&Math.abs(t-this.pendingAltitudeDeg)<Zi.ALTITUDE_STEP_DEG&&Math.abs(e-this.pendingAlignment)<Zi.ALIGNMENT_STEP&&Math.abs(i-this.pendingRare)<Zi.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const t=()=>{if(this.workHandle=void 0,!this.tracing)return;const e=performance.now(),i=this.urgent?Zi.URGENT_BUDGET_MS:Zi.BUDGET_MS;do this.sky.trace(Zi.RAYS_PER_BATCH);while(this.sky.tracedRays<Zi.RAYS&&performance.now()-e<i);if(this.sky.tracedRays>=Zi.RAYS){this.publish(),this.finishTracing();return}this.workHandle=requestAnimationFrame(t)};this.workHandle=requestAnimationFrame(t)}finishTracing(){this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment,this.mappedRare=this.pendingRare;const t=this.next;t&&this.requestMap(t.sourceAltitudeDeg,t.alignment,t.rare)}stopWork(){this.ticket++,this.job?.cancel(),this.job=void 0,this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){XN.fromRadiance(this.sky.harvest().data,this.texels),this.display()}display(){this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class kn{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=kn.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(kn.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];heads=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const t=kn.MAX_CONCURRENT*kn.SEGMENTS*kn.VERTICES_PER_SEGMENT;this.positions=new Float32Array(t*3),this.colors=new Float32Array(t*3);const e=new be;e.setAttribute("position",new we(this.positions,3)),e.setAttribute("color",new we(this.colors,3)),e.setDrawRange(0,0),this.object=new yt(e,La.material()),this.object.frustumCulled=!1,La.track(this.object)}get schedule(){return this.meteors}setShower(t,e,i){this.meteors=t,this.radiantAltitudeDeg=e,this.radiantAzimuthDeg=i}update(t){const e=this.object.geometry;if(this.heads=[],this.meteors.length===0){e.setDrawRange(0,0);return}const i=br.aliveAt(this.meteors,t).slice(0,kn.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const a=this.radiantOf(s);if(!a)continue;const c=Ei(a.altitudeDeg,a.azimuthDeg,1),[l,h]=this.basisAround(c),u=s.fromRadiantDeg+r*s.lengthDeg,d=Math.max(s.fromRadiantDeg,u-s.lengthDeg*.6),f=Math.min(1,(1-r)*2.5),p=this.turn(l,h,s.bearingDeg),m=(.15+.85*s.brightness)*f,g=y=>m*y**1.6,v=y=>this.onSphere(c,p,d+(u-d)*y),M=v(1);f>0&&this.heads.push({...m3(M.x,M.y,M.z),magnitude:br.magnitudeOf(s)-2.5*Math.log10(f)});const w=y=>kn.RADIUS*((kn.MIN_HALF_WIDTH_DEG+kn.BRIGHT_HALF_WIDTH_DEG*s.brightness*y)*Math.PI/180);for(let y=1;y<kn.POINTS;y++){const x=(y-1)/kn.SEGMENTS,b=y/kn.SEGMENTS;n=this.pushRibbon(n,v(x),v(b),w(x),w(b),g(x),g(b))}}e.setDrawRange(0,n),e.getAttribute("position").needsUpdate=!0,e.getAttribute("color").needsUpdate=!0}midpointOf(t){const e=this.radiantOf(t);if(!e)return;const i=Ei(e.altitudeDeg,e.azimuthDeg,1),[n,s]=this.basisAround(i),r=this.turn(n,s,t.bearingDeg),a=this.onSphere(i,r,t.fromRadiantDeg+t.lengthDeg/2),c=Math.hypot(a.x,a.y,a.z)||1;return{altitudeDeg:Math.asin(a.y/c)*180/Math.PI,azimuthDeg:(Math.atan2(a.x,-a.z)*180/Math.PI+360)%360}}radiantOf(t){return t.radiant?t.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(t,e,i,n,s,r,a){const c=this.normalise(this.cross(this.normalise(e),this.normalise(this.subtract(i,e))));for(let l=0;l<kn.ACROSS-1;l++){const h=l-1,u=l,d=this.across(e,c,n,h),f=this.across(i,c,s,h),p=this.across(e,c,n,u),m=this.across(i,c,s,u),g=(v,M)=>v===0?M:0;t=this.push(t,d,g(h,r)),t=this.push(t,f,g(h,a)),t=this.push(t,p,g(u,r)),t=this.push(t,f,g(h,a)),t=this.push(t,m,g(u,a)),t=this.push(t,p,g(u,r))}return t}across(t,e,i,n){return{x:t.x+e.x*i*n,y:t.y+e.y*i*n,z:t.z+e.z*i*n}}push(t,e,i){const n=t*3;this.positions[n]=e.x,this.positions[n+1]=e.y,this.positions[n+2]=e.z;const s=Bt.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.9,this.colors[n+1]=s*.95,this.colors[n+2]=s,t+1}turn(t,e,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:t.x*s+e.x*r,y:t.y*s+e.y*r,z:t.z*s+e.z*r}}onSphere(t,e,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:(t.x*s+e.x*r)*kn.RADIUS,y:(t.y*s+e.y*r)*kn.RADIUS,z:(t.z*s+e.z*r)*kn.RADIUS}}basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(t,e));return[i,this.normalise(this.cross(t,i))]}subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class $n{static MEDIAN_BEDTIME=22+40/60;static MEDIAN_RISING=7;static BEDTIME_SPREAD_H=1.2;static RISING_SPREAD_H=.7;static ALWAYS_UP=.02;static LIT_WHEN_ALL_UP=.5;static UNKNOWN_HOUR=.16;static DUSK_DEG=-1;static NIGHT_DEG=-9;static awakeAt(t){const e=(t%24+24)%24,i=$n.normal(((e<12?e+24:e)-$n.MEDIAN_BEDTIME)/$n.BEDTIME_SPREAD_H),n=$n.normal((e-$n.MEDIAN_RISING)/$n.RISING_SPREAD_H),s=i*(e<12?1-n:1);return Math.max($n.ALWAYS_UP,1-s)}static shareAt(t){return t===void 0||!Number.isFinite(t)?$n.UNKNOWN_HOUR:$n.LIT_WHEN_ALL_UP*$n.awakeAt(t)}static darknessAt(t){return Math.max(0,Math.min(1,($n.DUSK_DEG-t)/($n.DUSK_DEG-$n.NIGHT_DEG)))}static share(t,e){return $n.darknessAt(t)*$n.shareAt(e)}static normal(t){const e=Math.abs(t)/Math.SQRT2,i=1/(1+.3275911*e),n=1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-e*e);return t>=0?.5*(1+n):.5*(1-n)}}class Nh{static STREETLIGHT_RIG="streetlamp";static rigOf(t){if(t.kind==="streetlight"&&!t.lights?.length)return Nh.STREETLIGHT_RIG;const e=t.lights?.map(i=>i.id).join()??"";return J0.forKind(t.kind).find(i=>i.create().map(n=>n.id).join()===e)?.id??""}static viewOf(t,e,i){const n=Xr(t,e),s=r=>Number(r.toFixed(2));return{title:t.title,eastM:s(n.eastM),northM:s(n.northM),saidPosition:t.track?t.track.find(r=>r.t===e)?.saidPosition:t.saidPosition,altitudeM:s(n.altitudeM),headingDeg:s(n.headingDeg??0),color:t.color,sizeM:t.sizeM?{...t.sizeM}:void 0,lit:Sm(t,e,i),headlights:lE(t,e),lightRig:Nh.rigOf(t),observerSide:t.observerSide,model:t.model?{...t.model}:void 0}}static apply(t,e,i,n){switch(i){case"title":return{...t,title:e.title};case"eastM":case"northM":case"saidPosition":case"altitudeM":case"headingDeg":return Nh.placed(t,e,n);case"color":return{...t,color:e.color};case"sizeM.widthM":case"sizeM.lengthM":case"sizeM.heightM":{const s=e.sizeM,r=s!==void 0&&(s.widthM!==void 0||s.lengthM!==void 0||s.heightM!==void 0);return{...t,sizeM:r?{widthM:s.widthM,lengthM:s.lengthM,heightM:s.heightM}:void 0}}case"lit":{const s=[...(t.litKeyframes??[]).filter(r=>r.t!==n),{t:n,lit:e.lit}].sort((r,a)=>r.t-a.t);return{...t,litKeyframes:s}}case"headlights":{const s=[...(t.headlightKeyframes??[]).filter(r=>r.t!==n),{t:n,mode:e.headlights}].sort((r,a)=>r.t-a.t);return{...t,headlightKeyframes:s}}case"lightRig":{if(t.kind==="streetlight"&&e.lightRig===Nh.STREETLIGHT_RIG)return{...t,lights:void 0};if(t.kind==="streetlight"&&!e.lightRig)return{...t,lights:void 0,lit:!1,litKeyframes:void 0};const s=J0.byId(e.lightRig===""?void 0:e.lightRig);return{...t,lights:s?s.create():void 0}}case"observerSide":return{...t,observerSide:du(t.kind)&&e.observerSide?e.observerSide:void 0};case"model.id":return{...t,model:e.model?.id?{id:e.model.id}:void 0};case"model":return{...t,model:e.model};default:return t}}static placed(t,e,i){const n=(e.headingDeg%360+360)%360,s=t.track??(e.altitudeM!==0?[]:void 0);if(s){const a={t:i,eastM:e.eastM,northM:e.northM,altitudeM:e.altitudeM,headingDeg:n};return e.saidPosition&&(a.saidPosition=e.saidPosition),{...t,track:[...s.filter(c=>c.t!==i),a].sort((c,l)=>c.t-l.t)}}const r={...t,eastM:e.eastM,northM:e.northM,headingDeg:n,saidPosition:e.saidPosition};return r.saidPosition||delete r.saidPosition,r}}class Ci{constructor(t,e={}){this.size=t,this.span=Math.min(t.lengthM,Math.max(0,e.spanM??t.lengthM)),this.bank=(t.lengthM-this.span)/2,this.deck=Math.min(t.heightM,e.deckThicknessM??Ci.DEFAULT_DECK_THICKNESS_M),this.railHeight=e.railing?.heightM??Ci.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,e.railing?.postSpacingM??Ci.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(e.railing?.rails??Ci.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(t){const e=Math.abs(t)-this.span/2;return e<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-e/this.bank))}build(){const{widthM:t,heightM:e}=this.size,i=this.span/2,n=[];if(this.span>0){n.push(Ci.box(t,this.deck,this.span,0,e-this.deck/2,0));for(const c of[-1,1]){const l=e-this.deck;l>0&&this.bank>0&&n.push(Ci.box(t+1,l,Ci.ABUTMENT_THICKNESS_M,0,l/2,c*(i-Ci.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(Ci.box(t,.04,this.span,0,e+.02,0));const r=[];for(const c of[-1,1])this.bank<=0||(r.push(this.embankment(c)),s.push(this.bankRoad(c)));const a=[];for(const c of[-1,1])a.push(...this.railing(c*(t/2-Ci.POST_SIDE_M)));return{concrete:Ci.merge(n),road:Ci.merge(s),earth:Ci.merge(r),railing:Ci.merge(a)}}embankment(t){const e=this.size.widthM/2,i=this.stations(t),n=[],s=(l,h,u,d)=>{n.push(l.x,l.y,l.z,h.x,h.y,h.z,u.x,u.y,u.z,l.x,l.y,l.z,u.x,u.y,u.z,d.x,d.y,d.z)},r=l=>{const h=this.roadAt(l),u=e+Ci.BANK_SLOPE*h;return{leftFoot:new T(-u,0,l),leftTop:new T(-e,h,l),rightTop:new T(e,h,l),rightFoot:new T(u,0,l)}};for(let l=1;l<i.length;l++){const h=r(i[l-1]),u=r(i[l]),d=t>0,f=(p,m,g,v)=>d?s(p,m,g,v):s(v,g,m,p);f(h.leftFoot,h.leftTop,u.leftTop,u.leftFoot),f(h.leftTop,h.rightTop,u.rightTop,u.leftTop),f(h.rightTop,h.rightFoot,u.rightFoot,u.rightTop)}const a=r(i[0]);t>0?s(a.leftFoot,a.rightFoot,a.rightTop,a.leftTop):s(a.leftTop,a.rightTop,a.rightFoot,a.leftFoot);const c=new be;return c.setAttribute("position",new pe(n,3)),c.computeVertexNormals(),c}bankRoad(t){const e=this.size.widthM/2,i=this.stations(t),n=[];for(let r=1;r<i.length;r++){const a=i[r-1],c=i[r],l=this.roadAt(a)+.02,h=this.roadAt(c)+.02,u=t>0?[[-e,l,a],[e,l,a],[e,h,c],[-e,h,c]]:[[-e,h,c],[e,h,c],[e,l,a],[-e,l,a]];for(const d of[0,2,1,0,3,2])n.push(...u[d])}const s=new be;return s.setAttribute("position",new pe(n,3)),s.computeVertexNormals(),s}stations(t){const e=[];for(let i=0;i<=Ci.BANK_STATIONS;i++)e.push(t*(this.span/2+this.bank*i/Ci.BANK_STATIONS));return e}railing(t){const e=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),n=[];for(let a=0;a<=i;a++)n.push(-e+this.size.lengthM*a/i);const s=[],r=Ci.POST_SIDE_M;for(const a of n)s.push(Ci.box(r,this.railHeight,r,t,this.roadAt(a)+this.railHeight/2,a));for(let a=1;a<=this.rails;a++){const c=this.railHeight*a/this.rails-Ci.RAIL_HEIGHT_M/2;for(let l=1;l<n.length;l++){const h=new T(t,this.roadAt(n[l-1])+c,n[l-1]),u=new T(t,this.roadAt(n[l])+c,n[l]);s.push(Ci.beam(h,u))}}return s}static box(t,e,i,n,s,r){return new en(t,e,i).translate(n,s,r)}static beam(t,e){const i=new T().subVectors(e,t),n=new en(Ci.RAIL_DEPTH_M,Ci.RAIL_HEIGHT_M,i.length()),s=new es().setFromUnitVectors(new T(0,0,1),i.clone().normalize()),r=new T().addVectors(t,e).multiplyScalar(.5);return n.applyMatrix4(new Gt().compose(r,s,new T(1,1,1)))}static merge(t){const e=t.map(c=>c.getIndex()?c.toNonIndexed():c),i=e.reduce((c,l)=>c+l.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const c of e){const l=c.getAttribute("position"),h=c.getAttribute("normal");n.set(l.array,r*3),h&&s.set(h.array,r*3),r+=l.count}const a=new be;a.setAttribute("position",new pe(n,3)),a.setAttribute("normal",new pe(s,3));for(const c of t)c.dispose();for(const c of e)c.dispose();return a}}class Pi{static OVERHANG_M=.25;static SLAB_M=.2;static MIN_RIDGE_M=.1;static DEFAULT_RISE_M=3;static normalised(t){const e=t.shape??"flat";return{shape:e,riseM:e==="flat"?0:Math.max(0,t.riseM??Pi.DEFAULT_RISE_M),ridge:t.ridge??"width",...t.color?{color:t.color}:{}}}static build(t,e,i){const n=Pi.normalised(t),s=n.shape==="gable"&&n.ridge==="depth",r=(s?i:e)/2+Pi.OVERHANG_M,a=(s?e:i)/2+Pi.OVERHANG_M,c=n.shape==="flat"||n.riseM<=0?Pi.slab(r,a):n.shape==="dome"?Pi.dome(r-Pi.OVERHANG_M,a-Pi.OVERHANG_M,r,a,n.riseM):Pi.pitched(n.shape,r,a,n.riseM);return s&&c.rotateY(Math.PI/2),c.computeVertexNormals(),c}static slab(t,e){const i=Pi.SLAB_M,n=[[-t,0,-e],[t,0,-e],[t,0,e],[-t,0,e]],s=n.map(([c,,l])=>[c,i,l]),r=[],a=(c,l,h,u)=>{r.push(c,l,h,c,h,u)};a(s[0],s[3],s[2],s[1]);for(let c=0;c<4;c++){const l=(c+1)%4;a(n[c],n[l],s[l],s[c])}return Pi.of(r)}static pitched(t,e,i,n){const s=(h,u)=>[h,0,u],r=t==="gable"?e:Math.max(Pi.MIN_RIDGE_M/2,e-i),a=[-r,n,0],c=[r,n,0],l=[];return l.push(s(-e,-i),s(e,-i),c,s(-e,-i),c,a),l.push(s(e,i),s(-e,i),a,s(e,i),a,c),l.push(s(-e,i),s(-e,-i),a),l.push(s(e,-i),s(e,i),c),l.push(s(-e,-i),s(-e,i),s(e,i),s(-e,-i),s(e,i),s(e,-i)),Pi.of(l)}static DOME_RINGS=12;static DOME_SECTORS=48;static dome(t,e,i,n,s){const r=Pi.slab(i,n).getAttribute("position").array,a=[];for(let l=0;l<r.length;l+=3)a.push([r[l],r[l+1],r[l+2]]);const c=(l,h)=>{const u=l/Pi.DOME_RINGS*(Math.PI/2),d=h/Pi.DOME_SECTORS*2*Math.PI,f=Math.cos(u);return[t*f*Math.cos(d),Pi.SLAB_M+s*Math.sin(u),e*f*Math.sin(d)]};for(let l=0;l<Pi.DOME_RINGS;l++)for(let h=0;h<Pi.DOME_SECTORS;h++){const u=h+1;a.push(c(l,h),c(l+1,u),c(l,u),c(l,h),c(l+1,h),c(l+1,u))}return Pi.of(a)}static of(t){const e=new be;return e.setAttribute("position",new pe(t.flat(),3)),e}}class yr{static SLAB_M=.6;static SLABS=4;static SIZE=512;static JOINT_M=.012;static made;static texture(){if(yr.made)return yr.made;const t=yr.SIZE,e=new Uint8Array(t*t*4);let i=23063;const n=()=>{i=i+1831565813|0;let f=Math.imul(i^i>>>15,1|i);return f=f+Math.imul(f^f>>>7,61|f)^f,((f^f>>>14)>>>0)/4294967296},s=yr.SLABS,r=t/s,a=Math.max(1,Math.round(yr.JOINT_M/yr.SLAB_M*r)),c=Array.from({length:s*s},()=>.9+.1*n()),l=s*8,h=Array.from({length:l*l},()=>n()),u=(f,p)=>h[(p%l+l)%l*l+(f%l+l)%l];for(let f=0;f<t;f++)for(let p=0;p<t;p++){const m=Math.floor(p/r),g=Math.floor(f/r),v=p-m*r,M=f-g*r,w=v<a||M<a,y=p/r*8,x=f/r*8,b=Math.floor(y),E=Math.floor(x),S=y-b,A=x-E,_=S*S*(3-2*S),I=A*A*(3-2*A),D=(u(b,E)*(1-_)+u(b+1,E)*_)*(1-I)+(u(b,E+1)*(1-_)+u(b+1,E+1)*_)*I,O=n(),P=w?.55:c[g*s+m]*(.9+.12*D)*(.88+.12*O),N=Math.min(255,Math.round(255*P)),k=(f*t+p)*4;e[k]=N,e[k+1]=N,e[k+2]=N,e[k+3]=255}const d=new Ds(e,t,t,tn,fs);return d.wrapS=d.wrapT=bc,d.minFilter=cr,d.generateMipmaps=!0,d.colorSpace=Bn,d.anisotropy=8,d.needsUpdate=!0,yr.made=d,d}static layOn(t){const e=t.getAttribute("position"),i=yr.SLAB_M*yr.SLABS,n=new Float32Array(e.count*2);for(let s=0;s<e.count;s++)n[s*2]=e.getX(s)/i,n[s*2+1]=e.getZ(s)/i;t.setAttribute("uv",new pe(n,2))}}class Ot{static UPPER=0;static GROUND_WINDOW=1;static GROUND_DOOR=2;static PLAIN=3;static TALL=4;static LANCET=5;static TILES=6;static TALL_SILL=.5;static TALL_HEAD=2.62;static BAY_M=3;static FLOOR_M=3;static PIXELS=96;static shared;static sharedEmissive;static texture(){if(!Ot.shared){const t=new Ds(Ot.pixels(),Ot.PIXELS*Ot.TILES,Ot.PIXELS,tn,fs);t.colorSpace=Bn,t.wrapS=Qi,t.wrapT=Qi,t.magFilter=Me,t.minFilter=cr,t.generateMipmaps=!0,t.needsUpdate=!0,Ot.shared=t}return Ot.shared}static emissive(){if(!Ot.sharedEmissive){const t=new Ds(Ot.glow(),Ot.PIXELS*Ot.TILES,Ot.PIXELS,tn,fs);t.colorSpace=Bn,t.wrapS=Qi,t.wrapT=Qi,t.magFilter=Me,t.minFilter=cr,t.generateMipmaps=!0,t.needsUpdate=!0,Ot.sharedEmissive=t}return Ot.sharedEmissive}static glow(){const t=Ot.PIXELS,e=t*Ot.TILES,i=new Uint8Array(e*t*4);for(let r=3;r<i.length;r+=4)i[r]=255;const n=t/Ot.BAY_M,s=[[Ot.UPPER,.9,2.3],[Ot.GROUND_WINDOW,.9,2.3],[Ot.TALL,Ot.TALL_SILL,Ot.TALL_HEAD]];for(const[r,a,c]of s)for(let l=Math.round(a*n);l<Math.round(c*n);l++)for(let h=Math.round(.9*n);h<Math.round(2.1*n);h++){if(Math.abs(h-1.5*n)<.03*n)continue;const u=(l*e+r*t+h)*4,[d,f,p]=Ot.roomLight((h/n-.9)/1.2,(l/n-a)/(c-a));i[u]=d,i[u+1]=f,i[u+2]=p}return i}static roomLight(t,e){const i=.35+.65*Math.pow(Math.max(0,Math.min(1,e)),.8),n=1-.45*Math.pow(Math.abs(2*t-1),3),s=Math.min(t,1-t)<.16,r=i*n*(s?.35:1),a=s?[255,225,195]:[255,255,255],c=Math.pow(r,1/2.2);return[Math.round(a[0]*c),Math.round(a[1]*c),Math.round(a[2]*c)]}static pixels(){const t=Ot.PIXELS,e=t*Ot.TILES,i=new Uint8Array(e*t*4).fill(255),n=t/Ot.BAY_M,s=(p,m,g,v,M,w)=>{for(let y=Math.round(g*n);y<Math.round(M*n);y++)for(let x=Math.round(m*n);x<Math.round(v*n);x++){const b=(y*e+p*t+x)*4;i[b]=w[0],i[b+1]=w[1],i[b+2]=w[2],i[b+3]=255}},r=[225,225,222],a=[34,42,54],c=[200,198,192];for(const p of[Ot.UPPER,Ot.GROUND_WINDOW])s(p,.9-.06,.9-.06,2.1+.06,2.3+.06,r),s(p,.9,.9,2.1,2.3,a),s(p,1.5-.02,.9,1.5+.02,2.3,r),s(p,.8,.84,2.2,.9-.06,c);s(Ot.GROUND_DOOR,1-.06,0,2+.06,2.1+.06,r),s(Ot.GROUND_DOOR,1,0,2,2.1,[58,62,56]);const l=[44,44,46],h=Ot.TALL;s(h,0,0,3,.09,[214,210,202]),s(h,.9-.08,Ot.TALL_SILL-.04,2.1+.08,Ot.TALL_HEAD+.1,r),s(h,.9,Ot.TALL_SILL,2.1,Ot.TALL_HEAD,a),s(h,1.5-.02,Ot.TALL_SILL,1.5+.02,Ot.TALL_HEAD,r),s(h,.82,Ot.TALL_SILL,2.18,Ot.TALL_SILL+.05,l),s(h,.82,Ot.TALL_SILL+.38,2.18,Ot.TALL_SILL+.43,l);for(let p=.86;p<2.15;p+=.13)s(h,p,Ot.TALL_SILL,p+.03,Ot.TALL_SILL+.4,l);const u=Ot.LANCET,d=2,f=2.34;s(u,1.2,.66,1.8,d,[40,44,54]);for(let p=d;p<f;p+=1/n){const m=.3*Math.sqrt(1-((p-d)/(f-d))**2);s(u,1.5-m,p,1.5+m,p+1/n,[40,44,54])}return i}}class Ad{static hash(t,e){const i=Math.sin(t*12.9898+e*78.233)*43758.5453;return i-Math.floor(i)}static LANCET_BAY_M=6;static LANCET_TIER_M=10;static build(t,e,i,n=!0,s=0,r,a=Ot.FLOOR_M){const c=[],l=[],h=[],u=t/2,d=e/2,f=r==="lancet",p=Math.max(1,Math.round(i/(f?Ad.LANCET_TIER_M:Math.max(a,1)))),m=i/p,g=f?Ad.LANCET_BAY_M:Ot.BAY_M,v=(y,x,b,E)=>{const S=Math.max(1,Math.round(b/g)),A=b/S;for(let _=0;_<p;_++)for(let I=0;I<S;I++){const D=E&&_===0&&I===Math.floor((S-1)/2),O=n?f?(p-1-_)%2===0?Ot.LANCET:Ot.PLAIN:D?Ot.GROUND_DOOR:r==="tall"?Ot.TALL:_>0?Ot.UPPER:Ot.GROUND_WINDOW:Ot.PLAIN,P=O===Ot.UPPER||O===Ot.GROUND_WINDOW||O===Ot.TALL?Ad.hash(s,c.length):2;for(let Ut=0;Ut<6;Ut++)h.push(P);const N=y[0]+x[0]*A*I,k=y[1]+x[1]*A*I,B=N+x[0]*A,W=k+x[1]*A,Q=_*m,Z=Q+m,nt=O/Ot.TILES+.002,ot=(O+1)/Ot.TILES-.002;c.push(N,Q,k,B,Q,W,B,Z,W,N,Q,k,B,Z,W,N,Z,k),l.push(nt,.002,ot,.002,ot,.998,nt,.002,ot,.998,nt,.998)}};v([u,-d],[-1,0],t,!0),v([-u,d],[1,0],t,!1),v([-u,-d],[0,1],e,!1),v([u,d],[0,-1],e,!1);const M=Ot.PLAIN/Ot.TILES+.01;c.push(-u,i,-d,-u,i,d,u,i,d,-u,i,-d,u,i,d,u,i,-d);for(let y=0;y<6;y++)l.push(M,.5),h.push(2);const w=new be;return w.setAttribute("position",new pe(c,3)),w.setAttribute("uv",new pe(l,2)),w.setAttribute("litRank",new pe(h,1)),w.computeVertexNormals(),w}}class al{constructor(t,e={}){this.size=t,this.structure=e}static DEFAULT_DIAMETER_M=.008;static POLE_RADIUS_M=.13;static POLE_ABOVE_M=.5;static NATURAL_SIZE=Object.freeze({widthM:1,lengthM:30,heightM:5});get strands(){const t=this.structure.strands;return!t||t.length===0?[{heightM:this.size.heightM,acrossM:0}]:t.map(e=>({heightM:e.heightM,acrossM:e.acrossM??0}))}get poleStations(){const t=this.size.lengthM/2;switch(this.structure.poles??"both"){case"start":return[t];case"end":return[-t];case"none":return[];default:return[-t,t]}}get poleHeightM(){return this.structure.poleHeightM??Math.max(...this.strands.map(t=>t.heightM))+al.POLE_ABOVE_M}build(){const t=this.structure.diameterM??al.DEFAULT_DIAMETER_M,e=this.strands.map(n=>{const s=new gs(t/2,t/2,this.size.lengthM,6);return s.rotateX(Math.PI/2),s.translate(n.acrossM,n.heightM,0),s}),i=this.poleStations.map(n=>{const s=new gs(al.POLE_RADIUS_M*.8,al.POLE_RADIUS_M,this.poleHeightM,8);return s.translate(0,this.poleHeightM/2,n),s});return{strands:e,poles:i}}}class mn{static TILE_M=2.4;static COLUMNS=6;static COURSES=10;static SIZE_PX=256;static FOUNDATION_M=.8;static pattern;static build(t){const e=new Ke,i=t.sizeM?.widthM??.6,n=t.sizeM?.heightM??1,s=t.sizeM?.lengthM??10,r=n+mn.FOUNDATION_M,a=new en(i,r,s);mn.layStones(a,i,r,s);const c=new Rr({map:mn.texture()}),l=new yt(a,c);return l.position.y=(n-mn.FOUNDATION_M)/2,l.castShadow=!0,l.receiveShadow=!0,l.userData={emissive:!1},e.add(l),e}static layStones(t,e,i,n){const s=t.getAttribute("uv");[[n,i],[n,i],[e,n],[e,n],[e,i],[e,i]].forEach(([a,c],l)=>{for(let h=l*4;h<l*4+4;h++)s.setXY(h,s.getX(h)*a/mn.TILE_M,s.getY(h)*c/mn.TILE_M)}),s.needsUpdate=!0}static texture(){if(mn.pattern)return mn.pattern;const t=mn.SIZE_PX,e=new Uint8Array(t*t*4),i=mn.seeds();for(let s=0;s<t;s++)for(let r=0;r<t;r++){const a=r/t,c=s/t;let l=1/0,h=1/0,u=i[0];for(const M of i)for(let w=-1;w<=1;w++)for(let y=-1;y<=1;y++){const x=(a-(M.x+w))*mn.COLUMNS,b=(c-(M.y+y))*mn.COURSES*.5,E=.8*Math.max(Math.abs(x),Math.abs(b))+.2*Math.hypot(x,b);E<l?(h=l,l=E,u=M):E<h&&(h=E)}const d=h-l,f=Math.min(d/.1,1),p=.8+.2*Math.min(d/.5,1),m=.94+.12*mn.noise(r,s),g=(.15+(u.tone-.15)*f)*(f>.999?p*m:1),v=(s*t+r)*4;e[v]=Math.round(255*g*u.warm),e[v+1]=Math.round(255*g),e[v+2]=Math.round(255*g*u.cool),e[v+3]=255}const n=new Ds(e,t,t,tn);return n.wrapS=n.wrapT=bc,n.colorSpace=Bn,n.magFilter=Me,n.minFilter=cr,n.generateMipmaps=!0,n.anisotropy=4,n.needsUpdate=!0,mn.pattern=n,n}static seeds(){let t=20260831;const e=()=>(t=t*1664525+1013904223>>>0,t/4294967296),i=[];for(let n=0;n<mn.COURSES;n++)for(let s=0;s<mn.COLUMNS;s++){const r=.34+e()*.24;i.push({x:(s+n%2*.5+.5+(e()-.5)*.35)/mn.COLUMNS,y:(n+.5+(e()-.5)*.3)/mn.COURSES,tone:r,warm:1+e()*.1,cool:.9+e()*.1})}return i}static noise(t,e){const i=Math.sin(t*12.9898+e*78.233)*43758.5453;return i-Math.floor(i)}}class Te{static HEAD_WIDTH_M=.34;static HEAD_DEPTH_M=.24;static HEAD_MARGIN_M=.18;static POLE_RADIUS_M=.055;static HOUSING=[.05,.05,.05];static POLE=[.16,.17,.17];static BAND_M=.5;static BAND_GAP_M=.5;static KERB_CLEAR_M=.25;static CROSSING_LIFT_M=.08;static PAINT=[.8,.8,.78];static SIGN_POLE_RADIUS_M=.03;static SIGN_CENTRE_Y_M=2.55;static SIGN_METAL=[.48,.49,.5];static SIGN_RED=[.62,.05,.05];static SIGN_WHITE=[.82,.82,.8];static trafficLight(t){const e=t?2:3,i=t?me.PEDESTRIAN_HEAD_Y_M:me.VEHICLE_HEAD_Y_M,n=me.LENS_SPACING_M,s=(e-1)*n+2*Te.HEAD_MARGIN_M,r=i-s/2+.05,a=[Te.part(new gs(Te.POLE_RADIUS_M,Te.POLE_RADIUS_M,r,8),Te.POLE,0,r/2,0),Te.part(new en(Te.HEAD_WIDTH_M,s,Te.HEAD_DEPTH_M),Te.HOUSING,0,i,0)];for(let c=0;c<e;c++){const l=i+((e-1)/2-c)*n;a.push(Te.part(new en(.26,.02,.16),Te.HOUSING,0,l+.12,-.2))}return Te.group(a)}static crossing(t,e){const i=Te.BAND_M,n=i+Te.BAND_GAP_M,s=Math.max(i,t-2*Te.KERB_CLEAR_M),r=Math.max(1,Math.floor((s+Te.BAND_GAP_M)/n)),a=-((r-1)*n)/2,c=[],l=[],h=Te.CROSSING_LIFT_M,u=e/2;for(let g=0;g<r;g++){const v=a+g*n-i/2,M=v+i;c.push(v,h,u,M,h,u,M,h,-u,v,h,u,M,h,-u,v,h,-u);for(let w=0;w<6;w++)l.push(0,1,0)}const d=new be;d.setAttribute("position",new pe(c,3)),d.setAttribute("normal",new pe(l,3));const f=new Rr({color:16777215});f.color.setRGB(...Te.PAINT),f.polygonOffset=!0,f.polygonOffsetFactor=-4,f.polygonOffsetUnits=-4;const p=new yt(d,f);p.userData={emissive:!1},p.receiveShadow=!0,p.castShadow=!1;const m=new Ke;return m.add(p),m}static drape(t,e){t.traverse(i=>{const n=i;if(!n.isMesh)return;const s=n.geometry.getAttribute("position"),r=n.userData.crossingRest??=Float32Array.from(s.array);for(let a=0;a<s.count;a++)s.setY(a,r[a*3+1]+e(r[a*3],r[a*3+2]));s.needsUpdate=!0,n.geometry.computeBoundingSphere(),n.geometry.computeBoundingBox()})}static roadSign(t){const e=Te.SIGN_CENTRE_Y_M,i=t?.face??"other",[n,s,r]=i==="stop"?[.38,8,Math.PI/8]:i==="give-way"?[.52,3,0]:i==="speed-limit"?[.325,24,0]:[0,0,0],a=e+(i==="other"?.3:n),c=Te.SIGN_POLE_RADIUS_M,l=[Te.part(new gs(c,c,a,6),Te.SIGN_METAL,0,a/2,0)],h=(u,d,f,p)=>{const m=new gs(u,u,d,s,1,!1,r);m.rotateX(Math.PI/2),l.push(Te.part(m,p,0,e,-f))};if(i==="other")l.push(Te.part(new en(.6,.6,.012),Te.SIGN_METAL,0,e,-.038)),l.push(Te.part(new en(.58,.58,.004),Te.SIGN_WHITE,0,e,-.047));else{h(n,.012,c+.008,Te.SIGN_METAL);const[u,d,f]=i==="stop"?[Te.SIGN_WHITE,Te.SIGN_RED,.92]:[Te.SIGN_RED,Te.SIGN_WHITE,i==="give-way"?.68:.77];h(n*.99,.004,c+.017,u),h(n*f,.003,c+.0205,d)}return Te.group(l)}static pedestrianFigure(t,e){const i=t==="standing"?[[-.17,.25],[.17,.25],[.17,-.08],[.1,-.08],[.1,-.5],[.02,-.5],[.02,-.12],[-.02,-.12],[-.02,-.5],[-.1,-.5],[-.1,-.08],[-.17,-.08]]:[[-.05,.26],[-.09,.22],[-.24,.05],[-.19,.01],[-.07,.13],[-.07,0],[-.18,-.22],[-.29,-.47],[-.22,-.5],[-.1,-.25],[-.01,-.07],[.09,-.27],[.13,-.5],[.21,-.48],[.16,-.24],[.07,0],[.07,.11],[.2,0],[.24,.05],[.08,.22],[.05,.26]],n=new eM(i.map(([a,c])=>new tt(a,c))),s=new eM;s.absarc(t==="standing"?0:-.02,.38,.1,0,2*Math.PI,!1);const r=new Ey([n,s],6);return r.scale(e,e,e),r.rotateY(Math.PI),r}static part(t,e,i,n,s){return{geometry:t,color:e,matrix:new Gt().makeTranslation(i,n,s)}}static group(t){const e=[],i=[],n=[];for(const{geometry:c,color:l,matrix:h}of t){const u=c.index?c.toNonIndexed():c;u.applyMatrix4(h);const d=u.getAttribute("position"),f=u.getAttribute("normal");for(let p=0;p<d.count;p++)e.push(d.getX(p),d.getY(p),d.getZ(p)),i.push(f.getX(p),f.getY(p),f.getZ(p)),n.push(...l);u!==c&&u.dispose(),c.dispose()}const s=new be;s.setAttribute("position",new pe(e,3)),s.setAttribute("normal",new pe(i,3)),s.setAttribute("color",new pe(n,3));const r=new yt(s,new Rr({color:16777215,vertexColors:!0}));r.userData={emissive:!1},r.castShadow=!0,r.receiveShadow=!0;const a=new Ke;return a.add(r),a}}class su{static MIN_K=1667;static MAX_K=25e3;static ofTemperature(t){const e=Math.min(su.MAX_K,Math.max(su.MIN_K,t)),i=e<=4e3?-266123900/e**3-234358.9/e**2+877.6956/e+.17991:-3025846900/e**3+21070379e-1/e**2+222.6347/e+.24039,n=e<=2222?-1.1063814*i**3-1.3481102*i**2+2.18555832*i-.20219683:e<=4e3?-.9549476*i**3-1.37418593*i**2+2.09137015*i-.16748867:3.081758*i**3-5.8733867*i**2+3.75112997*i-.37001483,s=i/n,r=(1-i-n)/n,a=[3.2406*s-1.5372-.4986*r,-.9689*s+1.8758+.0415*r,.0557*s-.204+1.057*r].map(l=>Math.max(0,l)),c=.2126*a[0]+.7152*a[1]+.0722*a[2];return[a[0]/c,a[1]/c,a[2]/c]}}const i1=Math.PI/180;function ti(o,t,e,i,n=!1,s){const r=n&&s?new Rr({color:new rt(...s),emissive:new rt(...e)}):n?new Is({color:new rt(...e)}):new Rr({color:new rt(...e)}),a=new yt(t,r);return a.position.y=i,a.userData={emissive:n},a.castShadow=!n,a.receiveShadow=!n,o.add(a),a}const n1=.25,$N=.002,YN=100,Tb=3e4,KN=1500,qN=.25,ZN=1e3,JN=.15;function jN(o){const t=/^#([0-9a-f]{6})$/i.exec(o);if(!t)return[1,1,1];const e=parseInt(t[1],16),i=n=>{const s=n/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4};return[i(e>>16&255),i(e>>8&255),i(e&255)]}const QN=[.62,.62,.6],tL=[1,.85,.5],eL=[.25,.25,.25],g3=[1,.97,.85],iL=[.55,.68,.72],nL=.12,ma=.03,ga=.05,v3={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function _s(o,t){return o?.[t]}function va(o,t,e,i,n,s,r,a){if(a===void 0)return;const c=new Is({color:new rt(...iL).multiplyScalar(nL),transparent:!0,opacity:a/100,depthWrite:!1}),l=new yt(new en(t,e,i),c);l.position.set(n,s,r),l.renderOrder=2,o.add(l)}const Mr=.05,s1=[.6,.58,.53],Rb=[.5,.5,.48];function Lh(o,t,e,i,n,s,r,a){const c=new Rr({color:new rt(...a),side:zi}),l=new yt(new en(t,e,i),c);l.position.set(n,s,r),o.add(l)}function sL(o,t,e,i,n,s,r,a,c){const l=(i-s)/2,h=(p,m,g,v)=>{p<=0||(t?Lh(o,p,m,Mr,g,a+v,r,c):Lh(o,Mr,m,p,r,a+v,g,c))};h(e,l,0,i/2-l/2),h(e,l,0,-(i/2-l/2));const u=[...n].sort((p,m)=>p.center-m.center);let d=-e/2;for(const p of u){const g=p.center-p.main/2-d;h(g,s,d+g/2,0),d=p.center+p.main/2}const f=e/2-d;h(f,s,d+f/2,0)}function M3(o,t,e,i,n,s,r,a,c,l){const h=(i+n)/2,u=n-i,d=(f,p,m,g)=>{f.length===0?p?Lh(o,m,u,Mr,0,h,g,s1):Lh(o,Mr,u,m,g,h,0,s1):sL(o,p,m,u,f,s,g,h,s1)};d(r,!0,t*2,-e+Mr),d(a,!0,t*2,e-Mr),d(c,!1,e*2,-t+Mr),d(l,!1,e*2,t-Mr),Lh(o,t*2,Mr,e*2,0,i+Mr,0,Rb),Lh(o,t*2,Mr,e*2,0,n-Mr,0,Rb)}function wM(o,t,e,i){switch(o){case"front":return{x:0,z:-(e-i)};case"behind":return{x:0,z:e-i};case"left":return{x:-(t-i),z:0};case"right":return{x:t-i,z:0};case"front-left":return{x:-(t-i),z:-ya};case"front-right":return{x:t-i,z:-ya};case"behind-left":return{x:-(t-i),z:ya};case"behind-right":return{x:t-i,z:ya}}}function y3(o,t,e,i,n,s,r,a){const c=SM();c.scale.setScalar(n),c.rotation.y=v3[e];const{x:l,z:h}=wM(t,s,r,a);c.position.set(l,i,h),o.add(c)}const xM=6,bM=6,Ma=3,Yu=1.4,Ku=Ma*.5,w3=1.2,x3=.35,rL=.75,aL=1.6;function Ib(o,t,e,i,n){const s=new Ke,r=Math.max(1,o+1),a=r*Ma;ti(s,new en(xM,a,bM),[.55,.54,.5],a/2);const c=xM/2,l=bM/2;for(let h=0;h<r;h++){const u=h*Ma+Ma/2;va(s,Yu,Ku,ga,0,u,-l-ma,_s(t,"front")),va(s,Yu,Ku,ga,0,u,l+ma,_s(t,"behind")),va(s,ga,Ku,Yu,-c-ma,u,0,_s(t,"left")),va(s,ga,Ku,Yu,c+ma,u,0,_s(t,"right"))}if(e){const h=Math.min(Math.max(i??0,0),r-1);y3(s,e,n??e,h*Ma,.72,c,l,w3);const u=d=>_s(t,d)!==void 0?[{main:Yu,center:0}]:[];M3(s,c,l,h*Ma,(h+1)*Ma,Ku,u("front"),u("behind"),u("left"),u("right"))}return s}function Db(){const o=new Ke,t=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[e,i,n,s]of t){const r=new hn(n,10,7);r.scale(1,.85,1),r.translate(e,0,i),ti(o,r,[.26,.28,.17],s)}return o}function oL(o){const t=new Ke,e=new Ci(dt.sizeOf(o),o.bridge).build();ti(t,e.concrete,[.6,.6,.58],0);const i=ti(t,e.road,[.2,.2,.21],0),n=ti(t,e.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=Tn;return ti(t,e.railing,[.5,.52,.55],0),t}function cL(o){const t=new Ke,e=new al(dt.sizeOf(o),o.wire).build();for(const i of e.strands)ti(t,i,[.1,.1,.11],0);for(const i of e.poles)ti(t,i,[.3,.24,.18],0);return t}function Cb(){const o=new Ke;return ti(o,new gs(.15,.22,2,8),[.32,.22,.14],1),ti(o,new bu(1.4,3,8),[.16,.32,.14],3.5),o}const Ob=.275,lL=.35,hL=.9,uL=34,dL=8,fL=1.4;function Pb(){const o=new Ke,t=new hn(Ob,7,3,0,Math.PI*2,0,Math.PI/2);t.scale(1,lL/Ob,1);const e=dt.repeatOnGrid(t,uL,hL,dL,fL),i=ti(o,e,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=e.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=t.getAttribute("position").count,t.dispose(),o}function Nb(){const o=new Ke,t=new hn(1,7,3,0,Math.PI*2,0,Math.PI/2);return ti(o,t,[.38,.36,.32],0),o}const pL=[.24,.22,.18],mL=[.14,.17,.08];function gL(){const o=new Ke,t=ti(o,new en(1,1,1),pL,.5),e=ti(o,new en(1,.03,1),mL,1.015);for(const i of[t,e])i.material.side=Tn;return e.castShadow=!1,nu.install(e.material,!0),o}function Lb(o,t,e){const i=new Ke;t!=="wall"&&ti(i,new gs(.05,.08,5,8),[.28,.28,.3],2.5);const n=ti(i,new hn(.25,12,8),o?dt.lampHue(e):[0,0,0],5.1,!0,QN);return p3.applyOpaque(n.material),i}const vL=[.08,.08,.08],Go=.8,mh=1,na=1.7,r1=.6,Nc=.46,Ap=1.5,ih=.8,ya=.5,ML=na;function kb(o,t,e,i){const n=new Ke;ti(n,new en(1.8,1.4,4.2),[.45,.14,.14],.7),ti(n,new en(Go*2,r1,mh*2),[.4,.12,.12],na);for(const r of[-1.4,1.4])for(const a of[-.95,.95]){const c=ti(n,new gs(.4,.4,.3,12),vL,.4);c.rotation.z=Math.PI/2,c.position.x=a,c.position.z=r}const s=o?g3:[0,0,0];for(const r of[-.7,.7])ti(n,new hn(.15,8,6),s,.7,!0,eL).position.set(r,.7,-2.1);if(va(n,Ap,Nc,ga,0,na,-mh-ma,_s(t,"front")),va(n,Ap,Nc,ga,0,na,mh+ma,_s(t,"behind")),va(n,ga,Nc,ih,-Go-ma,na,-ya,_s(t,"front-left")),va(n,ga,Nc,ih,-Go-ma,na,ya,_s(t,"behind-left")),va(n,ga,Nc,ih,Go+ma,na,-ya,_s(t,"front-right")),va(n,ga,Nc,ih,Go+ma,na,ya,_s(t,"behind-right")),e){y3(n,e,i??e,rL,.5,Go,mh,x3);const r=(l,h)=>{const u=[];return _s(t,l)!==void 0&&u.push({main:ih,center:-ya}),_s(t,h)!==void 0&&u.push({main:ih,center:ya}),u},a=_s(t,"front")!==void 0?[{main:Ap,center:0}]:[],c=_s(t,"behind")!==void 0?[{main:Ap,center:0}]:[];M3(n,Go,mh,na-r1/2,na+r1/2,Nc,a,c,r("front-left","behind-left"),r("front-right","behind-right"))}return n}const Fb=new Map;function Ub(o,t){if(!o)return;const e=[[o.lengthM,t.lengthM],[o.heightM,t.heightM],[o.widthM,t.widthM]];for(const[i,n]of e)if(i!==void 0&&n>1e-6)return i/n}function a1(o,t){return t>1e-6?o/t:1}const b3=[.95,.9,.82],zb=[.72,.74,.78];function Bb(){const o=new Ke;ti(o,new gs(.25,.3,1.5,10),zb,.75),ti(o,new hn(.26,10,8),zb,1.74);const t=ti(o,new bu(.07,.16,8),b3,1.74);return t.rotation.x=-Math.PI/2,t.position.z=-.22,o}function SM(){const o=new Ke;ti(o,new gs(.25,.3,1.5,10),[.3,.3,.35],.75),ti(o,new hn(.22,10,8),[.62,.52,.46],1.72);const t=ti(o,new bu(.07,.16,8),b3,1.72);return t.rotation.x=-Math.PI/2,t.position.z=-.2,o}const yL=17,Hb=18.5,o1=[.16,.16,.18];function Gb(){const o=new Ke,t=ti(o,new gs(1.8,1.8,Hb*2,10),o1,0);t.rotation.x=Math.PI/2,ti(o,new en(yL*2,.5,4.5),o1,0);const e=ti(o,new en(.4,5.5,4),o1,3);return e.position.z=-Hb+2,o}class dt{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound","terrace","wall","building","bridge"]);static groundUnderFootprint(t,e,i,n,s,r=0){const a=dt.sizeOf(t);if(r>a.heightM)return s(e,i);const c=(n??0)*Math.PI/180,l=t.kind==="bridge"?Math.min(a.lengthM,t.bridge?.spanM??a.lengthM):a.lengthM,h=Math.min(21,Math.max(2,Math.ceil(l/.75)+1)),u=Math.min(21,Math.max(2,Math.ceil(a.widthM/.75)+1)),d=dt.GROWS_FROM_GROUND.has(t.kind);let f=d?1/0:-1/0;for(let p=0;p<h;p++){const m=(p/(h-1)-.5)*l;for(let g=0;g<u;g++){const v=(g/(u-1)-.5)*a.widthM,M=e+Math.sin(c)*m+Math.cos(c)*v,w=i-Math.cos(c)*m+Math.sin(c)*v;f=d?Math.min(f,s(M,w)):Math.max(f,s(M,w))}}return Number.isFinite(f)?f:s(e,i)}static wireGround(t,e,i,n,s){const r=dt.sizeOf(t).lengthM/2,a=(n??0)*Math.PI/180,c=s(e+Math.sin(a)*r,i-Math.cos(a)*r),l=s(e-Math.sin(a)*r,i+Math.cos(a)*r);return{startY:l,dropM:c-l}}static shearWire(t,e,i){e<=0||t.traverse(n=>{const s=n;if(!s.isMesh)return;const r=s.geometry.getAttribute("position"),a=s.userData.wireRest??=Float32Array.from(r.array);for(let c=0;c<r.count;c++){const l=.5-a[c*3+2]/e;r.setY(c,a[c*3+1]+i*l)}r.needsUpdate=!0,s.geometry.computeBoundingSphere(),s.geometry.computeBoundingBox()})}static occupantView(t,e=t.headingDeg){const i=t.observerSide;if(!i)throw new Error("occupantView requires object.observerSide to be set");const{x:n,z:s}=t.kind==="vehicle"?wM(i,Go,mh,x3):wM(i,xM/2,bM/2,w3),r=t.kind==="vehicle"?ML:(t.occupiedFloor??0)*Ma+aL,a=(e??0)-v3[t.observerFacing??i]/i1,c=this.scaleFor(t);return{x:n*c.x,z:s*c.z,eyeY:r*c.y,headingDeg:a}}static BODY_NAME="decor-body";static bodyOf(t){return t.getObjectByName(dt.BODY_NAME)??t}static repeatOnGrid(t,e,i,n,s){const r=t.getAttribute("position"),a=t.getAttribute("normal"),c=t.getIndex();if(!c)throw new Error("repeatOnGrid needs an indexed geometry");const l=r.count,h=e*n,u=new Float32Array(l*h*3),d=new Float32Array(l*h*3),f=new Uint32Array(c.count*h),p=-((e-1)*i)/2,m=-((n-1)*s)/2;let g=0;for(let M=0;M<n;M++)for(let w=0;w<e;w++,g++){const y=m+M*s,x=p+w*i;for(let b=0;b<l;b++){const E=(g*l+b)*3;u[E]=r.getX(b)+y,u[E+1]=r.getY(b),u[E+2]=r.getZ(b)+x,d[E]=a.getX(b),d[E+1]=a.getY(b),d[E+2]=a.getZ(b)}for(let b=0;b<c.count;b++)f[g*c.count+b]=c.getX(b)+g*l}const v=new be;return v.setAttribute("position",new pe(u,3)),v.setAttribute("normal",new pe(d,3)),v.setIndex(new wy(f,1)),v}static fitTerrace(t,e,i){const n=dt.sizeOf(e),s=n.widthM/2,r=n.lengthM/2,a=i(0,0)+n.heightM,c=Math.min(16,Math.max(1,Math.ceil(n.lengthM/3))),l=dt.bodyOf(t).children.filter(y=>y.isMesh);if(l.length<2)return a;const h=Math.min(10,n.widthM/4),u=[-s];for(const y of[.25,.5,.75,1])u.push(-s+h*y);const d=Math.max(1,Math.ceil((n.widthM-2*h)/3));for(let y=1;y<d;y++)u.push(-s+h+(n.widthM-2*h)*y/d);for(const y of[1,.75,.5,.25,0])u.push(s-h*y);const f=y=>-r+n.lengthM*y/c,p=.8,m=(y,x)=>{const b=Math.min(1,Math.max(0,(s-Math.abs(y))/h)),E=b*b*(3-2*b);return E*a+(1-E)*Math.min(a,i(y,x))},g=[],v=(y,x)=>{const b=i(y[0],y[1])-p,E=i(x[0],x[1])-p,S=Math.max(m(y[0],y[1]),b),A=Math.max(m(x[0],x[1]),E);g.push(y[0],b,y[1],x[0],E,x[1],y[0],S,y[1]),g.push(x[0],E,x[1],x[0],A,x[1],y[0],S,y[1])};for(let y=0;y<u.length-1;y++)v([u[y],-r],[u[y+1],-r]),v([u[y],r],[u[y+1],r]);const M=[];for(let y=0;y<u.length-1;y++)for(let x=0;x<c;x++){const b=[u[y],f(x)],E=[u[y+1],f(x)],S=[u[y],f(x+1)],A=[u[y+1],f(x+1)];for(const[_,I,D]of[[b,S,E],[E,S,A]])for(const O of[_,I,D])M.push(O[0],m(O[0],O[1]),O[1])}const w=(y,x)=>{const b=new be;b.setAttribute("position",new pe(x,3)),b.computeVertexNormals(),y.geometry.dispose(),y.geometry=b,y.position.y=0};return w(l[0],g),w(l[1],M),a}static fitCropToGround(t,e){t.updateMatrixWorld(!0);const i=new T;t.traverse(n=>{const s=n,r=s.userData.cropBasePositions,a=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!a)return;const c=s.geometry.getAttribute("position"),l=new Gt().copy(s.matrixWorld).invert();for(let h=0;h<c.count;h+=a){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(s.matrixWorld),i.y=e(i.x,i.z),i.applyMatrix4(l);for(let u=h;u<h+a;u++)c.setY(u,r[u*3+1]+i.y)}c.needsUpdate=!0,s.geometry.computeBoundingBox(),s.geometry.computeBoundingSphere()})}static applyModelParameters(t,e,i){if(!(!e||!i))for(const[n,s]of Object.entries(i)){const r=e[n];if("materials"in s)typeof r=="string"&&dt.tint(t,s.materials,r);else if(typeof r=="boolean"){const a=s.nodes.map(l=>new RegExp(l)),c=r===(s.hideWhen??!0);t.traverse(l=>{a.some(h=>h.test(l.name))&&(l.visible=!c)})}}}static tint(t,e,i){const n=e.map(s=>new RegExp(s));t.traverse(s=>{const r=s;if(!r.isMesh)return;const a=r.userData.tintedMaterials??[],c=l=>{if(!l.color||!n.some(f=>f.test(l.name)))return l;const u=l.clone();u.color.set(i);const d=u.emissive?Math.max(u.emissive.r,u.emissive.g,u.emissive.b):0;return d>0&&(u.emissive.multiply(u.color),u.emissive.multiplyScalar(d/(Math.max(u.emissive.r,u.emissive.g,u.emissive.b)||1))),a.push(u),u};r.material=Array.isArray(r.material)?r.material.map(c):c(r.material),a.length>0&&(r.userData.tintedMaterials=a)})}static paint(t,e){t.traverse(i=>{const n=i,s=n.userData;if(!n.isMesh||s?.emissive)return;const r=n.material;r?.color&&r.color.set(e)})}static addRoof(t,e){const i=Pi.normalised(e.roof),n=dt.sizeOf(e),s=e.sizeM?.heightM===void 0?n.heightM:dt.wallHeightOf(e,n.heightM),r=dt.roofColor(i.color),a=Pi.build(i,n.widthM,n.lengthM);e.roof.material==="stone"&&yr.layOn(a);const c=ti(t,a,r,s),l=c.material;l.side=Tn,e.roof.material==="stone"&&(l.map=yr.texture(),l.bumpMap=l.map,l.bumpScale=dt.STONE_BUMP),c.name=dt.ROOF_NAME}static wallHeightOf(t,e){return Math.min(e,Math.max(Ma,e-(t.roof?Pi.normalised(t.roof).riseM:0)))}static roofColor(t){const e=/^#([0-9a-f]{6})$/i.exec(t??"")?.[1];if(!e)return[.45,.25,.2];const i=new rt(`#${e}`);return[i.r,i.g,i.b]}static ROOF_NAME="decor-roof";static STONE_BUMP=2;static PLASTER="#d3cab8";static hasFacade(t){return t.kind==="building"&&dt.facadeOf(t)!==void 0&&!t.observerSide&&t.sizeM?.widthM!==void 0&&t.sizeM.lengthM!==void 0&&t.sizeM.heightM!==void 0}static facadeOf(t){if(t.kind!=="building"||t.facade?.openings==="none")return;if(t.facade)return t.facade;const e=t.sizeM?.heightM;return e===void 0?void 0:e-(t.roof?Pi.normalised(t.roof).riseM:0)>=Ma?dt.HOUSE_FACADE:void 0}static isBare(t){return t.openings==="plain"||t.plain===!0}static HOUSE_FACADE={};static buildFacade(t){const e=new Ke,i=dt.sizeOf(t),n=dt.facadeOf(t),s=n.openings==="tall"||n.openings==="lancet"?n.openings:void 0,r=Ad.build(i.widthM,i.lengthM,dt.wallHeightOf(t,i.heightM),!dt.isBare(n),t.eastM*7.31+t.northM*3.17,s,n.storeyM);if(n.closedAtNight){const l=r.getAttribute("litRank");for(let h=0;h<l.count;h++)l.setX(h,l.getX(h)/dt.CLOSED_AT_NIGHT_SHARE)}const a=new Rr({color:new rt(n.color??dt.PLASTER),map:Ot.texture(),emissiveMap:Ot.emissive(),emissive:new rt(1,1,1)});a.onBeforeCompile=l=>{l.uniforms.uLitShare=dt.litWindowShare,l.uniforms.uWindowLuminance=dt.windowLuminance,l.vertexShader=`attribute float litRank;
|
|
8946
8957
|
varying float vLitRank;
|
|
8947
8958
|
${l.vertexShader.replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
8948
8959
|
vLitRank = litRank;`)}`,l.fragmentShader=`uniform float uLitShare;
|
|
@@ -9002,7 +9013,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
9002
9013
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
9003
9014
|
}
|
|
9004
9015
|
`,transparent:!0,depthWrite:!1,side:Tn,fog:!1,blending:Ml,blendSrc:yl,blendDst:af})}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 Bt.respond(e*Bt.relativeOfResponse(Math.max(t,1e-5)))}}class ks{static SIZE=64;static MOVE_M=.01;holder=new Bi;cameras=[];faces=[];target=new Qe(ks.SIZE,ks.SIZE);white=new Is({color:new rt(1,1,1),side:Tn});scene=new hr;cabin;meshes=0;eye=new T;scratch=new T;constructor(){const t=[[new T(1,0,0),new T(0,1,0)],[new T(-1,0,0),new T(0,1,0)],[new T(0,1,0),new T(0,0,1)],[new T(0,-1,0),new T(0,0,-1)],[new T(0,0,1),new T(0,1,0)],[new T(0,0,-1),new T(0,1,0)]];for(const[e,i]of t){const n=new jn(90,1,.02,20);n.up.copy(i),n.lookAt(e),this.holder.add(n),this.cameras.push(n),this.faces.push(new Uint8Array(ks.SIZE*ks.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)<ks.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(ks.SIZE-1,Math.floor((s+1)/2*ks.SIZE)),c=Math.min(ks.SIZE-1,Math.floor((r+1)/2*ks.SIZE));return this.faces[e][(c*ks.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 xo))return;const l=new yt(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,ks.SIZE,ks.SIZE,this.faces[r])}t.setRenderTarget(n),t.shadowMap.autoUpdate=s;for(const r of i)r.removeFromParent()}}const c1="https://ufoathome.org/models/index.json";class _d{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??wL()}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(`
|
|
9005
|
-
`);let e=_d.shared.get(t);return e||(e=this.fetchFirstAvailable(),_d.shared.set(t,e),e.then(i=>{i.length===0&&_d.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 wL(){const o=`?v=${encodeURIComponent("0.
|
|
9016
|
+
`);let e=_d.shared.get(t);return e||(e=this.fetchFirstAvailable(),_d.shared.set(t,e),e.then(i=>{i.length===0&&_d.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 wL(){const o=`?v=${encodeURIComponent("0.179.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==c1?[t,c1]:[c1]).map(e=>e+o)}const xL=Re.point("decorModels").provide(Re.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 _d}]);class S3{constructor(t,e=xL){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=Re.point("decorModels");for(const i of this.sources){const n=e.ownerOf(i.id);if(!(n===void 0||n===Re.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return n}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function l1(o){const{GLTFLoader:t}=await at(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-VIIHsteW.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)}`)))})}class sr{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new yt(new vs(2,2),new De({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:sr.VERTEX,fragmentShader:sr.FRAGMENT,transparent:!0,depthWrite:!1,blending:Cn,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*sr.MIN_ANGLE_RAD),r=sr.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(sr.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(sr.MAX_SHARE*sr.FILL*Math.PI))}static VERTEX=`
|
|
9006
9017
|
uniform float uRadius;
|
|
9007
9018
|
varying vec2 vOffset;
|
|
9008
9019
|
void main() {
|
|
@@ -9093,7 +9104,7 @@ float litFromWithin() {
|
|
|
9093
9104
|
float d2 = max(dot(toLight, toLight), 1e-6);
|
|
9094
9105
|
float incidence = abs(dot(normalize(vLitNormal), toLight)) * inversesqrt(d2);
|
|
9095
9106
|
return min(incidence / d2 / ${r(e.mean)}, ${r(Td.MOST)});
|
|
9096
|
-
}`).replace("vec3 totalEmissiveRadiance = emissive;","vec3 totalEmissiveRadiance = emissive * litFromWithin();")},t.customProgramCacheKey=()=>`litFromWithin:${i},${n},${s},${e.mean}`,t.needsUpdate=!0}}class Ra{constructor(t){this.kind=t;const e=new be;this.positions=new Float32Array(t.count*3),this.sizes=new Float32Array(t.count),this.alphas=new Float32Array(t.count),e.setAttribute("position",new
|
|
9107
|
+
}`).replace("vec3 totalEmissiveRadiance = emissive;","vec3 totalEmissiveRadiance = emissive * litFromWithin();")},t.customProgramCacheKey=()=>`litFromWithin:${i},${n},${s},${e.mean}`,t.needsUpdate=!0}}class Ra{constructor(t){this.kind=t;const e=new be;this.positions=new Float32Array(t.count*3),this.sizes=new Float32Array(t.count),this.alphas=new Float32Array(t.count),e.setAttribute("position",new we(this.positions,3)),e.setAttribute("size",new we(this.sizes,1)),e.setAttribute("alpha",new we(this.alphas,1)),this.seeds=Array.from({length:t.count},(s,r)=>[Ra.hash(r*3+1)*2*Math.PI,.5+Ra.hash(r*3+2),.6+.8*Ra.hash(r*3+3)]);const i=new De({uniforms:{uColour:{value:new rt(t.colour[0],t.colour[1],t.colour[2])},uLight:{value:new rt(1,1,1)},uHalfHeight:{value:500}},vertexShader:Ra.VERTEX,fragmentShader:Ra.FRAGMENT,transparent:!0,depthWrite:!1,blending:Mc,toneMapped:!1});this.points=new ir(e,i),this.points.frustumCulled=!1,this.points.renderOrder=3,this.points.visible=!1;const n=new tt;this.points.onBeforeRender=s=>{const r=s.getRenderTarget();this.points.material.uniforms.uHalfHeight.value=(r?r.height:s.getDrawingBufferSize(n).y)/2}}static DUST={count:160,lifeS:2.2,startRadiusM:.4,spreadMS:2.5,riseMS:.8,birthSizeM:.5,deathSizeM:2.2,colour:[.52,.44,.33],opacity:.35};static SMOKE={count:60,lifeS:7,startRadiusM:.1,spreadMS:.15,riseMS:.7,birthSizeM:.6,deathSizeM:3.5,colour:[.42,.42,.42],opacity:.18};points;positions;sizes;alphas;seeds;set(t,e,i,n,s,r,a=[1,1,1]){const c=this.kind;if(this.points.visible=r>0,!this.points.visible)return;this.points.material.uniforms.uLight.value.setRGB(a[0],a[1],a[2]);for(let h=0;h<c.count;h++){const[u,d,f]=this.seeds[h],p=((n+h/c.count*c.lifeS)%c.lifeS+c.lifeS)%c.lifeS,m=p/c.lifeS,g=c.startRadiusM+c.spreadMS*d*Math.sqrt(p);this.positions[h*3]=t+Math.cos(u)*g+s.x*p,this.positions[h*3+1]=e+c.riseMS*f*p,this.positions[h*3+2]=i+Math.sin(u)*g+s.z*p,this.sizes[h]=c.birthSizeM+(c.deathSizeM-c.birthSizeM)*m,this.alphas[h]=c.opacity*r*Math.min(1,m*8)*(1-m)}const l=this.points.geometry;l.getAttribute("position").needsUpdate=!0,l.getAttribute("size").needsUpdate=!0,l.getAttribute("alpha").needsUpdate=!0}dispose(){this.points.geometry.dispose(),this.points.material.dispose()}static hash(t){const e=Math.sin(t*12.9898)*43758.5453;return e-Math.floor(e)}static VERTEX=`
|
|
9097
9108
|
attribute float size;
|
|
9098
9109
|
attribute float alpha;
|
|
9099
9110
|
uniform float uHalfHeight;
|
|
@@ -9116,7 +9127,7 @@ float litFromWithin() {
|
|
|
9116
9127
|
if (d2 > 1.0) discard;
|
|
9117
9128
|
gl_FragColor = vec4(uColour * uLight, vAlpha * exp(-3.0 * d2));
|
|
9118
9129
|
}
|
|
9119
|
-
`}class Gs{static shown(t,e,i){const n=i?i([1,1,1],e):Gs.withoutPhotometry([1,1,1],e);if(i?.recorded){const h=Gs.luminanceOf(n),u=Math.max(t[0],t[1],t[2])||1;return[t[0]/u*h,t[1]/u*h,t[2]/u*h]}const s=Bt.fromLightness(Bt.respond(Gs.luminanceOf(n))),r=Math.max(t[0],t[1],t[2])||1,a=[t[0]/r,t[1]/r,t[2]/r],c=Gs.luminanceOf(a);if(!(c>0)||!(s>0))return[0,0,0];const l=Bt.relativeOfResponse(Bt.lightnessOf(c*s))/c;return[a[0]*l,a[1]*l,a[2]*l]}static response(t){return Bt.respond(Gs.luminanceOf(t))}static withoutPhotometry(t,e){const i=Bt.relativeOfResponse(e/(e+1e4));return[t[0]*i,t[1]*i,t[2]*i]}static luminanceOf(t){return .2126*t[0]+.7152*t[1]+.0722*t[2]}}function E3(o){const t=new Map,e=new Map,i=o.clone();return A3(o,i,function(n,s){t.set(s,n),e.set(n,s)}),i.traverse(function(n){if(!n.isSkinnedMesh)return;const s=n,r=t.get(n),a=r.skeleton.bones;s.skeleton=r.skeleton.clone(),s.bindMatrix.copy(r.bindMatrix),s.skeleton.bones=a.map(function(c){return e.get(c)}),s.bind(s.skeleton,s.bindMatrix)}),i}function A3(o,t,e){e(o,t);for(let i=0;i<o.children.length;i++)A3(o.children[i],t.children[i],e)}const qu=Math.PI/180,_3=4;class oe{constructor(t,e,i=()=>0,n=()=>{}){this.loadModel=t,this.onModelArrived=e,this.sceneUnitsPerLux=i,this.emit=n,this.group.name="bodies"}group=new Ke;built=new Map;token=0;credits=new Map;flames=new Map;glares=new Map;lightVeils=new Map;lightRay=new l0;boxHit=new T;dust=new Map;smoke=[];scratch=new T;aim=new es;down=new T;frame;lastSet;models=new Map;async modelFor(t){const e=JSON.stringify(t);let i=this.models.get(e);i||(i=this.loadModel(t),this.models.set(e,i),i.then(r=>{r||this.models.delete(e)},()=>this.models.delete(e)));const n=await i;if(!n)return;const s=E3(n.scene);return s.traverse(r=>{r instanceof yt&&(r.material=Array.isArray(r.material)?r.material.map(a=>a.clone()):r.material.clone(),r.userData.sharedGeometry=!0)}),{...n,scene:s}}get modelCredits(){return[...this.credits.values()]}set(t,e,i=0,n,s=t.map(r=>r.id)){this.frame=e,this.lastSet=[t,e,i,n,s],this.pointLights.clear(),this.shapeShares.clear(),this.metered.clear();const r=new Set,a=[];for(const l of t){const h=l.flicker?oe.flickered(l,i):l;r.add(h.id);const u=oe.signatureOf(h);let d=this.built.get(h.id);(!d||d.signature!==u)&&(d&&this.remove(h.id),d=this.build(h),this.built.set(h.id,d),this.group.add(d.holder));const{holder:f,material:p,glowing:m,whole:g}=d;f.visible=!0,f.position.set(e.originX+h.eastM,e.originGroundY+h.upM,e.originZ-h.northM),f.rotation.set(h.attitude.pitchDeg*qu,-h.attitude.headingDeg*qu,-h.attitude.rollDeg*qu,"YXZ"),f.scale.set(h.sizeM.widthM,h.sizeM.heightM,h.sizeM.lengthM),p&&oe.paint(p,h,n),oe.fade(f,h.appearance.transparency),m&&oe.light(m,h,n),h.turns&&oe.unturn(d,f,h.turns),d.motions&&oe.move(d.motions,h.motions??{}),h.turns&&oe.turn(d,h.turns),this.shine(h,f,g?void 0:m,e),g&&m&&this.hideSpecks(f,m,e);const v=this.shapeShares.get(h.id)??1;for(const w of f.children)w.visible=v>0;v<1&&oe.fade(f,1-(1-h.appearance.transparency)*v);const M=this.metered.get(h.id);M&&h!==l&&h.appearance.luminanceCdM2>0&&(M.luminanceCdM2*=l.appearance.luminanceCdM2/h.appearance.luminanceCdM2),this.shineLights(h,f,g?void 0:m,e,a),this.throwFlame(h,f,i,n,e.eye,a),h.appearance.luminanceCdM2>0&&(g||!m?.length)&&a.push({position:f.position,candela:h.appearance.luminanceCdM2*(1-h.appearance.transparency)*h.sizeM.widthM*h.sizeM.heightM,colour:oe.rgbOf(h.appearance.color)})}this.emit(a);const c=new Set(s);for(const[l,{holder:h}]of[...this.built])r.has(l)||(c.has(l)?(h.visible=!1,this.flames.get(l)?.putOut(),this.glares.get(l)?.hide(),this.hideLights(l)):this.remove(l));this.drawPoints()}pointLights=new Map;shapeShares=new Map;static SHAPE_FROM_PIXELS=1.5;static SHAPE_FULL_PIXELS=3;metered=new Map;get pointSources(){return this.points??[]}points;drawPoints(){if(this.pointLights.size===0&&!this.points)return;this.points??=iu.map(i=>{const n=new ir(new be,Vt.material(i.size,!1));return Vt.track(n),n.frustumCulled=!1,n.name="body-points",this.group.add(n),n});const t=this.sceneUnitsPerLux(),e=this.points.map(()=>[]);for(const i of this.pointLights.values()){const n=Math.max(...i.light)/(t||1),s=n>0?-14.18-2.5*Math.log10(n):1/0;e[Math.max(0,Py(Ch(s)))].push(i)}this.points.forEach((i,n)=>{const s=e[n],r=new Float32Array(s.length*3),a=new Float32Array(s.length*3);s.forEach((l,h)=>{r.set([l.position.x,l.position.y,l.position.z],h*3),a.set(l.light,h*3)}),i.geometry.dispose();const c=new be;c.setAttribute("position",new ye(r,3)),c.setAttribute("color",new ye(a,3)),i.geometry=c})}shine(t,e,i,n){const s=n.eye,r=t.appearance.luminanceCdM2;let a=this.glares.get(t.id);if(!(r>0)||!s||i&&i.length>0){a?.hide();return}a||(a=new An(`body-veil:${t.id}`,An.OVER_EVERYTHING),this.glares.set(t.id,a),this.group.add(a.mesh));const c=this.apparentRadiusM(t,e,s),l=Math.max(e.position.distanceTo(s),c*1.01),h=Math.asin(c/l);let u=this.reliefClearShare(s,e.position,c);if(u>0&&n.occluders&&n.occluders.length>0&&(u*=this.decorClearShare(e,s,n.occluders)),u<=0){a.hide();return}const d=2*Math.PI*(1-Math.cos(h))*u,f=i?.find(x=>x.share>=1)?.hue??oe.rgbOf(t.appearance.color),p=r*d*this.sceneUnitsPerLux(),m=Math.max(...f)||1,g=this.throughAir([f[0]/m*p,f[1]/m*p,f[2]/m*p],e.position),v=1-t.appearance.transparency,M=t.appearance.haloScale;if(!(v>0)||!(M>0)){a.hide();return}a.shine(e.position,[g[0]*v,g[1]*v,g[2]*v],h*180/Math.PI*M),this.metered.set(t.id,{position:e.position.clone(),luminanceCdM2:r*v,solidAngleSr:d});const w=n.pixelRad!==void 0?2*h/n.pixelRad:1/0,y=Math.min(1,Math.max(0,(w-oe.SHAPE_FROM_PIXELS)/(oe.SHAPE_FULL_PIXELS-oe.SHAPE_FROM_PIXELS)));if(this.shapeShares.set(t.id,y),y<1){const x=v*(1-y);this.pointLights.set(t.id,{position:e.position.clone(),light:[g[0]*x,g[1]*x,g[2]*x]})}}static glaze(t){t.traverse(e=>{if(!(e instanceof yt))return;const i=e.material;!(i instanceof TI)||!(i.transmission>0)||(e.material=new xo(i.ior),i.dispose(),e.castShadow=!1)})}maskedShare(t,e){const i=this.built.get(t)?.holder,n=this.frame?.eye;if(!(!i||!n||!i.visible))return 1-this.decorClearShare(i,n,[e])}decorClearShare(t,e,i){t.updateMatrixWorld(!0);const n=new Je().setFromObject(t),s=[];t.traverse(a=>{a instanceof yt&&s.push(a)});const r=[...i].map(a=>({object:a,box:new Je().setFromObject(a)}));return this.clearShare(e,n,n.getCenter(new T),s,r)}apparentRadiusM(t,e,i){const n=t.sizeM.widthM/2,s=t.sizeM.heightM/2,r=t.sizeM.lengthM/2,a=this.scratch.subVectors(i,e.position),c=a.length()>0?a.applyQuaternion(e.quaternion.clone().invert()).normalize():a.set(0,0,1),l=Math.sqrt((s*r*c.x)**2+(n*r*c.y)**2+(n*s*c.z)**2);return Math.max(Math.sqrt(l),1e-6)}reliefClearShare(t,e,i){const n=this.frame?.groundYAt;if(!n)return 1;let s=0;const r=[e,new T(e.x,e.y+i,e.z),new T(e.x,e.y-i,e.z)];for(const a of r){const c=a.distanceTo(t),l=Math.max(8,Math.min(200,Math.ceil(c/25)));let h=!1;for(let u=1;u<l&&!h;u++){const d=u/l,f=t.x+(a.x-t.x)*d,p=t.z+(a.z-t.z)*d;h=n(f,p)>t.y+(a.y-t.y)*d+.5}h||s++}return s/r.length}throughAir(t,e){const i=this.frame?.transmittance?.(e.x,e.y,e.z)??[1,1,1];return[t[0]*i[0],t[1]*i[1],t[2]*i[2]]}static rgbOf(t){const e=new rt(t);return[e.r,e.g,e.b]}throwFlame(t,e,i,n,s,r){let a=this.flames.get(t.id);if(!a&&t.throwsFlame&&(a=new ol,this.flames.set(t.id,a),this.group.add(a.mesh,a.glow)),!a)return;const c=t.flame;if(!c){a.putOut(),this.dust.get(t.id)?.set(0,0,0,i,{x:0,z:0},0);return}e.updateMatrixWorld(!0);const l=e.getObjectByName(c.node??oe.EXHAUST_NODE);l?l.getWorldPosition(this.scratch):e.localToWorld(this.scratch.set(0,-.5,0)),a.place(this.scratch,l?oe.pointing(l,this.down,this.aim):e.quaternion,c.lengthM,c.widthM);const h=f=>{const p=new rt(f);return this.throughAir(oe.shown([p.r,p.g,p.b],c.luminanceCdM2,n),this.scratch)};a.set(h(c.color),h(c.tipColor??c.color),i),r.push({position:a.lightAt(new T),candela:oe.luminousIntensityCd(c),colour:oe.lightColourOf(c)});const u=ol.glowFor(c,s?a.mesh.position.distanceTo(s):0),d=new rt(c.color).lerp(new rt(c.tipColor??c.color),.5);a.shine(u.radiusM,this.throughAir(oe.shown([d.r,d.g,d.b],u.luminanceCdM2,n),this.scratch)),this.raiseDust(t.id,c,i)}raiseDust(t,e,i){const n=this.frame;if(!e.raisesDust||!n?.groundYAt){this.dust.get(t)?.set(0,0,0,i,{x:0,z:0},0);return}let s=this.dust.get(t);s||(s=new Ra(Ra.DUST),this.dust.set(t,s),this.group.add(s.points));const{x:r,y:a,z:c}=this.scratch,l=n.groundYAt(r,c),h=Math.max(0,Math.min(1,1-(a-l)/(e.lengthM+1)));s.set(r,l,c,i,n.wind??{x:0,z:0},h,n.light)}setSmoke(t,e){const i=this.frame;for(;this.smoke.length<t.length;){const n=new Ra(Ra.SMOKE);this.smoke.push(n),this.group.add(n.points)}this.smoke.forEach((n,s)=>{const r=t[s],a=e*1e3;if(!(r!==void 0&&i!==void 0&&a>=r.fromT&&(r.untilT===void 0||a<r.untilT))){n.set(0,0,0,e,{x:0,z:0},0);return}const l=i.originX+r.eastM,h=i.originZ-r.northM,u=(a-r.fromT)/1e3,d=Math.min(1,u/2)*(.1+.9*Math.pow(2,-u/(r.halfLifeS??20)));n.set(l,i.groundYAt?i.groundYAt(l,h):i.originGroundY,h,e,i.wind??{x:0,z:0},d,i.light)})}static luminousIntensityCd(t){return t.luminanceCdM2*.7*t.widthM*t.lengthM}static lightColourOf(t){const e=new rt(t.color),i=new rt(t.tipColor??t.color),n=[(e.r+i.r)/2,(e.g+i.g)/2,(e.b+i.b)/2],s=.2126*n[0]+.7152*n[1]+.0722*n[2];return s>0?[n[0]/s,n[1]/s,n[2]/s]:[1,1,1]}static pointing(t,e,i){return e.set(0,-1,0).transformDirection(t.matrixWorld).normalize(),i.setFromUnitVectors(oe.DOWN,e)}static DOWN=new T(0,-1,0);static SPECK_PIXELS=2;hideSpecks(t,e,i){const n=i.eye;t.updateMatrixWorld(!0);const s=new Je().setFromObject(t).getSize(new T),r=Math.max(s.x,s.y,s.z);for(const a of e){const c=new Je;for(const f of a.meshes)c.expandByObject(f);const l=c.getSize(new T),h=Math.max(l.x,l.y,l.z);if(h>=r/4)continue;const u=n?c.getCenter(new T).distanceTo(n):0,d=i.pixelRad===void 0||u<=0||h/u>=oe.SPECK_PIXELS*i.pixelRad;for(const f of a.meshes)f.visible=d}}static flickered(t,e){let i=0;for(let c=0;c<t.id.length;c++)i=Math.imul(i,31)+t.id.charCodeAt(c)>>>0;const n=c=>(Math.imul(i^c,2654435761)>>>0)/4294967296*2*Math.PI,s=(Math.sin(2*Math.PI*2.3*e+n(1))+Math.sin(2*Math.PI*5.1*e+n(2))+Math.sin(2*Math.PI*8.7*e+n(3)))/3,r=Math.max(0,1+t.flicker*s),a=t.lights?Object.fromEntries(Object.entries(t.lights).map(([c,l])=>[c,l*r])):void 0;return{...t,appearance:{...t.appearance,luminanceCdM2:t.appearance.luminanceCdM2*r},lights:a}}static GLOWS_WHOLE="glowsWhole";static EXHAUST_NODE="exhaust";shineLights(t,e,i,n,s){const r=n.eye,a=t.lights;if(!i||!a||!r){this.hideLights(t.id);return}e.updateMatrixWorld(!0);let c;for(const l of i){const h=`${t.id}\0${l.name}`,u=a[l.name];let d=this.lightVeils.get(h);if(!(u>0)||l.meshes.length===0){d?.hide();continue}const f=new Je;for(const A of l.meshes)f.expandByObject(A);const p=f.getCenter(new T),m=f.getSize(new T),g=Math.max(m.x,m.y,m.z)/2;s.push({position:p.clone(),candela:u*Math.PI*g*g,colour:l.hue});const v=Math.max(p.distanceTo(r),g*1.01,.001);c??=[e,...n.occluders??[]].map(A=>({object:A,box:new Je().setFromObject(A)}));const M=this.clearShare(r,f,p,l.meshes,c);if(M<=0){d?.hide();continue}d||(d=new An(`body-light:${t.id}:${l.name}`,An.OVER_EVERYTHING),this.lightVeils.set(h,d),this.group.add(d.mesh));const w=Math.asin(Math.min(1,g/v)),y=2*Math.PI*(1-Math.cos(w))*M,x=u*y*this.sceneUnitsPerLux(),b=Math.max(...l.hue)||1,E=[l.hue[0]/b,l.hue[1]/b,l.hue[2]/b],S=this.throughAir([E[0]*x,E[1]*x,E[2]*x],p);d.shine(p,S,w*180/Math.PI)}}clearShare(t,e,i,n,s){const r=[i];for(const[l,h]of[[.2,.2],[.8,.2],[.2,.8],[.8,.8]])r.push(new T(e.min.x+(e.max.x-e.min.x)*l,i.y+(l<.5?-1:1)*(e.max.y-e.min.y)*.3,e.min.z+(e.max.z-e.min.z)*h));const a=new T;let c=0;for(const l of r){a.subVectors(l,t);const h=a.length();this.lightRay.set(t,a.normalize()),this.lightRay.far=h;const u=s.filter(({box:f})=>{const p=this.lightRay.ray.intersectBox(f,this.boxHit);return p!==null&&p.distanceTo(t)<h}).map(({object:f})=>f);u.length>0&&this.lightRay.intersectObjects(u,!0).some(f=>f.object instanceof yt&&!n.includes(f.object)&&!(f.object.material instanceof xo)&&f.distance<h-.05)||c++}return c/r.length}hideLights(t){const e=`${t}\0`;for(const[i,n]of this.lightVeils)i.startsWith(e)&&n.hide()}dropGlare(t){const e=this.glares.get(t);e&&(this.group.remove(e.mesh),e.dispose(),this.glares.delete(t))}dropFlame(t){const e=this.flames.get(t);if(!e)return;e.mesh.removeFromParent(),e.glow.removeFromParent(),e.dispose(),this.flames.delete(t);const i=this.dust.get(t);i&&(i.points.removeFromParent(),i.dispose(),this.dust.delete(t))}outlineOf(t,e){const i=this.built.get(t)?.holder,n=this.frame,s=i?.getObjectByName(e);if(!i||!n||!s)return;i.updateMatrixWorld(!0);const r=[];return s.traverse(a=>{if(!(a instanceof yt))return;const c=a.geometry.getAttribute("position"),l=Math.max(1,Math.floor(c.count/400));for(let h=0;h<c.count;h+=l)this.scratch.fromBufferAttribute(c,h).applyMatrix4(a.matrixWorld),r.push({eastM:this.scratch.x-n.originX,northM:n.originZ-this.scratch.z,upM:this.scratch.y-n.originGroundY})}),r.length>0?r:void 0}boxOf(t,e){const i=this.built.get(t)?.holder;return i?.visible?e.setFromObject(i):void 0}pick(t){return this.pickHit(t)?.id}pickHit(t){const e=[...this.built.entries()].filter(([,{holder:r}])=>r.visible),i=t.intersectObjects(e.map(([,{holder:r}])=>r),!0)[0];if(!i)return;let n=i.object;for(;n&&!e.some(([,{holder:r}])=>r===n);)n=n.parent;const s=e.find(([,{holder:r}])=>r===n)?.[0];return s===void 0?void 0:{id:s,distance:i.distance}}reachFrom(t){let e=0;for(const{holder:i}of this.built.values()){if(!i.visible)continue;const n=Math.hypot(i.position.x-t.x,i.position.z-t.z);e=Math.max(e,n+Math.max(i.scale.x,i.scale.y,i.scale.z)/2)}return e}furthestFrom(t){let e=0;for(const{holder:i}of this.built.values())i.visible&&(e=Math.max(e,i.position.distanceTo(t)));return e}get reflectors(){return[...this.built.entries()].filter(([,{holder:t}])=>t.visible).map(([t,{holder:e}])=>({id:t,holder:e,shiny:oe.isShiny(e)}))}static isShiny(t){let e=!1;return t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:[n])(s instanceof xo||s instanceof ec&&(s.roughness<oe.SHINY_ROUGHNESS||s.metalness>oe.SHINY_METALNESS))&&(e=!0)}),e}static SHINY_ROUGHNESS=.6;static SHINY_METALNESS=.3;static overlay(t){t.traverse(e=>e.layers.enable(_3))}get any(){return[...this.built.values()].some(({holder:t})=>t.visible)}clear(){this.token++;for(const t of[...this.built.keys()])this.remove(t);this.pointLights.clear();for(const t of this.points??[])t.geometry.dispose(),t.material.dispose(),t.removeFromParent();this.points=void 0}build(t){const e=new Ke;e.name=`body:${t.id}`;const i=oe.signatureOf(t),n=oe.primitiveOf(t.model);if(n==="figure"){const c=new ec({roughness:.7,metalness:0});oe.paint(c,t);const l=dt.build({id:t.id,kind:"entity",eastM:0,northM:0},!1);return l.traverse(h=>{h instanceof yt&&(h.material=c,h.castShadow=!0,h.receiveShadow=!0)}),e.add(oe.fit(l,0)),oe.overlay(e),{holder:e,signature:i,material:c}}if(n){const c=new ec({roughness:.45,metalness:0});oe.paint(c,t);const l=new yt(oe.unitGeometry(n),c);return l.castShadow=!0,l.receiveShadow=!0,e.add(l),oe.overlay(e),{holder:e,signature:i,material:c}}const s=new ec({roughness:.45,metalness:0});oe.paint(s,t);const r=new yt(oe.unitGeometry("ellipsoid"),s);r.castShadow=!0,r.receiveShadow=!0,e.add(r),oe.overlay(e);const a=this.token;return this.modelFor(t.model).then(c=>{if(!c||a!==this.token||this.built.get(t.id)?.holder!==e)return;e.remove(r),r.geometry.dispose(),s.dispose(),dt.applyModelParameters(c.scene,t.modelParameters,c.bindings),Td.apply(c.scene),oe.glaze(c.scene),e.add(oe.fit(c.scene,c.headingOffsetDeg??t.model.headingOffsetDeg??0)),oe.overlay(e),this.credits.set(t.id,c.credit);const l=this.built.get(t.id);l&&(l.material=void 0,l.glowing=oe.glowingOf(c.scene),l.whole=c.scene.userData[oe.GLOWS_WHOLE]===!0,l.motions=oe.motionsOf(c.scene),l.parts=void 0,l.loaded=!0),this.lastSet&&this.set(...this.lastSet),this.onModelArrived()}).catch(c=>console.warn(`Keeping the ellipsoid for body "${t.id}":`,c)),{holder:e,signature:i,material:s}}static fit(t,e){const i=new Ke;t.rotation.y=-e*qu,i.add(t),i.updateMatrixWorld(!0);const n=new Je().setFromObject(i),s=n.getSize(new T),r=n.getCenter(new T),a=new Ke;return i.position.sub(r),a.add(i),a.scale.set(1/Math.max(s.x,1e-6),1/Math.max(s.y,1e-6),1/Math.max(s.z,1e-6)),t.traverse(c=>{c instanceof yt&&(c.castShadow=!0,c.receiveShadow=!0)}),a}static paint(t,e,i){const n=new rt(e.appearance.color),s=.2126*n.r+.7152*n.g+.0722*n.b;s>0&&n.multiplyScalar(e.appearance.albedo/s),n.r=Math.min(1,n.r),n.g=Math.min(1,n.g),n.b=Math.min(1,n.b),t.color.equals(n)||t.color.copy(n);const r=new rt(e.appearance.color),a=Math.max(r.r,r.g,r.b);oe.glow(t,a>0?[r.r/a,r.g/a,r.b/a]:[1,1,1],e.appearance.luminanceCdM2,i)}static fade(t,e){const i=1-Math.min(1,Math.max(0,e));t.traverse(n=>{if(n instanceof yt)for(const s of Array.isArray(n.material)?n.material:[n.material]){if(!(s instanceof Ga))continue;const r=s.userData.bodyOpacity??={transparent:s.transparent,opacity:s.opacity,depthWrite:s.depthWrite},a=r.opacity*i,c=i<1;s.opacity===a&&s.transparent===(r.transparent||c)||(s.transparent=r.transparent||c,s.opacity=a,s.depthWrite=c?!1:r.depthWrite,s.needsUpdate=!0)}})}static light(t,e,i){for(const{material:n,hue:s,share:r,name:a}of t)oe.glow(n,s,e.lights?.[a]??e.appearance.luminanceCdM2*r,i)}static glow(t,e,i,n){if(!(i>0)){(t.emissive.r!==0||t.emissive.g!==0||t.emissive.b!==0)&&t.emissive.setRGB(0,0,0);return}const s=oe.shown(e,i,n);t.emissive.setRGB(s[0],s[1],s[2])}static motionsOf(t){if(t.animations.length===0)return;const e=new rD(t),i=new Map;for(const n of t.animations){const s=e.clipAction(n);s.setLoop(rA,1),s.clampWhenFinished=!0,s.play(),s.paused=!0,i.set(n.name,s)}return i}static unturn(t,e,i){t.parts??=new Map;for(const n of Object.keys(i)){if(!t.parts.has(n)){const r=e.getObjectByName(n);r?t.parts.set(n,{node:r,rest:r.quaternion.clone()}):t.loaded&&(t.parts.set(n,void 0),console.warn(`Body model has no part "${n}" to turn`))}const s=t.parts.get(n);s&&s.node.quaternion.copy(s.rest)}}static turn(t,e){for(const[i,n]of Object.entries(e)){const s=t.parts?.get(i);s&&s.node.quaternion.multiply(oe.TURN.setFromAxisAngle(oe.UP,-n*qu))}}static TURN=new es;static UP=new T(0,1,0);static move(t,e){let i;for(const[n,s]of t){const r=Math.max(0,e[n]??0),a=r-Math.floor(r),c=r>0&&a===0?1:a;s.time=c*s.getClip().duration,i=s.getMixer()}i?.update(0)}static shown(t,e,i){return Gs.shown(t,e,i)}static glowingOf(t){const e=[],i=new Map;t.traverse(r=>{if(r instanceof yt)for(const a of Array.isArray(r.material)?r.material:[r.material]){if(!(a instanceof ec))continue;const c=i.get(a);if(c){c.push(r);continue}i.set(a,[r]),Math.max(a.emissive.r,a.emissive.g,a.emissive.b)>0&&e.push(a)}});const n=r=>Math.max(r.emissive.r,r.emissive.g,r.emissive.b),s=Math.max(...e.map(n),0);return s<=0?[]:e.map(r=>({material:r,hue:[r.emissive.r,r.emissive.g,r.emissive.b],share:n(r)/s,name:r.name,meshes:i.get(r)??[]}))}static primitiveOf(t){return t.url===void 0&&gE.includes(t.id??"")?t.id:void 0}static signatureOf(t){return`${t.model.id??""}|${t.model.url??""}|${t.modelParameters?JSON.stringify(t.modelParameters):""}`}static unitGeometry(t){let e;switch(t){case"ellipsoid":case"sphere":e=new hn(.5,48,24);break;case"disc":{const r=[];for(let c=0;c<=24;c++){const l=.5*Math.sin(c/24*Math.PI),h=.5*Math.cos(c/24*Math.PI);r.push(new tt(l,Math.sign(h)*h*h*2))}e=new Om(r.reverse(),64);break}case"cylinder":e=new gs(.5,.5,1,48);break;case"cone":e=new bu(.5,1,48);break;case"box":e=new en(1,1,1);break;case"torus":e=new Ay(.35,.15,24,64),e.rotateX(Math.PI/2);break;case"figure":e=new hn(.5,24,12);break}e.computeBoundingBox();const i=e.boundingBox,n=i.getSize(new T),s=i.getCenter(new T);return e.translate(-s.x,-s.y,-s.z),e.scale(1/n.x,1/n.y,1/n.z),e.computeVertexNormals(),e}remove(t){const e=this.built.get(t);if(!e)return;e.holder.removeFromParent(),e.holder.traverse(n=>{if(!(n instanceof yt))return;n.userData.sharedGeometry||n.geometry.dispose();const s=Array.isArray(n.material)?n.material:[n.material];for(const r of s)r.dispose()}),this.built.delete(t),this.credits.delete(t),this.dropFlame(t),this.dropGlare(t);const i=`${t}\0`;for(const[n,s]of[...this.lightVeils])n.startsWith(i)&&(this.group.remove(s.mesh),s.dispose(),this.lightVeils.delete(n))}}const EM=2,bL=5,SL=2048;class Fr{constructor(t){this.scene=t}cloudLayers=[];cloudSignature="";setCloudLayers(t){const e=t.map(i=>i.mesh.uuid).join(",");if(e!==this.cloudSignature){this.cloudSignature=e,this.cloudLayers=t;for(const i of this.meshes.values())this.configureCloudMaterial(i.material)}}configureCloudMaterial(t){const e=this.cloudLayers,i=this.cloudSignature;t.customProgramCacheKey=()=>i,t.onBeforeCompile=n=>{if(!e.length)return;n.vertexShader=`varying vec3 cloudPoint;
|
|
9130
|
+
`}class Gs{static shown(t,e,i){const n=i?i([1,1,1],e):Gs.withoutPhotometry([1,1,1],e);if(i?.recorded){const h=Gs.luminanceOf(n),u=Math.max(t[0],t[1],t[2])||1;return[t[0]/u*h,t[1]/u*h,t[2]/u*h]}const s=Bt.fromLightness(Bt.respond(Gs.luminanceOf(n))),r=Math.max(t[0],t[1],t[2])||1,a=[t[0]/r,t[1]/r,t[2]/r],c=Gs.luminanceOf(a);if(!(c>0)||!(s>0))return[0,0,0];const l=Bt.relativeOfResponse(Bt.lightnessOf(c*s))/c;return[a[0]*l,a[1]*l,a[2]*l]}static response(t){return Bt.respond(Gs.luminanceOf(t))}static withoutPhotometry(t,e){const i=Bt.relativeOfResponse(e/(e+1e4));return[t[0]*i,t[1]*i,t[2]*i]}static luminanceOf(t){return .2126*t[0]+.7152*t[1]+.0722*t[2]}}function E3(o){const t=new Map,e=new Map,i=o.clone();return A3(o,i,function(n,s){t.set(s,n),e.set(n,s)}),i.traverse(function(n){if(!n.isSkinnedMesh)return;const s=n,r=t.get(n),a=r.skeleton.bones;s.skeleton=r.skeleton.clone(),s.bindMatrix.copy(r.bindMatrix),s.skeleton.bones=a.map(function(c){return e.get(c)}),s.bind(s.skeleton,s.bindMatrix)}),i}function A3(o,t,e){e(o,t);for(let i=0;i<o.children.length;i++)A3(o.children[i],t.children[i],e)}const qu=Math.PI/180,_3=4;class oe{constructor(t,e,i=()=>0,n=()=>{}){this.loadModel=t,this.onModelArrived=e,this.sceneUnitsPerLux=i,this.emit=n,this.group.name="bodies"}group=new Ke;built=new Map;token=0;credits=new Map;flames=new Map;glares=new Map;lightVeils=new Map;lightRay=new l0;boxHit=new T;dust=new Map;smoke=[];scratch=new T;aim=new es;down=new T;frame;lastSet;models=new Map;async modelFor(t){const e=JSON.stringify(t);let i=this.models.get(e);i||(i=this.loadModel(t),this.models.set(e,i),i.then(r=>{r||this.models.delete(e)},()=>this.models.delete(e)));const n=await i;if(!n)return;const s=E3(n.scene);return s.traverse(r=>{r instanceof yt&&(r.material=Array.isArray(r.material)?r.material.map(a=>a.clone()):r.material.clone(),r.userData.sharedGeometry=!0)}),{...n,scene:s}}get modelCredits(){return[...this.credits.values()]}set(t,e,i=0,n,s=t.map(r=>r.id)){this.frame=e,this.lastSet=[t,e,i,n,s],this.pointLights.clear(),this.shapeShares.clear(),this.metered.clear();const r=new Set,a=[];for(const l of t){const h=l.flicker?oe.flickered(l,i):l;r.add(h.id);const u=oe.signatureOf(h);let d=this.built.get(h.id);(!d||d.signature!==u)&&(d&&this.remove(h.id),d=this.build(h),this.built.set(h.id,d),this.group.add(d.holder));const{holder:f,material:p,glowing:m,whole:g}=d;f.visible=!0,f.position.set(e.originX+h.eastM,e.originGroundY+h.upM,e.originZ-h.northM),f.rotation.set(h.attitude.pitchDeg*qu,-h.attitude.headingDeg*qu,-h.attitude.rollDeg*qu,"YXZ"),f.scale.set(h.sizeM.widthM,h.sizeM.heightM,h.sizeM.lengthM),p&&oe.paint(p,h,n),oe.fade(f,h.appearance.transparency),m&&oe.light(m,h,n),h.turns&&oe.unturn(d,f,h.turns),d.motions&&oe.move(d.motions,h.motions??{}),h.turns&&oe.turn(d,h.turns),this.shine(h,f,g?void 0:m,e),g&&m&&this.hideSpecks(f,m,e);const v=this.shapeShares.get(h.id)??1;for(const w of f.children)w.visible=v>0;v<1&&oe.fade(f,1-(1-h.appearance.transparency)*v);const M=this.metered.get(h.id);M&&h!==l&&h.appearance.luminanceCdM2>0&&(M.luminanceCdM2*=l.appearance.luminanceCdM2/h.appearance.luminanceCdM2),this.shineLights(h,f,g?void 0:m,e,a),this.throwFlame(h,f,i,n,e.eye,a),h.appearance.luminanceCdM2>0&&(g||!m?.length)&&a.push({position:f.position,candela:h.appearance.luminanceCdM2*(1-h.appearance.transparency)*h.sizeM.widthM*h.sizeM.heightM,colour:oe.rgbOf(h.appearance.color)})}this.emit(a);const c=new Set(s);for(const[l,{holder:h}]of[...this.built])r.has(l)||(c.has(l)?(h.visible=!1,this.flames.get(l)?.putOut(),this.glares.get(l)?.hide(),this.hideLights(l)):this.remove(l));this.drawPoints()}pointLights=new Map;shapeShares=new Map;static SHAPE_FROM_PIXELS=1.5;static SHAPE_FULL_PIXELS=3;metered=new Map;get pointSources(){return this.points??[]}points;drawPoints(){if(this.pointLights.size===0&&!this.points)return;this.points??=iu.map(i=>{const n=new ir(new be,Vt.material(i.size,!1));return Vt.track(n),n.frustumCulled=!1,n.name="body-points",this.group.add(n),n});const t=this.sceneUnitsPerLux(),e=this.points.map(()=>[]);for(const i of this.pointLights.values()){const n=Math.max(...i.light)/(t||1),s=n>0?-14.18-2.5*Math.log10(n):1/0;e[Math.max(0,Py(Ch(s)))].push(i)}this.points.forEach((i,n)=>{const s=e[n],r=new Float32Array(s.length*3),a=new Float32Array(s.length*3);s.forEach((l,h)=>{r.set([l.position.x,l.position.y,l.position.z],h*3),a.set(l.light,h*3)}),i.geometry.dispose();const c=new be;c.setAttribute("position",new we(r,3)),c.setAttribute("color",new we(a,3)),i.geometry=c})}shine(t,e,i,n){const s=n.eye,r=t.appearance.luminanceCdM2;let a=this.glares.get(t.id);if(!(r>0)||!s||i&&i.length>0){a?.hide();return}a||(a=new An(`body-veil:${t.id}`,An.OVER_EVERYTHING),this.glares.set(t.id,a),this.group.add(a.mesh));const c=this.apparentRadiusM(t,e,s),l=Math.max(e.position.distanceTo(s),c*1.01),h=Math.asin(c/l);let u=this.reliefClearShare(s,e.position,c);if(u>0&&n.occluders&&n.occluders.length>0&&(u*=this.decorClearShare(e,s,n.occluders)),u<=0){a.hide();return}const d=2*Math.PI*(1-Math.cos(h))*u,f=i?.find(x=>x.share>=1)?.hue??oe.rgbOf(t.appearance.color),p=r*d*this.sceneUnitsPerLux(),m=Math.max(...f)||1,g=this.throughAir([f[0]/m*p,f[1]/m*p,f[2]/m*p],e.position),v=1-t.appearance.transparency,M=t.appearance.haloScale;if(!(v>0)||!(M>0)){a.hide();return}a.shine(e.position,[g[0]*v,g[1]*v,g[2]*v],h*180/Math.PI*M),this.metered.set(t.id,{position:e.position.clone(),luminanceCdM2:r*v,solidAngleSr:d});const w=n.pixelRad!==void 0?2*h/n.pixelRad:1/0,y=Math.min(1,Math.max(0,(w-oe.SHAPE_FROM_PIXELS)/(oe.SHAPE_FULL_PIXELS-oe.SHAPE_FROM_PIXELS)));if(this.shapeShares.set(t.id,y),y<1){const x=v*(1-y);this.pointLights.set(t.id,{position:e.position.clone(),light:[g[0]*x,g[1]*x,g[2]*x]})}}static glaze(t){t.traverse(e=>{if(!(e instanceof yt))return;const i=e.material;!(i instanceof TI)||!(i.transmission>0)||(e.material=new xo(i.ior),i.dispose(),e.castShadow=!1)})}maskedShare(t,e){const i=this.built.get(t)?.holder,n=this.frame?.eye;if(!(!i||!n||!i.visible))return 1-this.decorClearShare(i,n,[e])}decorClearShare(t,e,i){t.updateMatrixWorld(!0);const n=new Je().setFromObject(t),s=[];t.traverse(a=>{a instanceof yt&&s.push(a)});const r=[...i].map(a=>({object:a,box:new Je().setFromObject(a)}));return this.clearShare(e,n,n.getCenter(new T),s,r)}apparentRadiusM(t,e,i){const n=t.sizeM.widthM/2,s=t.sizeM.heightM/2,r=t.sizeM.lengthM/2,a=this.scratch.subVectors(i,e.position),c=a.length()>0?a.applyQuaternion(e.quaternion.clone().invert()).normalize():a.set(0,0,1),l=Math.sqrt((s*r*c.x)**2+(n*r*c.y)**2+(n*s*c.z)**2);return Math.max(Math.sqrt(l),1e-6)}reliefClearShare(t,e,i){const n=this.frame?.groundYAt;if(!n)return 1;let s=0;const r=[e,new T(e.x,e.y+i,e.z),new T(e.x,e.y-i,e.z)];for(const a of r){const c=a.distanceTo(t),l=Math.max(8,Math.min(200,Math.ceil(c/25)));let h=!1;for(let u=1;u<l&&!h;u++){const d=u/l,f=t.x+(a.x-t.x)*d,p=t.z+(a.z-t.z)*d;h=n(f,p)>t.y+(a.y-t.y)*d+.5}h||s++}return s/r.length}throughAir(t,e){const i=this.frame?.transmittance?.(e.x,e.y,e.z)??[1,1,1];return[t[0]*i[0],t[1]*i[1],t[2]*i[2]]}static rgbOf(t){const e=new rt(t);return[e.r,e.g,e.b]}throwFlame(t,e,i,n,s,r){let a=this.flames.get(t.id);if(!a&&t.throwsFlame&&(a=new ol,this.flames.set(t.id,a),this.group.add(a.mesh,a.glow)),!a)return;const c=t.flame;if(!c){a.putOut(),this.dust.get(t.id)?.set(0,0,0,i,{x:0,z:0},0);return}e.updateMatrixWorld(!0);const l=e.getObjectByName(c.node??oe.EXHAUST_NODE);l?l.getWorldPosition(this.scratch):e.localToWorld(this.scratch.set(0,-.5,0)),a.place(this.scratch,l?oe.pointing(l,this.down,this.aim):e.quaternion,c.lengthM,c.widthM);const h=f=>{const p=new rt(f);return this.throughAir(oe.shown([p.r,p.g,p.b],c.luminanceCdM2,n),this.scratch)};a.set(h(c.color),h(c.tipColor??c.color),i),r.push({position:a.lightAt(new T),candela:oe.luminousIntensityCd(c),colour:oe.lightColourOf(c)});const u=ol.glowFor(c,s?a.mesh.position.distanceTo(s):0),d=new rt(c.color).lerp(new rt(c.tipColor??c.color),.5);a.shine(u.radiusM,this.throughAir(oe.shown([d.r,d.g,d.b],u.luminanceCdM2,n),this.scratch)),this.raiseDust(t.id,c,i)}raiseDust(t,e,i){const n=this.frame;if(!e.raisesDust||!n?.groundYAt){this.dust.get(t)?.set(0,0,0,i,{x:0,z:0},0);return}let s=this.dust.get(t);s||(s=new Ra(Ra.DUST),this.dust.set(t,s),this.group.add(s.points));const{x:r,y:a,z:c}=this.scratch,l=n.groundYAt(r,c),h=Math.max(0,Math.min(1,1-(a-l)/(e.lengthM+1)));s.set(r,l,c,i,n.wind??{x:0,z:0},h,n.light)}setSmoke(t,e){const i=this.frame;for(;this.smoke.length<t.length;){const n=new Ra(Ra.SMOKE);this.smoke.push(n),this.group.add(n.points)}this.smoke.forEach((n,s)=>{const r=t[s],a=e*1e3;if(!(r!==void 0&&i!==void 0&&a>=r.fromT&&(r.untilT===void 0||a<r.untilT))){n.set(0,0,0,e,{x:0,z:0},0);return}const l=i.originX+r.eastM,h=i.originZ-r.northM,u=(a-r.fromT)/1e3,d=Math.min(1,u/2)*(.1+.9*Math.pow(2,-u/(r.halfLifeS??20)));n.set(l,i.groundYAt?i.groundYAt(l,h):i.originGroundY,h,e,i.wind??{x:0,z:0},d,i.light)})}static luminousIntensityCd(t){return t.luminanceCdM2*.7*t.widthM*t.lengthM}static lightColourOf(t){const e=new rt(t.color),i=new rt(t.tipColor??t.color),n=[(e.r+i.r)/2,(e.g+i.g)/2,(e.b+i.b)/2],s=.2126*n[0]+.7152*n[1]+.0722*n[2];return s>0?[n[0]/s,n[1]/s,n[2]/s]:[1,1,1]}static pointing(t,e,i){return e.set(0,-1,0).transformDirection(t.matrixWorld).normalize(),i.setFromUnitVectors(oe.DOWN,e)}static DOWN=new T(0,-1,0);static SPECK_PIXELS=2;hideSpecks(t,e,i){const n=i.eye;t.updateMatrixWorld(!0);const s=new Je().setFromObject(t).getSize(new T),r=Math.max(s.x,s.y,s.z);for(const a of e){const c=new Je;for(const f of a.meshes)c.expandByObject(f);const l=c.getSize(new T),h=Math.max(l.x,l.y,l.z);if(h>=r/4)continue;const u=n?c.getCenter(new T).distanceTo(n):0,d=i.pixelRad===void 0||u<=0||h/u>=oe.SPECK_PIXELS*i.pixelRad;for(const f of a.meshes)f.visible=d}}static flickered(t,e){let i=0;for(let c=0;c<t.id.length;c++)i=Math.imul(i,31)+t.id.charCodeAt(c)>>>0;const n=c=>(Math.imul(i^c,2654435761)>>>0)/4294967296*2*Math.PI,s=(Math.sin(2*Math.PI*2.3*e+n(1))+Math.sin(2*Math.PI*5.1*e+n(2))+Math.sin(2*Math.PI*8.7*e+n(3)))/3,r=Math.max(0,1+t.flicker*s),a=t.lights?Object.fromEntries(Object.entries(t.lights).map(([c,l])=>[c,l*r])):void 0;return{...t,appearance:{...t.appearance,luminanceCdM2:t.appearance.luminanceCdM2*r},lights:a}}static GLOWS_WHOLE="glowsWhole";static EXHAUST_NODE="exhaust";shineLights(t,e,i,n,s){const r=n.eye,a=t.lights;if(!i||!a||!r){this.hideLights(t.id);return}e.updateMatrixWorld(!0);let c;for(const l of i){const h=`${t.id}\0${l.name}`,u=a[l.name];let d=this.lightVeils.get(h);if(!(u>0)||l.meshes.length===0){d?.hide();continue}const f=new Je;for(const A of l.meshes)f.expandByObject(A);const p=f.getCenter(new T),m=f.getSize(new T),g=Math.max(m.x,m.y,m.z)/2;s.push({position:p.clone(),candela:u*Math.PI*g*g,colour:l.hue});const v=Math.max(p.distanceTo(r),g*1.01,.001);c??=[e,...n.occluders??[]].map(A=>({object:A,box:new Je().setFromObject(A)}));const M=this.clearShare(r,f,p,l.meshes,c);if(M<=0){d?.hide();continue}d||(d=new An(`body-light:${t.id}:${l.name}`,An.OVER_EVERYTHING),this.lightVeils.set(h,d),this.group.add(d.mesh));const w=Math.asin(Math.min(1,g/v)),y=2*Math.PI*(1-Math.cos(w))*M,x=u*y*this.sceneUnitsPerLux(),b=Math.max(...l.hue)||1,E=[l.hue[0]/b,l.hue[1]/b,l.hue[2]/b],S=this.throughAir([E[0]*x,E[1]*x,E[2]*x],p);d.shine(p,S,w*180/Math.PI)}}clearShare(t,e,i,n,s){const r=[i];for(const[l,h]of[[.2,.2],[.8,.2],[.2,.8],[.8,.8]])r.push(new T(e.min.x+(e.max.x-e.min.x)*l,i.y+(l<.5?-1:1)*(e.max.y-e.min.y)*.3,e.min.z+(e.max.z-e.min.z)*h));const a=new T;let c=0;for(const l of r){a.subVectors(l,t);const h=a.length();this.lightRay.set(t,a.normalize()),this.lightRay.far=h;const u=s.filter(({box:f})=>{const p=this.lightRay.ray.intersectBox(f,this.boxHit);return p!==null&&p.distanceTo(t)<h}).map(({object:f})=>f);u.length>0&&this.lightRay.intersectObjects(u,!0).some(f=>f.object instanceof yt&&!n.includes(f.object)&&!(f.object.material instanceof xo)&&f.distance<h-.05)||c++}return c/r.length}hideLights(t){const e=`${t}\0`;for(const[i,n]of this.lightVeils)i.startsWith(e)&&n.hide()}dropGlare(t){const e=this.glares.get(t);e&&(this.group.remove(e.mesh),e.dispose(),this.glares.delete(t))}dropFlame(t){const e=this.flames.get(t);if(!e)return;e.mesh.removeFromParent(),e.glow.removeFromParent(),e.dispose(),this.flames.delete(t);const i=this.dust.get(t);i&&(i.points.removeFromParent(),i.dispose(),this.dust.delete(t))}outlineOf(t,e){const i=this.built.get(t)?.holder,n=this.frame,s=i?.getObjectByName(e);if(!i||!n||!s)return;i.updateMatrixWorld(!0);const r=[];return s.traverse(a=>{if(!(a instanceof yt))return;const c=a.geometry.getAttribute("position"),l=Math.max(1,Math.floor(c.count/400));for(let h=0;h<c.count;h+=l)this.scratch.fromBufferAttribute(c,h).applyMatrix4(a.matrixWorld),r.push({eastM:this.scratch.x-n.originX,northM:n.originZ-this.scratch.z,upM:this.scratch.y-n.originGroundY})}),r.length>0?r:void 0}boxOf(t,e){const i=this.built.get(t)?.holder;return i?.visible?e.setFromObject(i):void 0}pick(t){return this.pickHit(t)?.id}pickHit(t){const e=[...this.built.entries()].filter(([,{holder:r}])=>r.visible),i=t.intersectObjects(e.map(([,{holder:r}])=>r),!0)[0];if(!i)return;let n=i.object;for(;n&&!e.some(([,{holder:r}])=>r===n);)n=n.parent;const s=e.find(([,{holder:r}])=>r===n)?.[0];return s===void 0?void 0:{id:s,distance:i.distance}}reachFrom(t){let e=0;for(const{holder:i}of this.built.values()){if(!i.visible)continue;const n=Math.hypot(i.position.x-t.x,i.position.z-t.z);e=Math.max(e,n+Math.max(i.scale.x,i.scale.y,i.scale.z)/2)}return e}furthestFrom(t){let e=0;for(const{holder:i}of this.built.values())i.visible&&(e=Math.max(e,i.position.distanceTo(t)));return e}get reflectors(){return[...this.built.entries()].filter(([,{holder:t}])=>t.visible).map(([t,{holder:e}])=>({id:t,holder:e,shiny:oe.isShiny(e)}))}static isShiny(t){let e=!1;return t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:[n])(s instanceof xo||s instanceof ec&&(s.roughness<oe.SHINY_ROUGHNESS||s.metalness>oe.SHINY_METALNESS))&&(e=!0)}),e}static SHINY_ROUGHNESS=.6;static SHINY_METALNESS=.3;static overlay(t){t.traverse(e=>e.layers.enable(_3))}get any(){return[...this.built.values()].some(({holder:t})=>t.visible)}clear(){this.token++;for(const t of[...this.built.keys()])this.remove(t);this.pointLights.clear();for(const t of this.points??[])t.geometry.dispose(),t.material.dispose(),t.removeFromParent();this.points=void 0}build(t){const e=new Ke;e.name=`body:${t.id}`;const i=oe.signatureOf(t),n=oe.primitiveOf(t.model);if(n==="figure"){const c=new ec({roughness:.7,metalness:0});oe.paint(c,t);const l=dt.build({id:t.id,kind:"entity",eastM:0,northM:0},!1);return l.traverse(h=>{h instanceof yt&&(h.material=c,h.castShadow=!0,h.receiveShadow=!0)}),e.add(oe.fit(l,0)),oe.overlay(e),{holder:e,signature:i,material:c}}if(n){const c=new ec({roughness:.45,metalness:0});oe.paint(c,t);const l=new yt(oe.unitGeometry(n),c);return l.castShadow=!0,l.receiveShadow=!0,e.add(l),oe.overlay(e),{holder:e,signature:i,material:c}}const s=new ec({roughness:.45,metalness:0});oe.paint(s,t);const r=new yt(oe.unitGeometry("ellipsoid"),s);r.castShadow=!0,r.receiveShadow=!0,e.add(r),oe.overlay(e);const a=this.token;return this.modelFor(t.model).then(c=>{if(!c||a!==this.token||this.built.get(t.id)?.holder!==e)return;e.remove(r),r.geometry.dispose(),s.dispose(),dt.applyModelParameters(c.scene,t.modelParameters,c.bindings),Td.apply(c.scene),oe.glaze(c.scene),e.add(oe.fit(c.scene,c.headingOffsetDeg??t.model.headingOffsetDeg??0)),oe.overlay(e),this.credits.set(t.id,c.credit);const l=this.built.get(t.id);l&&(l.material=void 0,l.glowing=oe.glowingOf(c.scene),l.whole=c.scene.userData[oe.GLOWS_WHOLE]===!0,l.motions=oe.motionsOf(c.scene),l.parts=void 0,l.loaded=!0),this.lastSet&&this.set(...this.lastSet),this.onModelArrived()}).catch(c=>console.warn(`Keeping the ellipsoid for body "${t.id}":`,c)),{holder:e,signature:i,material:s}}static fit(t,e){const i=new Ke;t.rotation.y=-e*qu,i.add(t),i.updateMatrixWorld(!0);const n=new Je().setFromObject(i),s=n.getSize(new T),r=n.getCenter(new T),a=new Ke;return i.position.sub(r),a.add(i),a.scale.set(1/Math.max(s.x,1e-6),1/Math.max(s.y,1e-6),1/Math.max(s.z,1e-6)),t.traverse(c=>{c instanceof yt&&(c.castShadow=!0,c.receiveShadow=!0)}),a}static paint(t,e,i){const n=new rt(e.appearance.color),s=.2126*n.r+.7152*n.g+.0722*n.b;s>0&&n.multiplyScalar(e.appearance.albedo/s),n.r=Math.min(1,n.r),n.g=Math.min(1,n.g),n.b=Math.min(1,n.b),t.color.equals(n)||t.color.copy(n);const r=new rt(e.appearance.color),a=Math.max(r.r,r.g,r.b);oe.glow(t,a>0?[r.r/a,r.g/a,r.b/a]:[1,1,1],e.appearance.luminanceCdM2,i)}static fade(t,e){const i=1-Math.min(1,Math.max(0,e));t.traverse(n=>{if(n instanceof yt)for(const s of Array.isArray(n.material)?n.material:[n.material]){if(!(s instanceof Ga))continue;const r=s.userData.bodyOpacity??={transparent:s.transparent,opacity:s.opacity,depthWrite:s.depthWrite},a=r.opacity*i,c=i<1;s.opacity===a&&s.transparent===(r.transparent||c)||(s.transparent=r.transparent||c,s.opacity=a,s.depthWrite=c?!1:r.depthWrite,s.needsUpdate=!0)}})}static light(t,e,i){for(const{material:n,hue:s,share:r,name:a}of t)oe.glow(n,s,e.lights?.[a]??e.appearance.luminanceCdM2*r,i)}static glow(t,e,i,n){if(!(i>0)){(t.emissive.r!==0||t.emissive.g!==0||t.emissive.b!==0)&&t.emissive.setRGB(0,0,0);return}const s=oe.shown(e,i,n);t.emissive.setRGB(s[0],s[1],s[2])}static motionsOf(t){if(t.animations.length===0)return;const e=new rD(t),i=new Map;for(const n of t.animations){const s=e.clipAction(n);s.setLoop(rA,1),s.clampWhenFinished=!0,s.play(),s.paused=!0,i.set(n.name,s)}return i}static unturn(t,e,i){t.parts??=new Map;for(const n of Object.keys(i)){if(!t.parts.has(n)){const r=e.getObjectByName(n);r?t.parts.set(n,{node:r,rest:r.quaternion.clone()}):t.loaded&&(t.parts.set(n,void 0),console.warn(`Body model has no part "${n}" to turn`))}const s=t.parts.get(n);s&&s.node.quaternion.copy(s.rest)}}static turn(t,e){for(const[i,n]of Object.entries(e)){const s=t.parts?.get(i);s&&s.node.quaternion.multiply(oe.TURN.setFromAxisAngle(oe.UP,-n*qu))}}static TURN=new es;static UP=new T(0,1,0);static move(t,e){let i;for(const[n,s]of t){const r=Math.max(0,e[n]??0),a=r-Math.floor(r),c=r>0&&a===0?1:a;s.time=c*s.getClip().duration,i=s.getMixer()}i?.update(0)}static shown(t,e,i){return Gs.shown(t,e,i)}static glowingOf(t){const e=[],i=new Map;t.traverse(r=>{if(r instanceof yt)for(const a of Array.isArray(r.material)?r.material:[r.material]){if(!(a instanceof ec))continue;const c=i.get(a);if(c){c.push(r);continue}i.set(a,[r]),Math.max(a.emissive.r,a.emissive.g,a.emissive.b)>0&&e.push(a)}});const n=r=>Math.max(r.emissive.r,r.emissive.g,r.emissive.b),s=Math.max(...e.map(n),0);return s<=0?[]:e.map(r=>({material:r,hue:[r.emissive.r,r.emissive.g,r.emissive.b],share:n(r)/s,name:r.name,meshes:i.get(r)??[]}))}static primitiveOf(t){return t.url===void 0&&gE.includes(t.id??"")?t.id:void 0}static signatureOf(t){return`${t.model.id??""}|${t.model.url??""}|${t.modelParameters?JSON.stringify(t.modelParameters):""}`}static unitGeometry(t){let e;switch(t){case"ellipsoid":case"sphere":e=new hn(.5,48,24);break;case"disc":{const r=[];for(let c=0;c<=24;c++){const l=.5*Math.sin(c/24*Math.PI),h=.5*Math.cos(c/24*Math.PI);r.push(new tt(l,Math.sign(h)*h*h*2))}e=new Om(r.reverse(),64);break}case"cylinder":e=new gs(.5,.5,1,48);break;case"cone":e=new bu(.5,1,48);break;case"box":e=new en(1,1,1);break;case"torus":e=new Ay(.35,.15,24,64),e.rotateX(Math.PI/2);break;case"figure":e=new hn(.5,24,12);break}e.computeBoundingBox();const i=e.boundingBox,n=i.getSize(new T),s=i.getCenter(new T);return e.translate(-s.x,-s.y,-s.z),e.scale(1/n.x,1/n.y,1/n.z),e.computeVertexNormals(),e}remove(t){const e=this.built.get(t);if(!e)return;e.holder.removeFromParent(),e.holder.traverse(n=>{if(!(n instanceof yt))return;n.userData.sharedGeometry||n.geometry.dispose();const s=Array.isArray(n.material)?n.material:[n.material];for(const r of s)r.dispose()}),this.built.delete(t),this.credits.delete(t),this.dropFlame(t),this.dropGlare(t);const i=`${t}\0`;for(const[n,s]of[...this.lightVeils])n.startsWith(i)&&(this.group.remove(s.mesh),s.dispose(),this.lightVeils.delete(n))}}const EM=2,bL=5,SL=2048;class Fr{constructor(t){this.scene=t}cloudLayers=[];cloudSignature="";setCloudLayers(t){const e=t.map(i=>i.mesh.uuid).join(",");if(e!==this.cloudSignature){this.cloudSignature=e,this.cloudLayers=t;for(const i of this.meshes.values())this.configureCloudMaterial(i.material)}}configureCloudMaterial(t){const e=this.cloudLayers,i=this.cloudSignature;t.customProgramCacheKey=()=>i,t.onBeforeCompile=n=>{if(!e.length)return;n.vertexShader=`varying vec3 cloudPoint;
|
|
9120
9131
|
`+n.vertexShader,n.vertexShader=n.vertexShader.replace("#include <project_vertex>",`#include <project_vertex>
|
|
9121
9132
|
cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let s=`varying vec3 cloudPoint;
|
|
9122
9133
|
`,r="";e.forEach((a,c)=>{const l=`cloud${c}_`;for(const[h,u]of Object.entries(a.uniforms))n.uniforms[l+h]=u;s+=nN(l),r+=`diffuseColor.a *= ${l}transmissionAt(normalize(cloudPoint), length(cloudPoint));
|
|
@@ -9573,7 +9584,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
9573
9584
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
9574
9585
|
gl_FragColor = vec4(light, 1.0);
|
|
9575
9586
|
}
|
|
9576
|
-
`,transparent:!0,blending:Cn,depthWrite:!1,side:zi,fog:!1});this.object=new yt(new hn(Ly.RADIUS,128,32,0,Math.PI*2,0,Be.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<Be.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Gn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=Gn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class om{constructor(t){this.generator=t}static SIZE=128;target=new pf(om.SIZE,{type:Ye,generateMipmaps:!0,minFilter:cr,magFilter:Me});camera=new Iy(.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 hs{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){hs.install(),this.generator=new rM(t),this.eye=new om(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=hs.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 om(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]),hs.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),l?.(g.probe.sharp),hs.decor=g.probe.filtered;for(const v of r)hs.reflectOn(v,g.probe);for(const v of n)v.shiny||hs.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 T;static reflectOn(t,e={filtered:hs.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof xo?e.sharp&&s.setSurroundings(e.sharp):s instanceof ec&&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(hs.installed)return;hs.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!ue.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}ue.lights_fragment_maps=ue.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const T3=0,EL=1,AL=2,Wb=2,h1=1.25,Xb=1,ps=32,Rn=ps/4,R3=65535,v0=Math.pow(2,-24),ky=Symbol("SKIP_GENERATION"),I3={strategy:T3,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[ky]:!1};function ji(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 AM(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 $b(o,t){t.set(o)}function Yb(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 _p(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 Zu(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 cn(o,t){return t[o+15]===R3}function Vn(o,t){return t[o+6]}function ms(o,t){return t[o+14]}function In(o){return o+Rn}function Dn(o,t){const e=t[o+6];return o+e*Rn}function Fy(o,t){return t[o+7]}function u1(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,w=(t+e-v)*6;M<w;M+=6){const y=o[M+0],x=o[M+1],b=y-x,E=y+x;b<s&&(s=b),E>c&&(c=E),y<u&&(u=y),y>p&&(p=y);const S=o[M+2],A=o[M+3],_=S-A,I=S+A;_<r&&(r=_),I>l&&(l=I),S<d&&(d=S),S>m&&(m=S);const D=o[M+4],O=o[M+5],P=D-O,N=D+O;P<a&&(a=P),N>h&&(h=N),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 io=32,_L=(o,t)=>o.candidate-t.candidate,Ho=new Array(io).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Tp=new Float32Array(6);function TL(o,t,e,i,n,s){let r=-1,a=0;if(s===T3)r=AM(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(s===EL)r=AM(o),r!==-1&&(a=RL(e,i,n,r));else if(s===AL){const c=Zu(o);let l=h1*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)/io;if(n<io/4){const M=[...Ho];M.length=n;let w=0;for(let x=u;x<d;x+=6,w++){const b=M[w];b.candidate=e[x+2*f],b.count=0;const{bounds:E,leftCacheBounds:S,rightCacheBounds:A}=b;for(let _=0;_<3;_++)A[_]=1/0,A[_+3]=-1/0,S[_]=1/0,S[_+3]=-1/0,E[_]=1/0,E[_+3]=-1/0;_p(x,e,E)}M.sort(_L);let y=n;for(let x=0;x<y;x++){const b=M[x];for(;x+1<y&&M[x+1].candidate===b.candidate;)M.splice(x+1,1),y--}for(let x=u;x<d;x+=6){const b=e[x+2*f];for(let E=0;E<y;E++){const S=M[E];b>=S.candidate?_p(x,e,S.rightCacheBounds):(_p(x,e,S.leftCacheBounds),S.count++)}}for(let x=0;x<y;x++){const b=M[x],E=b.count,S=n-b.count,A=b.leftCacheBounds,_=b.rightCacheBounds;let I=0;E!==0&&(I=Zu(A)/c);let D=0;S!==0&&(D=Zu(_)/c);const O=Xb+h1*(I*E+D*S);O<l&&(r=f,l=O,a=b.candidate)}}else{for(let y=0;y<io;y++){const x=Ho[y];x.count=0,x.candidate=p+v+y*v;const b=x.bounds;for(let E=0;E<3;E++)b[E]=1/0,b[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/v);E>=io&&(E=io-1);const S=Ho[E];S.count++,_p(y,e,S.bounds)}const M=Ho[io-1];$b(M.bounds,M.rightCacheBounds);for(let y=io-2;y>=0;y--){const x=Ho[y],b=Ho[y+1];Yb(x.bounds,b.rightCacheBounds,x.rightCacheBounds)}let w=0;for(let y=0;y<io-1;y++){const x=Ho[y],b=x.count,E=x.bounds,A=Ho[y+1].rightCacheBounds;b!==0&&(w===0?$b(E,Tp):Yb(E,Tp,Tp)),w+=b;let _=0,I=0;w!==0&&(_=Zu(Tp)/c);const D=n-w;D!==0&&(I=Zu(A)/c);const O=Xb+h1*(_*w+I*D);O<l&&(r=f,l=O,a=x.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function RL(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 d1{constructor(){this.boundingData=new Float32Array(6)}}function IL(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 D3,M0,_M,C3;const DL=Math.pow(2,32);function TM(o){return"count"in o?1:1+TM(o.left)+TM(o.right)}function CL(o,t,e){return D3=new Float32Array(e),M0=new Uint32Array(e),_M=new Uint16Array(e),C3=new Uint8Array(e),RM(o,t)}function RM(o,t){const e=o/4,i=o/2,n="count"in t,s=t.boundingData;for(let r=0;r<6;r++)D3[e+r]=s[r];if(n)return t.buffer?(C3.set(new Uint8Array(t.buffer),o),o+t.buffer.byteLength):(M0[e+6]=t.offset,_M[i+14]=t.count,_M[i+15]=R3,o+ps);{const{left:r,right:a,splitAxis:c}=t,l=o+ps;let h=RM(l,r);const u=o/ps,f=h/ps-u;if(f>DL)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return M0[e+6]=f,M0[e+7]=c,RM(h,a)}}function OL(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 d1;return u1(t,e,i,g.boundingData,p),M(g,e,i,p),g;function v(w){u&&u((w-s.offset)/s.count)}function M(w,y,x,b=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const S=x>l;if(x<=c&&!S||E>=r)return v(y+x),w.offset=y,w.count=x,w;const A=TL(w.boundingData,b,t,y,x,h);let _=A.axis===-1?-1:IL(d,f,t,y,x,A);if(A.axis===-1||_===y||_===y+x){if(!S)return v(y+x),w.offset=y,w.count=x,w;A.axis=Math.max(0,AM(w.boundingData)),_=y+Math.max(1,Math.floor(x/2))}w.splitAxis=A.axis;const I=new d1,D=y,O=_-y;w.left=I,u1(t,D,O,I.boundingData,p),M(I,D,O,p,E+1);const P=new d1,N=_,k=x-O;return w.right=P,u1(t,N,k,P.boundingData,p),M(P,N,k,p,E+1),w}}function PL(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=OL(o,a,c.offset,c.count,t,r),h=TM(l),u=new e(ps*h);return CL(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 NL{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 Hi=new NL;let mc,Fh;const nh=[],Rp=new Uy(()=>new Je);function LL(o,t,e,i,n,s){mc=Rp.getPrimitive(),Fh=Rp.getPrimitive(),nh.push(mc,Fh),Hi.setBuffer(o._roots[t]);const r=IM(0,o.geometry,e,i,n,s);Hi.clearBuffer(),Rp.releasePrimitive(mc),Rp.releasePrimitive(Fh),nh.pop(),nh.pop();const a=nh.length;return a>0&&(Fh=nh[a-1],mc=nh[a-2]),r}function IM(o,t,e,i,n=null,s=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:l}=Hi;let h=o*2;if(cn(h,c)){const d=Vn(o,l),f=ms(h,c);return ji(o,a,mc),i(d,f,!1,r,s+o/Rn,mc)}else{let _=function(D){const{uint16Array:O,uint32Array:P}=Hi;let N=D*2;for(;!cn(N,O);)D=In(D),N=D*2;return Vn(D,P)},I=function(D){const{uint16Array:O,uint32Array:P}=Hi;let N=D*2;for(;!cn(N,O);)D=Dn(D,P),N=D*2;return Vn(D,P)+ms(N,O)};const d=In(o),f=Dn(o,l);let p=d,m=f,g,v,M,w;if(n&&(M=mc,w=Fh,ji(p,a,M),ji(m,a,w),g=n(M),v=n(w),v<g)){p=f,m=d;const D=g;g=v,v=D,M=w}M||(M=mc,ji(p,a,M));const y=cn(p*2,c),x=e(M,y,g,r+1,s+p/Rn);let b;if(x===Wb){const D=_(p),P=I(p)-D;b=i(D,P,!0,r+1,s+p/Rn,M)}else b=x&&IM(p,t,e,i,n,s,r+1);if(b)return!0;w=Fh,ji(m,a,w);const E=cn(m*2,c),S=e(w,E,v,r+1,s+m/Rn);let A;if(S===Wb){const D=_(m),P=I(m)-D;A=i(D,P,!0,r+1,s+m/Rn,w)}else A=S&&IM(m,t,e,i,n,s,r+1);return!!A}}const Rd=new Hi.constructor,cm=new Hi.constructor,Jo=new Uy(()=>new Je),sh=new Je,rh=new Je,f1=new Je,p1=new Je;let m1=!1;function kL(o,t,e,i){if(m1)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");m1=!0;const n=o._roots,s=t._roots;let r,a=0,c=0;const l=new Gt().copy(e).invert();for(let h=0,u=n.length;h<u;h++){Rd.setBuffer(n[h]),c=0;const d=Jo.getPrimitive();ji(0,Rd.float32Array,d),d.applyMatrix4(l);for(let f=0,p=s.length;f<p&&(cm.setBuffer(s[f]),r=Or(0,0,e,l,i,a,c,0,0,d),cm.clearBuffer(),c+=s[f].byteLength/ps,!r);f++);if(Jo.releasePrimitive(d),Rd.clearBuffer(),a+=n[h].byteLength/ps,r)break}return m1=!1,r}function Or(o,t,e,i,n,s=0,r=0,a=0,c=0,l=null,h=!1){let u,d;h?(u=cm,d=Rd):(u=Rd,d=cm);const f=u.float32Array,p=u.uint32Array,m=u.uint16Array,g=d.float32Array,v=d.uint32Array,M=d.uint16Array,w=o*2,y=t*2,x=cn(w,m),b=cn(y,M);let E=!1;if(b&&x)h?E=n(Vn(t,v),ms(t*2,M),Vn(o,p),ms(o*2,m),c,r+t/Rn,a,s+o/Rn):E=n(Vn(o,p),ms(o*2,m),Vn(t,v),ms(t*2,M),a,s+o/Rn,c,r+t/Rn);else if(b){const S=Jo.getPrimitive();ji(t,g,S),S.applyMatrix4(e);const A=In(o),_=Dn(o,p);ji(A,f,sh),ji(_,f,rh);const I=S.intersectsBox(sh),D=S.intersectsBox(rh);E=I&&Or(t,A,i,e,n,r,s,c,a+1,S,!h)||D&&Or(t,_,i,e,n,r,s,c,a+1,S,!h),Jo.releasePrimitive(S)}else{const S=In(t),A=Dn(t,v);ji(S,g,f1),ji(A,g,p1);const _=l.intersectsBox(f1),I=l.intersectsBox(p1);if(_&&I)E=Or(o,S,e,i,n,s,r,a,c+1,l,h)||Or(o,A,e,i,n,s,r,a,c+1,l,h);else if(_)if(x)E=Or(o,S,e,i,n,s,r,a,c+1,l,h);else{const D=Jo.getPrimitive();D.copy(f1).applyMatrix4(e);const O=In(o),P=Dn(o,p);ji(O,f,sh),ji(P,f,rh);const N=D.intersectsBox(sh),k=D.intersectsBox(rh);E=N&&Or(S,O,i,e,n,r,s,c,a+1,D,!h)||k&&Or(S,P,i,e,n,r,s,c,a+1,D,!h),Jo.releasePrimitive(D)}else if(I)if(x)E=Or(o,A,e,i,n,s,r,a,c+1,l,h);else{const D=Jo.getPrimitive();D.copy(p1).applyMatrix4(e);const O=In(o),P=Dn(o,p);ji(O,f,sh),ji(P,f,rh);const N=D.intersectsBox(sh),k=D.intersectsBox(rh);E=N&&Or(A,O,i,e,n,r,s,c,a+1,D,!h)||k&&Or(A,P,i,e,n,r,s,c,a+1,D,!h),Jo.releasePrimitive(D)}}return E}const g1=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(;!cn(r,e);)s=In(s),r=s*2;return Vn(s,t)},this.getRangeEnd=s=>{let r=s*2;for(;!cn(r,e);)s=Dn(s,t),r=s*2;return Vn(s,t)+ms(r,e)};const n=(s,r,a)=>{const c=r*2,l=cn(c,e);if(!s(a,l,r)&&!l){const u=In(r),d=Dn(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=Fy(c,t);return s(r,a,new Float32Array(o,c*4,6),l)}})}}},Kb=new Je,ah=new Float32Array(6);class FL{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...I3,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),PL(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,ah,0);const[f,p,m,g,v,M]=ah;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,ah,0);const[a,c,l,h,u,d]=ah,f=(a+h)/2,p=(c+u)/2,m=(l+d)/2,g=(h-a)/2,v=(u-c)/2,M=(d-l)/2,w=(s-n)*6;i[w+0]=f,i[w+1]=g+(Math.abs(f)+g)*v0,i[w+2]=p,i[w+3]=v+(Math.abs(p)+v)*v0,i[w+4]=m,i[w+5]=M+(Math.abs(m)+M)*v0}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/ps;for(let l=0;l<c;l++){const h=Rn*l,u=2*h;cn(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){g1.setBVH(this,e),g1.traverse(t),g1.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/ps;for(let l=c-1;l>=0;l--){const h=l*Rn,u=h*2;if(cn(u,r)){const f=Vn(h,s),p=ms(u,r);this.writePrimitiveRangeBounds(f,p,ah,0),a.set(ah,h)}else{const f=In(h),p=Dn(h,s);for(let m=0;m<3;m++){const g=a[f+m],v=a[f+m+3],M=a[p+m],w=a[p+m+3];a[h+m]=g<M?g:M,a[h+m+3]=v>w?v:w}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{ji(0,new Float32Array(i),Kb),t.union(Kb)}),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=LL(this,u,i,n,e,l),c)break;l+=f.byteLength/ps}return c}bvhcast(t,e,i){let{intersectsRanges:n}=i;return kL(this,t,e,n)}}function UL(){return typeof SharedArrayBuffer<"u"}function zy(o){return o.index?o.index.count:o.attributes.position.count}function zm(o){return zy(o)/3}function zL(o,t=ArrayBuffer){return o>65535?new Uint32Array(new t(4*o)):new Uint16Array(new t(2*o))}function BL(o,t){if(!o.index){const e=o.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=zL(e,i);o.setIndex(new ye(n,1));for(let s=0;s<e;s++)n[s]=s}}function HL(o,t,e){const i=zy(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 GL(o,t){return o.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function qb(o,t,e){const i=HL(o,t,e),n=GL(o,e);if(!n.length)return[i];const s=[],r=i.offset,a=i.offset+i.count,c=zy(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 VL(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 WL extends FL{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&&!UL())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={...I3,...e},e[ky]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=qb(e,t.range,i),s=VL(n,t.useSharedArrayBuffer);this._indirectBuffer=s}else BL(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Je))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:qb(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Ao{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}}Ao.prototype.setFromBox=(function(){const o=new T;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 XL=(function(){const o=new T,t=new T,e=new T;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}})(),By=(function(){const o=new tt,t=new T,e=new T;return function(n,s,r,a){XL(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}}}})(),$L=(function(){const o=new T,t=new T,e=new Hr,i=new Eo;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}})(),YL=["x","y","z"],ro=1e-15,Zb=ro*ro;function mr(o){return Math.abs(o)<ro}class Kr extends Hn{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new T),this.satBounds=new Array(4).fill().map(()=>new Ao),this.points=[this.a,this.b,this.c],this.plane=new Hr,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Eo,this.needsUpdate=!0}intersectsSphere(t){return $L(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<ro?g<ro||v<ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):g<ro?v<ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):v<ro&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}Kr.prototype.closestPointToSegment=(function(){const o=new T,t=new T,e=new Eo;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]),By(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)}})();Kr.prototype.intersectsTriangle=(function(){const o=new Kr,t=new Ao,e=new Ao,i=new T,n=new T,s=new T,r=new T,a=new Eo,c=new Eo,l=new T,h=new tt,u=new tt;function d(w,y,x,b){const E=i;!w.isDegenerateIntoPoint&&!w.isDegenerateIntoSegment?E.copy(w.plane.normal):E.copy(y.plane.normal);const S=w.satBounds,A=w.satAxes;for(let D=1;D<4;D++){const O=S[D],P=A[D];if(t.setFromPoints(P,y.points),O.isSeparated(t)||(r.copy(E).cross(P),t.setFromPoints(r,w.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],P=I[D];if(t.setFromPoints(P,w.points),O.isSeparated(t)||(r.crossVectors(E,P),t.setFromPoints(r,w.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}return x&&(b||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),x.start.set(0,0,0),x.end.set(0,0,0)),!0}function f(w,y,x,b,E,S,A,_,I,D,O){let P=A/(A-_);D.x=b+(E-b)*P,O.start.subVectors(y,w).multiplyScalar(P).add(w),P=A/(A-I),D.y=b+(S-b)*P,O.end.subVectors(x,w).multiplyScalar(P).add(w)}function p(w,y,x,b,E,S,A,_,I,D,O){if(E>0)f(w.c,w.a,w.b,b,y,x,I,A,_,D,O);else if(S>0)f(w.b,w.a,w.c,x,y,b,_,A,I,D,O);else if(_*I>0||A!=0)f(w.a,w.b,w.c,y,x,b,A,_,I,D,O);else if(_!=0)f(w.b,w.a,w.c,x,y,b,_,A,I,D,O);else if(I!=0)f(w.c,w.a,w.b,b,y,x,I,A,_,D,O);else return!0;return!1}function m(w,y,x,b){const E=y.degenerateSegment,S=w.plane.distanceToPoint(E.start),A=w.plane.distanceToPoint(E.end);return mr(S)?mr(A)?d(w,y,x,b):(x&&(x.start.copy(E.start),x.end.copy(E.start)),w.containsPoint(E.start)):mr(A)?(x&&(x.start.copy(E.end),x.end.copy(E.end)),w.containsPoint(E.end)):w.plane.intersectLine(E,i)!=null?(x&&(x.start.copy(i),x.end.copy(i)),w.containsPoint(i)):!1}function g(w,y,x){const b=y.a;return mr(w.plane.distanceToPoint(b))&&w.containsPoint(b)?(x&&(x.start.copy(b),x.end.copy(b)),!0):!1}function v(w,y,x){const b=w.degenerateSegment,E=y.a;return b.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<Zb?(x&&(x.start.copy(E),x.end.copy(E)),!0):!1}function M(w,y,x,b){if(w.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=w.degenerateSegment,S=y.degenerateSegment,A=n,_=s;E.delta(A),S.delta(_);const I=i.subVectors(S.start,E.start),D=A.x*_.y-A.y*_.x;if(mr(D))return!1;const O=(I.x*_.y-I.y*_.x)/D,P=-(A.x*I.y-A.y*I.x)/D;if(O<0||O>1||P<0||P>1)return!1;const N=E.start.z+A.z*O,k=S.start.z+_.z*P;return mr(N-k)?(x&&(x.start.copy(E.start).addScaledVector(A,O),x.end.copy(E.start).addScaledVector(A,O)),!0):!1}else return y.isDegenerateIntoPoint?v(w,y,x):m(y,w,x,b);else{if(w.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(w.a)<Zb?(x&&(x.start.copy(w.a),x.end.copy(w.a)),!0):!1:y.isDegenerateIntoSegment?v(y,w,x):g(y,w,x);if(y.isDegenerateIntoPoint)return g(w,y,x);if(y.isDegenerateIntoSegment)return m(w,y,x,b)}}return function(y,x=null,b=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(o.copy(y),o.update(),y=o);const E=M(this,y,x,b);if(E!==void 0)return E;const S=this.plane,A=y.plane;let _=A.distanceToPoint(this.a),I=A.distanceToPoint(this.b),D=A.distanceToPoint(this.c);mr(_)&&(_=0),mr(I)&&(I=0),mr(D)&&(D=0);const O=_*I,P=_*D;if(O>0&&P>0)return!1;let N=S.distanceToPoint(y.a),k=S.distanceToPoint(y.b),B=S.distanceToPoint(y.c);mr(N)&&(N=0),mr(k)&&(k=0),mr(B)&&(B=0);const W=N*k,Q=N*B;if(W>0&&Q>0)return!1;n.copy(S.normal),s.copy(A.normal);const Z=n.cross(s);let nt=0,ot=Math.abs(Z.x);const Ut=Math.abs(Z.y);Ut>ot&&(ot=Ut,nt=1),Math.abs(Z.z)>ot&&(nt=2);const jt=YL[nt],K=this.a[jt],lt=this.b[jt],ct=this.c[jt],V=y.a[jt],Lt=y.b[jt],Xt=y.c[jt];if(p(this,K,lt,ct,O,P,_,I,D,h,a))return d(this,y,x,b);if(p(y,V,Lt,Xt,W,Q,N,k,B,u,c))return d(this,y,x,b);if(h.y<h.x){const kt=h.y;h.y=h.x,h.x=kt,l.copy(a.start),a.start.copy(a.end),a.end.copy(l)}if(u.y<u.x){const kt=u.y;u.y=u.x,u.x=kt,l.copy(c.start),c.start.copy(c.end),c.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(x&&(u.x>h.x?x.start.copy(c.start):x.start.copy(a.start),u.y<h.y?x.end.copy(c.end):x.end.copy(a.end)),!0)}})();Kr.prototype.distanceToPoint=(function(){const o=new T;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Kr.prototype.distanceToTriangle=(function(){const o=new T,t=new T,e=["a","b","c"],i=new Eo,n=new Eo;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]),By(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 Cs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new T,this.max=new T,this.matrix=new Gt,this.invMatrix=new Gt,this.points=new Array(8).fill().map(()=>new T),this.satAxes=new Array(3).fill().map(()=>new T),this.satBounds=new Array(3).fill().map(()=>new Ao),this.alignedSatBounds=new Array(3).fill().map(()=>new Ao),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}}Cs.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}})();Cs.prototype.intersectsBox=(function(){const o=new Ao;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}})();Cs.prototype.intersectsTriangle=(function(){const o=new Kr,t=new Array(3),e=new Ao,i=new Ao,n=new T;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}})();Cs.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}})();Cs.prototype.distanceToPoint=(function(){const o=new T;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Cs.prototype.distanceToBox=(function(){const o=["x","y","z"],t=new Array(12).fill().map(()=>new Eo),e=new Array(12).fill().map(()=>new Eo),i=new T,n=new T;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 w=(g+1)%3,y=(g+2)%3,x=v<<w|M<<y,b=1<<g|v<<w|M<<y,E=f[x],S=f[b];t[m].set(E,S);const _=o[g],I=o[w],D=o[y],O=e[m],P=O.start,N=O.end;P[_]=u[_],P[I]=v?u[I]:d[I],P[D]=M?u[D]:d[I],N[_]=d[_],N[I]=v?u[I]:d[I],N[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 w=n.distanceToSquared(i);if(w<p&&(p=w,c&&c.copy(i),l&&l.copy(n),w<h))return Math.sqrt(w)}for(let g=0;g<12;g++){const v=t[g];for(let M=0;M<12;M++){const w=e[M];By(v,w,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 KL extends Uy{constructor(){super(()=>new Kr)}}const Er=new KL,Ju=new T,v1=new T;function qL(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=>(Ju.copy(t).clamp(h.min,h.max),Ju.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<a&&d<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Ju);const d=t.distanceToSquared(Ju);return d<a&&(v1.copy(Ju),a=d,c=u),d<s}}),a===1/0)return null;const l=Math.sqrt(a);return e.point?e.point.copy(v1):e.point=v1.clone(),e.distance=l,e.faceIndex=c,e}const Ip=parseInt(_f)>=169,ZL=parseInt(_f)<=161,Lc=new T,kc=new T,Fc=new T,Dp=new tt,Cp=new tt,Op=new tt,Jb=new T,jb=new T,Qb=new T,ju=new T;function JL(o,t,e,i,n,s,r,a){let c;if(s===zi?c=o.intersectTriangle(i,e,t,!0,n):c=o.intersectTriangle(t,e,i,s!==Tn,n),c===null)return null;const l=o.origin.distanceTo(n);return l<r||l>a?null:{distance:l,point:n.clone()}}function tS(o,t,e,i,n,s,r,a,c,l,h){Lc.fromBufferAttribute(t,s),kc.fromBufferAttribute(t,r),Fc.fromBufferAttribute(t,a);const u=JL(o,Lc,kc,Fc,ju,c,l,h);if(u){if(i){Dp.fromBufferAttribute(i,s),Cp.fromBufferAttribute(i,r),Op.fromBufferAttribute(i,a),u.uv=new tt;const f=Hn.getInterpolation(ju,Lc,kc,Fc,Dp,Cp,Op,u.uv);Ip||(u.uv=f)}if(n){Dp.fromBufferAttribute(n,s),Cp.fromBufferAttribute(n,r),Op.fromBufferAttribute(n,a),u.uv1=new tt;const f=Hn.getInterpolation(ju,Lc,kc,Fc,Dp,Cp,Op,u.uv1);Ip||(u.uv1=f),ZL&&(u.uv2=u.uv1)}if(e){Jb.fromBufferAttribute(e,s),jb.fromBufferAttribute(e,r),Qb.fromBufferAttribute(e,a),u.normal=new T;const f=Hn.getInterpolation(ju,Lc,kc,Fc,Jb,jb,Qb,u.normal);u.normal.dot(o.direction)>0&&u.normal.multiplyScalar(-1),Ip||(u.normal=f)}const d={a:s,b:r,c:a,normal:new T,materialIndex:0};if(Hn.getNormal(Lc,kc,Fc,d.normal),u.face=d,u.faceIndex=s,Ip){const f=new T;Hn.getBarycoord(ju,Lc,kc,Fc,f),u.barycoord=f}}return u}function eS(o){return o&&o.isMaterial?o.side:o}function Bm(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,w=d.length;M<w;M++){const{start:y,count:x,materialIndex:b}=d[M];if(v>=y&&v<y+x){const E=eS(t[b]),S=tS(e,f,p,m,g,c,l,h,E,s,r);if(S)if(S.faceIndex=i,S.face.materialIndex=b,n)n.push(S);else return S}}}else{const v=eS(t),M=tS(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 xn(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 jL(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++)Bm(c,t,e,h,s,r,a)}function QL(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=Bm(a,t,e,u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function t9(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,xn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function e9(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(cn(m,a)){const g=Vn(d,r),v=ms(m,a);let M=1/0,w=1/0,y=1/0,x=-1/0,b=-1/0,E=-1/0;for(let S=3*g,A=3*(g+v);S<A;S++){let _=i[S];const I=n.getX(_),D=n.getY(_),O=n.getZ(_);I<M&&(M=I),I>x&&(x=I),D<w&&(w=D),D>b&&(b=D),O<y&&(y=O),O>E&&(E=O)}return c[d+0]!==M||c[d+1]!==w||c[d+2]!==y||c[d+3]!==x||c[d+4]!==b||c[d+5]!==E?(c[d+0]=M,c[d+1]=w,c[d+2]=y,c[d+3]=x,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=In(d),v=Dn(d,r);let M=p,w=!1,y=!1;if(t){if(!M){const _=g/Rn+f/ps,I=v/Rn+f/ps;w=t.has(_),y=t.has(I),M=!w&&!y}}else w=!0,y=!0;const x=M||w,b=M||y;let E=!1;x&&(E=u(g,f,M));let S=!1;b&&(S=u(v,f,M));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],P=c[I+3],N=c[D],k=c[D+3];c[d+_]=O<N?O:N,c[d+_+3]=P>k?P:k}return A}}}function Ec(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],w=t[o+1],y=t[o+3+1],x=t[o+2],b=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=(w-m)*d,c=(y-m)*d):(a=(y-m)*d,c=(w-m)*d),s>c||a>r||((a>s||isNaN(s))&&(s=a),(c<r||isNaN(r))&&(r=c),f>=0?(l=(x-g)*f,h=(b-g)*f):(l=(b-g)*f,h=(x-g)*f),s>h||l>r)?!1:((l>s||s!==s)&&(s=l),(h<r||r!==r)&&(r=h),s<=n&&r>=i)}function i9(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;Bm(c,t,e,d,s,r,a)}}function n9(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=Bm(a,t,e,c?c[u]:u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function s9(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),xn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function r9(o,t,e,i,n,s,r){Hi.setBuffer(o._roots[t]),DM(0,o,e,i,n,s,r),Hi.clearBuffer()}function DM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Hi,h=o*2;if(cn(h,c)){const d=Vn(o,l),f=ms(h,c);jL(t,e,i,d,f,n,s,r)}else{const d=In(o);Ec(d,a,i,s,r)&&DM(d,t,e,i,n,s,r);const f=Dn(o,l);Ec(f,a,i,s,r)&&DM(f,t,e,i,n,s,r)}}const a9=["x","y","z"];function o9(o,t,e,i,n,s){Hi.setBuffer(o._roots[t]);const r=CM(0,o,e,i,n,s);return Hi.clearBuffer(),r}function CM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Hi;let l=o*2;if(cn(l,a)){const u=Vn(o,c),d=ms(l,a);return QL(t,e,i,u,d,n,s)}else{const u=Fy(o,c),d=a9[u],p=i.direction[d]>=0;let m,g;p?(m=In(o),g=Dn(o,c)):(m=Dn(o,c),g=In(o));const M=Ec(m,r,i,n,s)?CM(m,t,e,i,n,s):null;if(M){const x=M.point[d];if(p?x<=r[g+u]:x>=r[g+u+3])return M}const y=Ec(g,r,i,n,s)?CM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const Pp=new Je,oh=new Kr,ch=new Kr,Qu=new Gt,iS=new Cs,Np=new Cs;function c9(o,t,e,i){Hi.setBuffer(o._roots[t]);const n=OM(0,o,e,i);return Hi.clearBuffer(),n}function OM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Hi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),iS.set(e.boundingBox.min,e.boundingBox.max,i),n=iS),cn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Vn(o,a),g=ms(c,r);if(Qu.copy(i).invert(),e.boundsTree)return ji(o,s,Np),Np.matrix.copy(Qu),Np.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>Np.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let w=m*3,y=(g+m)*3;w<y;w+=3)if(xn(ch,w,u,d),ch.needsUpdate=!0,M.intersectsTriangle(ch))return!0;return!1}});{const v=zm(e);for(let M=m*3,w=(g+m)*3;M<w;M+=3){xn(oh,M,u,d),oh.a.applyMatrix4(Qu),oh.b.applyMatrix4(Qu),oh.c.applyMatrix4(Qu),oh.needsUpdate=!0;for(let y=0,x=v*3;y<x;y+=3)if(xn(ch,y,f,p),ch.needsUpdate=!0,oh.intersectsTriangle(ch))return!0}}}else{const h=In(o),u=Dn(o,a);return ji(h,s,Pp),!!(n.intersectsBox(Pp)&&OM(h,t,e,i,n)||(ji(u,s,Pp),n.intersectsBox(Pp)&&OM(u,t,e,i,n)))}}const Lp=new Gt,M1=new Cs,td=new Cs,l9=new T,h9=new T,u9=new T,d9=new T;function f9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),M1.set(t.boundingBox.min,t.boundingBox.max,e),M1.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=Er.getPrimitive(),f=Er.getPrimitive();let p=l9,m=h9,g=null,v=null;n&&(g=u9,v=d9);let M=1/0,w=null,y=null;return Lp.copy(e).invert(),td.matrix.copy(Lp),o.shapecast({boundsTraverseOrder:x=>M1.distanceToBox(x),intersectsBounds:(x,b,E)=>E<M&&E<r?(b&&(td.min.copy(x.min),td.max.copy(x.max),td.needsUpdate=!0),!0):!1,intersectsRange:(x,b)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:S=>td.distanceToBox(S),intersectsBounds:(S,A,_)=>_<M&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){xn(f,3*_,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let D=x,O=x+b;D<O;D++){xn(d,3*D,l,c),d.needsUpdate=!0;const P=d.distanceToTriangle(f,p,g);if(P<M&&(m.copy(p),v&&v.copy(g),M=P,w=D,y=_),P<s)return!0}}}});{const E=zm(t);for(let S=0,A=E;S<A;S++){xn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=x,I=x+b;_<I;_++){xn(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,w=_,y=S),D<s)return!0}}}}}),Er.releasePrimitive(d),Er.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=w,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(Lp),m.applyMatrix4(Lp),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function p9(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(cn(m,a)){const g=Vn(d,r),v=ms(m,a);let M=1/0,w=1/0,y=1/0,x=-1/0,b=-1/0,E=-1/0;for(let S=g,A=g+v;S<A;S++){const _=3*o.resolveTriangleIndex(S);for(let I=0;I<3;I++){let D=_+I;D=i?i[D]:D;const O=n.getX(D),P=n.getY(D),N=n.getZ(D);O<M&&(M=O),O>x&&(x=O),P<w&&(w=P),P>b&&(b=P),N<y&&(y=N),N>E&&(E=N)}}return c[d+0]!==M||c[d+1]!==w||c[d+2]!==y||c[d+3]!==x||c[d+4]!==b||c[d+5]!==E?(c[d+0]=M,c[d+1]=w,c[d+2]=y,c[d+3]=x,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=In(d),v=Dn(d,r);let M=p,w=!1,y=!1;if(t){if(!M){const _=g/Rn+f/ps,I=v/Rn+f/ps;w=t.has(_),y=t.has(I),M=!w&&!y}}else w=!0,y=!0;const x=M||w,b=M||y;let E=!1;x&&(E=u(g,f,M));let S=!1;b&&(S=u(v,f,M));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],P=c[I+3],N=c[D],k=c[D+3];c[d+_]=O<N?O:N,c[d+_+3]=P>k?P:k}return A}}}function m9(o,t,e,i,n,s,r){Hi.setBuffer(o._roots[t]),PM(0,o,e,i,n,s,r),Hi.clearBuffer()}function PM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Hi,h=o*2;if(cn(h,c)){const d=Vn(o,l),f=ms(h,c);i9(t,e,i,d,f,n,s,r)}else{const d=In(o);Ec(d,a,i,s,r)&&PM(d,t,e,i,n,s,r);const f=Dn(o,l);Ec(f,a,i,s,r)&&PM(f,t,e,i,n,s,r)}}const g9=["x","y","z"];function v9(o,t,e,i,n,s){Hi.setBuffer(o._roots[t]);const r=NM(0,o,e,i,n,s);return Hi.clearBuffer(),r}function NM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Hi;let l=o*2;if(cn(l,a)){const u=Vn(o,c),d=ms(l,a);return n9(t,e,i,u,d,n,s)}else{const u=Fy(o,c),d=g9[u],p=i.direction[d]>=0;let m,g;p?(m=In(o),g=Dn(o,c)):(m=Dn(o,c),g=In(o));const M=Ec(m,r,i,n,s)?NM(m,t,e,i,n,s):null;if(M){const x=M.point[d];if(p?x<=r[g+u]:x>=r[g+u+3])return M}const y=Ec(g,r,i,n,s)?NM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const kp=new Je,lh=new Kr,hh=new Kr,ed=new Gt,nS=new Cs,Fp=new Cs;function M9(o,t,e,i){Hi.setBuffer(o._roots[t]);const n=LM(0,o,e,i);return Hi.clearBuffer(),n}function LM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Hi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),nS.set(e.boundingBox.min,e.boundingBox.max,i),n=nS),cn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Vn(o,a),g=ms(c,r);if(ed.copy(i).invert(),e.boundsTree)return ji(o,s,Fp),Fp.matrix.copy(ed),Fp.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>Fp.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let w=m,y=g+m;w<y;w++)if(xn(hh,3*t.resolveTriangleIndex(w),u,d),hh.needsUpdate=!0,M.intersectsTriangle(hh))return!0;return!1}});{const v=zm(e);for(let M=m,w=g+m;M<w;M++){const y=t.resolveTriangleIndex(M);xn(lh,3*y,u,d),lh.a.applyMatrix4(ed),lh.b.applyMatrix4(ed),lh.c.applyMatrix4(ed),lh.needsUpdate=!0;for(let x=0,b=v*3;x<b;x+=3)if(xn(hh,x,f,p),hh.needsUpdate=!0,lh.intersectsTriangle(hh))return!0}}}else{const h=In(o),u=Dn(o,a);return ji(h,s,kp),!!(n.intersectsBox(kp)&&LM(h,t,e,i,n)||(ji(u,s,kp),n.intersectsBox(kp)&&LM(u,t,e,i,n)))}}const Up=new Gt,y1=new Cs,id=new Cs,y9=new T,w9=new T,x9=new T,b9=new T;function S9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),y1.set(t.boundingBox.min,t.boundingBox.max,e),y1.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=Er.getPrimitive(),f=Er.getPrimitive();let p=y9,m=w9,g=null,v=null;n&&(g=x9,v=b9);let M=1/0,w=null,y=null;return Up.copy(e).invert(),id.matrix.copy(Up),o.shapecast({boundsTraverseOrder:x=>y1.distanceToBox(x),intersectsBounds:(x,b,E)=>E<M&&E<r?(b&&(id.min.copy(x.min),id.max.copy(x.max),id.needsUpdate=!0),!0):!1,intersectsRange:(x,b)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:S=>id.distanceToBox(S),intersectsBounds:(S,A,_)=>_<M&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){const D=E.resolveTriangleIndex(_);xn(f,3*D,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let O=x,P=x+b;O<P;O++){const N=o.resolveTriangleIndex(O);xn(d,3*N,l,c),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,g);if(k<M&&(m.copy(p),v&&v.copy(g),M=k,w=O,y=_),k<s)return!0}}}})}else{const E=zm(t);for(let S=0,A=E;S<A;S++){xn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=x,I=x+b;_<I;_++){const D=o.resolveTriangleIndex(_);xn(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,w=_,y=S),O<s)return!0}}}}}),Er.releasePrimitive(d),Er.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=w,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(Up),m.applyMatrix4(Up),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function sS(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 zp=new Cs,Bp=new El,rS=new T,aS=new Gt,oS=new T,w1=["getX","getY","getZ"];class lm extends WL{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 lm(e,{...i,[ky]:!0});if(a._roots=s,a._indirectBuffer=r||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new ye(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/ps;p<m;p++){const g=Rn*p,v=2*g;cn(v,f)||(d[g+6]=d[g+6]/Rn-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[w1[f]](h),m=r[w1[f]](u),g=r[w1[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 w=v+0,y=v+1,x=v+2;a&&(w=a[w],y=a[y],x=a[x]),c||(w=w*u+h,y=y*u+h,x=x*u+h);for(let b=0;b<3;b++){let E,S,A;c?(E=r[d[b]](w),S=r[d[b]](y),A=r[d[b]](x)):(E=l[w+b],S=l[y+b],A=l[x+b]);let _=E;S<_&&(_=S),A<_&&(_=A);let I=E;S>I&&(I=S),A>I&&(I=A);const D=(I-_)/2,O=b*2;i[M+O+0]=_+D,i[M+O+1]=D+(Math.abs(_)+D)*v0}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(n===void 0)return;aS.copy(t.matrixWorld).invert(),Bp.copy(e.ray).applyMatrix4(aS),oS.setFromMatrixScale(t.matrixWorld),rS.copy(Bp.direction).multiply(oS);const s=rS.length(),r=e.near/s,a=e.far/s;if(e.firstHitOnly===!0){let c=this.raycastFirst(Bp,n,r,a);c=sS(c,t,e),c&&i.push(c)}else{const c=this.raycast(Bp,n,r,a);for(let l=0,h=c.length;l<h;l++){const u=sS(c[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?p9:e9)(this,t)}raycast(t,e=Ba,i=0,n=1/0){const s=this._roots,r=[],a=this.indirect?m9:r9;for(let c=0,l=s.length;c<l;c++)a(this,c,e,t,r,i,n);return r}raycastFirst(t,e=Ba,i=0,n=1/0){const s=this._roots;let r=null;const a=this.indirect?v9:o9;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?M9:c9;for(let r=0,a=n.length;r<a&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=Er.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?s9:t9});return Er.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=Er.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,l=this.indirect?p=>{const m=this.resolveTriangleIndex(p);xn(r,m*3,a,c)}:p=>{xn(r,p*3,a,c)},h=Er.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const m=t.resolveTriangleIndex(p);xn(h,m*3,u,d)}:p=>{xn(h,p*3,u,d)};if(s){if(!(t instanceof lm))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(m,g,v,M,w,y,x,b)=>{for(let E=v,S=v+M;E<S;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,w,y,x,b))return!0}return!1};if(n){const m=n;n=function(g,v,M,w,y,x,b,E){return m(g,v,M,w,y,x,b,E)?!0:p(g,v,M,w,y,x,b,E)}}else n=p}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return zp.set(t.min,t.max,e),zp.needsUpdate=!0,this.shapecast({intersectsBounds:i=>zp.intersectsBox(i),intersectsTriangle:i=>zp.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?S9:f9)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return qL(this,t,e,i,n)}}class aa{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new Tr;static install(){if(aa.installed)return;aa.installed=!0;const t=yt.prototype.raycast;yt.prototype.raycast=function(e,i){const n=aa.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 ye)||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<aa.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=aa.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(r))return null;const a=aa.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;aa.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const c=new lm(i,{indirect:!0});return aa.trees.set(i,{bvh:c,position:n,positionVersion:n.version,index:s,indexVersion:s?.version??0}),c}}function E9(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.visibilityKm===t.visibilityKm&&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 Hp=900,x1=1,cS=4,b1=5,Gp=.5,Vp=We.GROUND_RADIUS_M;function lS(o){return We.groundRadiusFor(o)}const S1=.5,E1=850,Wp=.03,A9=.015,ys=850,uh=300,Za=120,_9=700,A1=.03,T9=3.5,Xp=20,_1=.04,R9=.26,hS=4,T1=1.5,uS=-1,I9=.01,y0=-4,D9=2,C9=20,$p=2600,O9=.97,P9=.38,nd=y0,N9=8,L9=2,dS=1500,k9=.7,F9=.3,U9=.32,z9=.65,fS=2.4,B9=.9,H9=400,G9=[0,45,90,135,180,225,270,315],V9=2,W9=16,pS=4e3,mS=880,Yp=40,gS=60,X9=10,vS=1,$9=We.REBUILD_DISTANCE_M,MS=.265,yS=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*MS,Math.sin(e)*MS]})],R1=700,I1=250/UM,Y9=12,wS=5,D1=6,Uc=[.92,.92,.95],C1=[.15,.15,.19],O1={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}},gh=0,P1=0,K9=150,N1=3e3,sd=20,q9=15,xS=gh,Z9=40,bS=1,J9=9;function L1(o){return bS+(J9-bS)*o}const SS=new rt(.75,.82,.92),j9=10,Q9=.5;function ES(o){return oa(o/j9,Q9,1)}const zc=200,AS=.18,_S=.32,t7=.35,TS=new rt(.85,.9,.98),RS=5,IS=.85,DS=.01;function e7(o,t,e=1){return Math.round(o*(DS+(1-DS)*t)*e)}function i7(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 CS=230,OS=.7,PS=.05,n7=.6,s7=.7,r7=.15,NS=.35,a7=3,o7=1/12,c7=.5,ia=new rt(.82,.86,1),l7=2500,h7=1.6,k1=15,u7={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 ht{renderer;scene=new hr;phenomena=new Fr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Ke;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()+pS,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),pS+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new we;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new tt;decorModelProvider=new S3;decorModelToken=0;decorModelCredits=new Map;emitterLights=new bs(this.scene,()=>this.relativeScale,{halfExtentM:Za,depthHalfRangeM:uh,biasM:A1,normalBiasM:_1,mapSize:1024});bodySystem=new oe(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??ht.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*ht.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 q0(16777215,0);celestialLightTarget=new Bi;skyLight=new GI(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 l0;weather=gm;observerElevationM=0;siteElevationM=0;air=new ls;groundRadius=Vp;terrainRadius=Vp;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new T;cloudFieldOffset=new T;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new T;rainLastVerticalFacing=-1;rainViewportSize=new tt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new q0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new T;sunVisible=!1;lensFlareScratch=new T;sunOcclusionRaycaster=new l0;sunOcclusionDirectionScratch=new T;sunOcclusionRightScratch=new T;sunOcclusionUpScratch=new T;ufoOcclusionRaycaster=new l0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=ke.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 Mf;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=jA()){xd.install(),aa.install(),this.renderer=new n8({canvas:t,antialias:!0}),this.resolution=new ni(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=dd,this.camera=new jn(60,t.width/Math.max(t.height,1),.1,Hp*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=-Za,this.celestialLight.shadow.camera.right=Za,this.celestialLight.shadow.camera.top=Za,this.celestialLight.shadow.camera.bottom=-Za,this.celestialLight.shadow.camera.near=ys-uh,this.celestialLight.shadow.camera.far=ys+uh,this.celestialLight.shadow.bias=-A1/(2*uh),this.celestialLight.shadow.normalBias=_1,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(ia),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 fe(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*I1,0,t.z*I1);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)*ei,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ei;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ei,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(lS(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Vp),this.camera.far=Math.max(Hp*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=ht.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return We.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=re(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=vS+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=We.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=re(n,s,r.lat,r.lng);if(Math.hypot(l.x,l.z)<r.radiusM*ht.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:n,lng:s,radiusM:e.radiusM};const a=++this.lookPatchToken,c=this.terrainProviders;e1(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=ht.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=re(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)}),ht.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(We.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=re(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<$9*(r/Vp))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(re(t,e,c.lat,c.lng).x,re(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(e1(t,e,this.terrainProviders,r,{route:this.observerRoute}),ht.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?re(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=vS,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(!We.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=re(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*ht.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??We.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(e1(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*ht.FAR_RING_OPEN_SHARE,referenceElevationM:s}),ht.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=ht.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-ht.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=re(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=re(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)/ht.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=We.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>ht.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(re(t,e,s.lat,s.lng).x,re(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(bd(t,e,i)),ht.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>ht.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),ht.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(re(t,e,a.lat,a.lng).x,re(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(bd(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)}),ht.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)),hs.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=at(async()=>{const{WaterSystem:t}=await import("./WaterSystem-DrSAhM5g.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>ht.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(re(t,e,s.lat,s.lng).x,re(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(bd(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)}),ht.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),hs.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=at(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-C1nfRJfj.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??=at(async()=>{const{TraceSystem:t}=await import("./TraceSystem-BkUPo1Xf.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(b1);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=dt.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?re(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 Ii(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?An.LENS_K:An.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(E9(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!i7(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||e.visibilityKm!==t.visibilityKm||n||s)&&this.restateHaze(),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>=c7,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(ht.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=ht.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=ht.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),dt.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,N9);for(const i of t){const n=dt.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)<L9,i.lamp),i.model&&i.id.startsWith(Li.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=ht.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??=at(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-CqpZgLkb.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=ht.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=Ts.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Be.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 yM){const a=go.of(r);s.add(a.key);const c=go.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}=Ei(s.position.altitudeDeg,s.position.azimuthDeg,ys),[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,ht.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):m0(-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*ei)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*ei)*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?Ei(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*ei)/Math.cos(t.lat*ei)}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 l1(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(_0(t))||!dt.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=E3(i.scene);n.traverse(s=>{s instanceof yt&&(s.userData.sharedModel=!0)}),dt.applyModelParameters(n,t.modelParameters,i.bindings),dt.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new zs;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?cE[t.kind]:_0(t);if(!(!n||!dt.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 l1(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"&&(oe.glaze(c),hs.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=l1(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||hs.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?re(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&du(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=Xr(s,i),m=dt.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*ei,v=m.x*Math.cos(g)+m.z*Math.sin(g),M=-m.x*Math.sin(g)+m.z*Math.cos(g),w=p.eastM+n.x,y=-p.northM+n.z;r.x=-(w+v),r.z=-(y+M),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ei,-(m.headingDeg+this.indoorLookYawDeg)*ei,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=Xr(p,i),v=this.lampNudges.get(p.id),M=g.eastM+(v?.eastM??0)+n.x+r.x,w=-(g.northM+(v?.northM??0))+n.z+r.z,y=this.terrainMesh,x=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(m.userData.footprintKey!==x){if(p.kind==="wire"){const O=dt.wireGround(p,M,w,g.headingDeg,(P,N)=>this.groundYUnder(P,N));m.userData.footprintGroundY=O.startY,dt.shearWire(m,dt.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(M,w),P=-(g.headingDeg??0)*ei,N=Math.cos(P),k=Math.sin(P);m.userData.footprintGroundY=O,Te.drape(dt.bodyOf(m),(B,W)=>this.groundYUnder(M+B*N+W*k,w-B*k+W*N)-O)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,M,w,g.headingDeg,g.altitudeM);m.userData.footprintKey=x}const E=g.altitudeM>ht.AIRBORNE_M&&Math.hypot(M,w)<ht.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,S=p.id.startsWith(Li.ID_PREFIX)?ht.trafficHeight(g.altitudeM,m.userData.footprintGroundY):E+g.altitudeM;if(m.position.set(M,S,w),p.kind==="crop"){const O=Math.hypot(M,w);m.visible=O<=K9}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*ei);const D=yT(p,i);if(D!==void 0&&ht.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const O=this.terrainMesh,P=[O?.geometry.uuid,M-(O?.position.x??0),w-(O?.position.z??0),m.position.y-(O?.position.y??0),g.headingDeg,g.altitudeM].map(N=>typeof N=="number"?N.toFixed(4):N).join(":");m.userData.cropGroundKey!==P&&(dt.fitCropToGround(m,(N,k)=>this.groundYUnder(N,k)+g.altitudeM),m.userData.cropGroundKey=P)}if(!_){const O=m.position.distanceTo(this.camera.position);a=Math.max(a,O),O<ht.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(Hp*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=Xr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=dt.sizeOf(s),u=-(a.headingDeg??0)*ei,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=dt.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):P1}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))+ht.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*ht.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 P1;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=oa((e-r)/(a-r)*(s-1),0,s-1),u=oa((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return P1;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,m=u-f,g=(x,b)=>n.getY(x*s+b),v=g(f,d),M=g(f,d+1),w=g(f+1,d),y=g(f+1,d+1);return p+m<=1?v+(M-v)*p+(w-v)*m:y+(w-y)*(1-p)+(M-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return dt.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=Ks.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?Ks.NONE:this.perception??Ks.NONE;if(ki.uColorVision.value.set(...i.colorMatrix),ki.uContrast.value=i.contrastGain,!t){ki.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";ki.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,ht.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),h!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(h=Math.min(h,ht.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);ki.uMediumExposure.value=u,ki.uPhoneStrength.value=n&&c!==void 0&&c>0?Lr.strengthFor(Lr.MID_GREY*u*e*c):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new T;let r=0,a=0;for(const{position:c,luminanceCdM2: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/(ht.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&&dt.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"?lE(n,t):void 0,c=a!==void 0?ml.lamps(a):Sm(n,t,this.lastAstronomy?.sun.altitudeDeg);dt.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??=at(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-B4RR270O.js");return{HeadlightSystem:t}},[],import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new T(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=dt.sizeOf(t).lengthM,r=e.getWorldPosition(new T).addScaledVector(n,s/2-F9);r.y+=k9;const a=dt.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*U9,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?ml.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new T(Math.sin(i),0,-Math.cos(i)),s=new T(n.x*fS,this.camera.position.y-B9,n.z*fS);this.headlightSystem.aim("observer",e,s,n,z9,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=dt.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=dS*dt.lampShare(n),c=new CA(16764006,a*this.relativeScale,H9);n?.colorTemperatureK&&c.color.setRGB(...dt.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;dt.setLitWindowShare(t?$n.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=Gs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Bt.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=an.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,hS,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<y0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=hS/ys*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ei(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ei(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(oa(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?oa(e.separationDeg*n*ei/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 T(s.x,s.y,s.z).normalize(),moon:new T(d.x,d.y,d.z).normalize(),sunRadiusRad:i*ei,moonRadiusRad:f*ei};const p=.01,m=(M,w)=>Ei(t.sun.altitudeDeg+M,t.sun.azimuthDeg+w,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},v={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new kh(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??ht.relativeSkyOf(MM(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),Vt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??dS)*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.hazeOpticalDepth()??Dt.DEFAULT_AEROSOL_OPTICAL_DEPTH)*Dt.aerosolDensity(this.siteElevationM+this.observerElevationM),n=this.cloudTransmission(t),s=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),r=Be.aureoleScale(i,Be.airMass(t.altitudeDeg))*n,a=Be.coronaScale(s),c=Be.illuminanceOf(t.magnitude),l=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),r.toExponential(2),a.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(l===this.lunarDiffractionKey)return;this.lunarDiffractionKey=l,this.lunarDiffraction||(this.lunarDiffraction=new Ly,this.celestialGroup.add(this.lunarDiffraction.object));const h=Be.profile(Be.HAZE_COARSE_MODE),u=Be.profile(Be.CLOUD_DROPLETS),d=MN(t.altitudeDeg),f=new Float32Array(Be.STEPS*3);let p=0;for(let M=0;M<Be.STEPS;M++){const w=M*3,y=[0,1,2].map(b=>c*d[b]*(r*h[w+b]+a*u[w+b])),x=Gs.shown(y,Gs.luminanceOf(y),(b,E)=>e.relativeOfLuminance(b,E));f.set(x,w),p=Math.max(p,Gs.response(x))}const{x:m,y:g,z:v}=Ei(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(p>1/200?{x:m,y:g,z:v}:void 0,f)}applyAir(){this.scene.fog instanceof yc||(this.scene.fog=new yc),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)}hazeOpticalDepth(){return ls.aerosolOpticalDepthOf(this.weather,this.siteElevationM)}restateHaze(){this.air=ls.of(this.weather,this.siteElevationM),this.applyAir();const t=this.hazeOpticalDepth(),e=rl.OPTICAL_DEPTH_STEP;this.scatteredSky?.setConditions({aerosolOpticalDepth:t===void 0?void 0:Math.round(t/e)*e}),this.pumpScatteredSky()}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.weather.visibilityKm!==void 0&&this.restateHaze(),this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,ht.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:an.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?an.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?W9:V9),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 WN(E1),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):m0(-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=`${Li.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(e))continue;const s=this.screenPointOf(new T().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(Wp*this.camera.fov*Math.PI/180);let s,r=n;const a=new T;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(Li.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(Wp*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>=nd,s=!n&&t.moon.altitudeDeg>=nd,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ei)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?Vb.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=nd&&(h=t.moon,u=Vb.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*ei)),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 b=Be.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)g[I]=b*E[I]*m*c,this.cloudBeam[I]=b*E[I];const{x:S,y:A,z:_}=Ei(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(S,A,_),u>0){const I=Be.illuminanceOf(h.magnitude)*i,D=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),O=h===r?f:this.cloudTransmission(h);for(let P=0;P<3;P++)a[P]=I*D[P]*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 b=this.skyCloudTransmission(),E=e.skyIrradiance,S=[0,1,2].map(_=>E[_]*b+g[_]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const A=Jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(S[0]+a[0]*d),A*(S[1]+a[1]*d),A*(S[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:w,z:y}=Ei(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(M,w,y),this.celestialLight.shadow.normalBias=_1*oa(w/R9,.1,1),this.placeShadowFrustum();const x=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/x,a[1]/x,a[2]/x),this.celestialLight.intensity=x,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=Ts.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Be.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=ht.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 Rr||r instanceof ec)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=ht.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new T(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=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=T9;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Xp+5,i.near=this.shadowLightDistanceM-Xp,i.far=this.shadowLightDistanceM+Xp,i.updateProjectionMatrix(),e.bias=-.004/(2*Xp),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!==ht.CABIN_SKY_SHARE&&(r.envMapIntensity=ht.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(_9,Math.max(Za,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(uh,e*(uh/Za));this.shadowLightDistanceM=Math.max(ys,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-A1/(2*s);const r=e>2*Za?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Za;shadowLightDistanceM=ys;shadowUp=new T(0,1,0);shadowAxisX=new T;shadowAxisY=new T;shadowWorld=new T;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*ei,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new T(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Bt.semiSaturation(Bt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new kn,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}=Ei(t.altitudeDeg,t.azimuthDeg,1);return{direction:new T(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=_i.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 m0(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.references?.release(),this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+ht.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.scatteredSky?.invalidate(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;if(this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e),!this.pixelRatioHeld){const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}}this.drawIfDirty()}get maxPixelRatio(){return this.resolution.maximum}pixelRatioHeld=!1;holdPixelRatio(t){this.pixelRatioHeld=t!==void 0;const e=t??this.resolution.maximum;this.renderer.getPixelRatio()!==e&&this.applyPixelRatio(e)}async controlFrame(){await this.loadControlPasses(),this.render();const t=this.drawn;return this.drawIfDirty(),this.drawn===t?void 0:{image:this.renderer.domElement.toDataURL("image/png"),...this.drawControlPasses()}}async loadControlPasses(){if(this.controlPasses)return;const{ControlPasses:t}=await at(async()=>{const{ControlPasses:e}=await import("./ControlPasses-BxgSO3B9.js");return{ControlPasses:e}},[],import.meta.url);this.controlPasses??=new t}drawControlPasses(){if(!this.controlPasses)throw new Error("The control passes are not loaded: see loadControlPasses");return this.controlPasses.draw({renderer:this.renderer,scene:this.scene,camera:this.camera,equidistant:this.usableEquidistantPass(),sky:[this.celestialGroup,...this.pointLayerHost.clouds(),...this.lensFlare?[this.lensFlare.mesh]:[]],isSolid:t=>ht.isSolidSurface(t),drawPhenomena:t=>this.renderPhenomenaPass(t)})}controlPasses;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&&du(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Xr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=dt.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 hs(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 ir),...[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:hs.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,ht.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new Oh,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>Ei(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(ht.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>=nd?t.sun:t.moon.altitudeDeg>=nd?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 Nr;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?Ei(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??ht.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>ht.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(ki.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:Gs.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>he.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new he,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 he,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(ki.uRetina.value=this.retina.texture,ki.uRetinaOn.value=1,ki.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)*ei,-(n?.headingDeg??0)*ei,(n?.rollDeg??0)*ei,"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:Gs.luminanceOf(l.lux)})}return a}historicQuaternion=new es;historicEuler=new Yr;historicDirection=new T;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<ht.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,o7);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(),dt.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?[EM]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},zs.INTERVAL_MS)),ki.uRodShare.value=this.scatteredSky?.rodShare??0,ki.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);ki.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 ir&&e.userData.pointSource||e instanceof yt&&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(b1),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(_3),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 Is({blending:Ml,blendSrc:Ta,blendDst:Ta,blendSrcAlpha:Ta,blendDstAlpha:Ta,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??=at(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-BRTCOQHk.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 T)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}get areReferencesShown(){return this.referencesShown}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const 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);ht.markDecorDepth(h,u),u&&c++}c>0&&(t.layers.set(x1),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(EM),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new Cm;phenomenaViewProjection=new Gt;occluderSphere=new Tr;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 Je().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new Tr).applyMatrix4(new Gt().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=ht.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 jn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new Is({colorWrite:!1,side:Tn});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(ht.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*ei}static isSolidSurface(t){if(!(t instanceof yt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==Cn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof yt))return;e&&ht.isSolidSurface(i)?i.layers.enable(x1):i.layers.disable(x1)})}startExposure(){this.cancelExposure(),this.references?.hold(this.camera),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 rN(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()+ht.EXPOSURE_BUDGET_MS,s=ht.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(){ki.uRodShare.value=this.scatteredSky?.rodShare??0,ki.uHasOverlay.value=1,ki.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 hr,n=new ur(-1,1,1,-1,0,2),s=Yp/(mS*Math.tan(gS*ei/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new T).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new Uu(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 Je,i=new T,n=this.camera.getWorldDirection(new T),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<ht.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 Ed(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,ki.uMediumExposure.value,this.sunBeyondPicture())}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new tt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Di(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 Ny(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 Ni(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=ht.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 T)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ni.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*ei);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new T;screenPointQuaternion=new es;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-ht.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=ke.offFrameShare(Math.atan(Math.hypot(s.x*a,s.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI,this.ghostOptics.reachDeg);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(cS),this.camera.layers.set(cS),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 yS)this.isSunOccluded(e[0],e[1])||t++;return t/yS.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 xo));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?ht.VEIL_SAMPLES:ht.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 ks;veilTargetScratch=new T;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const v=t.x+e.x*g-s.position.x,M=t.z+e.z*g-s.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const 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 w=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(g<w||g>y)return!1;continue}const x=(w-g)/v,b=(y-g)/v;d=Math.max(d,Math.min(x,b)),f=Math.min(f,Math.max(x,b))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const v=d+(f-d)*g/m,M=t.x+e.x*v,w=t.y+e.y*v,y=t.z+e.z*v;if(w<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=Gp;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=>ht.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=I9*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new T).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=ht.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(oa(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=A9*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?ht.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new Je,d=new T;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new T).length()/2,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const v=Math.acos(Math.min(1,m.normalize().dot(n))),M=Math.atan(p/g);if(M>r){const w=this.raycaster.intersectObject(f,!0)[0];if(!w||c!==void 0&&c<w.distance)continue}else if(v>r)continue;M<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(Wp*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,Gp)}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 Je;bodyCornerScratch=new T;decorFrameScratch=new Gt;decorPartMatrix=new Gt;decorPartScratch=new Je;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const i=this.decorFrameScratch.copy(e.matrixWorld).invert(),n=this.bodyBoxScratch.makeEmpty();if(e.traverse(l=>{const h=l.geometry;!h||!l.visible||(h.boundingBox||h.computeBoundingBox(),h.boundingBox&&n.union(this.decorPartScratch.copy(h.boundingBox).applyMatrix4(this.decorPartMatrix.multiplyMatrices(i,l.matrixWorld))))}),n.isEmpty())return;let s=1/0,r=1/0,a=-1/0,c=-1/0;for(let l=0;l<8;l++){const h=this.bodyCornerScratch.set(l&1?n.max.x:n.min.x,l&2?n.max.y:n.min.y,l&4?n.max.z:n.min.z).applyMatrix4(e.matrixWorld),u=this.screenPointOf(h.sub(this.camera.position).normalize());if(!u)return;s=Math.min(s,u.ndcX),a=Math.max(a,u.ndcX),r=Math.min(r,u.ndcY),c=Math.max(c,u.ndcY)}return{minX:s,minY:r,maxX:a,maxY:c}}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*ei/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 Hr;decorHitScratch=new T;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&(s.transparent&&s.opacity<ht.SEE_THROUGH_BELOW||s instanceof xo))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=ht.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 El().copy(n).applyMatrix4(new Gt().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new T(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,ht.RAILWAY_PICK_ABOVE_M))return;const c=ht.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-ht.RAILWAY_GROUND_MARGIN_M,Gp))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:ht.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(Wp*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,Gp))return;const c=ht.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())dt.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new T;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<ht.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 hn(Hp,32,16),i=e.attributes.position,n=e.getAttribute("color")??new pe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=m3(i.getX(r),i.getY(r),i.getZ(r)),l=mN(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 Is({vertexColors:!0,side:zi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new yt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=lS(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new xy(this.groundRadius,48),i=new Rr({color:new rt(S1,S1,S1),fog:!0});yc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new yt(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=Ei(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-Fe.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*O9);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Fe.iceAlphaAt(i,$p,r,this.cloudFieldOffset)*P9),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<y0){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}=Ei(e.altitudeDeg,e.azimuthDeg,ys),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,s,l),u=ht.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/ys)**2,p=[0,1,2].map(g=>u[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(ht.BRIGHTEST_RELATIVE,g));d instanceof yt||(this.disposeMesh(d),d=new yt(new hn(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 ir)){this.disposeMesh(d);const m=new be;m.setAttribute("position",new ye(new Float32Array(3),3)),m.setAttribute("color",new ye(new Float32Array(3),3)),d=new ir(m,Vt.material(iu[iu.length-1].size,!1)),Vt.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/ys*(180/Math.PI),ht.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=VN(),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<y0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ei(t.altitudeDeg,t.azimuthDeg,ys),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??wa.MEAN_RADIUS_DEG,h=ys*Math.tan(l*ei),u=Math.max(oa(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/ys)**2,d=new rt(...c.map(m=>Math.min(ht.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(oa(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Uu?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=kS(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Uu(new c0({map:kS(t.phase),color:d,fog:!1,blending:Cn,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=D9){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 ht.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,Vt.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=Be.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Gs.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 c0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Uu(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(An.radiusDeg(An.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new An(`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=Ch(t.magnitude,e),s=Qg(n);this.cometKey=i,this.setBodyMesh(i,t.position,T1*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new er(ys),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Zi,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:$p},0);return}const s=this.lowerCloudCover(),r=Ee.deckLitUntilDeg(Ee.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?fe.SUN_MAGNITUDE:e.magnitude),l=Ee.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=Ei(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??$p},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??i_,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new sl,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?fe.SUN_MAGNITUDE:e.magnitude,C9),c=tr.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}=Ei(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 qo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=kr.galactic(i,n),r=ht.directionOf(s.centre),a=ht.directionOf(s.rotation),c=ht.directionOf(s.pole),l=new de().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=ht.directionOf(kr.eclipticPole(i,n)),u=ht.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:ht.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:_t.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new T(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ei(t.altitudeDeg,t.azimuthDeg,1);return new T(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=Ch(n.magnitude,e),a=Qg(r);this.setBodyMesh(s,n.position,T1*(.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=Ch(n.magnitude,e),r=Qg(s),a=u7[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),l=T1*(.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 Br(n,s),a=F1(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<uS)continue;const{x:p,y:m,z:g}=Ei(d,f,E1);c.push({x:p,y:m,z:g,brightness:Ch(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Be.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of yN){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<uS)continue;const{x:f,y:p,z:m}=Ei(u,d,E1);this.namedStars.push({star:h,direction:new T(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=iu.map((h,u)=>{const d=c.filter(x=>Py(x.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((x,b)=>{f[b*3]=x.x,f[b*3+1]=x.y,f[b*3+2]=x.z,p[b]=x.brightness,m.set(x.illuminance,b*3),g[b]=x.phase,v[b]=x.speedFactor});const M=new be;M.setAttribute("position",new ye(f,3)),M.setAttribute("seed",new ye(g.map(x=>x/(2*Math.PI)),1));const w=new ye(new Float32Array(d.length*3),3);M.setAttribute("color",w);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new ir(M,Vt.material(h.size)),Vt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:p,illuminance:m,phase:g,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Vt.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 eu(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(Uc[0]+(C1[0]-Uc[0])*e,Uc[1]+(C1[1]-Uc[1])*e,Uc[2]+(C1[2]-Uc[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}=fM(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=pM(R1);this.cloudMesh=new yt(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}=fM(new rt(...Uc),t,$p,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new yt(pM(R1*1.04),e),this.cirrusMesh.renderOrder=wS-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?eu.deckOrder(!0,0,1):wS}cloudLayerOffset(){const e=((this.weather.cloudBaseM??UM)-this.observerElevationM)*I1;return Math.sign(e||1)*Math.max(Math.abs(e),Y9)}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*k1*this.relativeScale/Math.PI,l=new rt(e[0]+ia.r*c,e[1]+ia.g*c,e[2]+ia.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 e7(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,N1],[this.rainSplashSystem?.points,zc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:O1[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=ES(L1(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=O1[t],i=e.poolSize,n=F1(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 w=0;w<i;w++){const y=n()*Math.PI*2,x=n()*e.radiusM;s[w*3]=Math.cos(y)*x,s[w*3+1]=gh+n()*(e.topYM-gh),s[w*3+2]=Math.sin(y)*x,r[w]=n()*Math.PI*2,a[w]=.7+n()*.6,c[w]=.6+n()*.8,l[w]=.4+n()*1.2}const m=new be;m.setAttribute("position",new ye(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:d7(t)},uNearFocusDistance:{value:RS},uHazeDistance:{value:e.radiusM*IS}},v=new De({uniforms:g,vertexShader:M7,fragmentShader:y7,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const M=new ir(m,v);M.renderOrder=D1,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=O1[i];if(this.precipitationUniforms?.uColor.value.copy(ht.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*ei,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,w=i==="hail"&&f&&p&&m&&g&&v;for(let y=0,x=0;y<c.length;y+=3,x++){if(w&&f[x]>0){if(f[x]-=e,f[x]<=0){const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A,f[x]=0}else{const S=1-f[x]/m[x];c[y+1]=gh+Math.sin(Math.PI*S)*p[x],c[y]=Kp(c[y]+(r+g[x])*e,n.radiusM),c[y+2]=Kp(c[y+2]+(a+v[x])*e,n.radiusM)}continue}let b=0,E=0;if(M){const S=n7*u[x],A=s7*d[x];b=Math.sin(t*S*Math.PI*2+l[x])*A,E=Math.sin(t*S*Math.PI*2+l[x]+Math.PI/2)*A}if(c[y]+=(r+b)*e,c[y+1]-=n.fallSpeedMPerS*h[x]*e,c[y+2]+=(a+E)*e,c[y]=Kp(c[y],n.radiusM),c[y+2]=Kp(c[y+2],n.radiusM),c[y+1]<gh){if(w){p[x]=NS*(.2+Math.random()*1.6),m[x]=r7*(.5+Math.random()),f[x]=m[x];const _=Math.random()*Math.PI*2,I=a7*(p[x]/NS);g[x]=Math.cos(_)*I,v[x]=Math.sin(_)*I,c[y+1]=gh;continue}const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=L1(this.weather.precipitationIntensity);this.rainSystem=BN({count:N1,radiusM:sd,heightM:q9,bottomYM:xS,overallSpeed:Z9,color:SS.clone(),opacity:.85,visibleCount:this.precipitationCount(N1),speedStreak:ES(t),pixelSize:CS,seed:9001,nearFocusDistanceM:RS,hazeDistanceM:sd*IS,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=D1,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=F1(4242),e=new Float32Array(zc*3),i=new Float32Array(zc),n=new Float32Array(zc),s=new Float32Array(zc);for(let h=0;h<zc;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*sd;e[h*3]=Math.cos(u)*d,e[h*3+1]=xS,e[h*3+2]=Math.sin(u)*d,n[h]=LS(AS,_S),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new be;r.setAttribute("position",new ye(e,3));const a=new ye(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(zc));const c=new De({uniforms:{uMaxSize:{value:t7},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:TS.clone()},uTexture:{value:m7()}},vertexShader:g7,fragmentShader:v7,transparent:!0,depthWrite:!1}),l=new ir(r,c);l.renderOrder=D1,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*ei;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-L1(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(ht.litBySky(SS,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(ht.litBySky(TS,this.baseFogColor));const n=this.weather.windDirectionDeg*ei,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=sd,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=OS+(1-OS)*(1-l),u=PS+(1-PS)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=CS*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())*sd;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=LS(AS,_S),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,(l7/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*k1*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+ia.r*l,this.airlight[1]+ia.g*l,this.airlight[2]+ia.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*h7;r.setRGB(1+c*ia.r,1+c*ia.g,1+c*ia.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*k1*this.relativeScale,e){const{x:c,y:l,z:h}=Ei(25,e.azimuthDeg,ys);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new Zo(ys*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=G9.map(t=>{const e=ul.point(t,this.compassPoints),i=new c0({map:w7(e),depthTest:!1,fog:!1}),n=new Uu(i),{x:s,y:r,z:a}=Ei(0,t,mS);return n.position.set(s,r,a),n.scale.set(Yp,Yp,1),n.renderOrder=X9,n.layers.set(b1),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=gS*Math.PI/360,i=Yp*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 ei=Math.PI/180;function oa(o,t,e){return Math.max(t,Math.min(e,o))}function LS(o,t){return o+Math.random()*(t-o)}function Kp(o,t){return(o%(t*2)+t*3)%(t*2)-t}let qp,Zp;function d7(o){switch(o){case"snow":return f7();case"hail":return p7()}}function f7(){if(qp)return qp;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),qp=new Tc(t),qp}function p7(){if(Zp)return Zp;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),Zp=new Tc(t),Zp}let Jp;function m7(){if(Jp)return Jp;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),Jp=new Tc(t),Jp}const g7=`
|
|
9587
|
+
`,transparent:!0,blending:Cn,depthWrite:!1,side:zi,fog:!1});this.object=new yt(new hn(Ly.RADIUS,128,32,0,Math.PI*2,0,Be.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<Be.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Gn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=Gn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class om{constructor(t){this.generator=t}static SIZE=128;target=new pf(om.SIZE,{type:Ye,generateMipmaps:!0,minFilter:cr,magFilter:Me});camera=new Iy(.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 hs{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){hs.install(),this.generator=new rM(t),this.eye=new om(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=hs.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 om(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]),hs.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),l?.(g.probe.sharp),hs.decor=g.probe.filtered;for(const v of r)hs.reflectOn(v,g.probe);for(const v of n)v.shiny||hs.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 T;static reflectOn(t,e={filtered:hs.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof xo?e.sharp&&s.setSurroundings(e.sharp):s instanceof ec&&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(hs.installed)return;hs.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!ue.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}ue.lights_fragment_maps=ue.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const T3=0,EL=1,AL=2,Wb=2,h1=1.25,Xb=1,ps=32,Rn=ps/4,R3=65535,v0=Math.pow(2,-24),ky=Symbol("SKIP_GENERATION"),I3={strategy:T3,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[ky]:!1};function ji(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 AM(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 $b(o,t){t.set(o)}function Yb(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 _p(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 Zu(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 cn(o,t){return t[o+15]===R3}function Vn(o,t){return t[o+6]}function ms(o,t){return t[o+14]}function In(o){return o+Rn}function Dn(o,t){const e=t[o+6];return o+e*Rn}function Fy(o,t){return t[o+7]}function u1(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,w=(t+e-v)*6;M<w;M+=6){const y=o[M+0],x=o[M+1],b=y-x,E=y+x;b<s&&(s=b),E>c&&(c=E),y<u&&(u=y),y>p&&(p=y);const S=o[M+2],A=o[M+3],_=S-A,I=S+A;_<r&&(r=_),I>l&&(l=I),S<d&&(d=S),S>m&&(m=S);const D=o[M+4],O=o[M+5],P=D-O,N=D+O;P<a&&(a=P),N>h&&(h=N),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 io=32,_L=(o,t)=>o.candidate-t.candidate,Ho=new Array(io).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Tp=new Float32Array(6);function TL(o,t,e,i,n,s){let r=-1,a=0;if(s===T3)r=AM(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(s===EL)r=AM(o),r!==-1&&(a=RL(e,i,n,r));else if(s===AL){const c=Zu(o);let l=h1*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)/io;if(n<io/4){const M=[...Ho];M.length=n;let w=0;for(let x=u;x<d;x+=6,w++){const b=M[w];b.candidate=e[x+2*f],b.count=0;const{bounds:E,leftCacheBounds:S,rightCacheBounds:A}=b;for(let _=0;_<3;_++)A[_]=1/0,A[_+3]=-1/0,S[_]=1/0,S[_+3]=-1/0,E[_]=1/0,E[_+3]=-1/0;_p(x,e,E)}M.sort(_L);let y=n;for(let x=0;x<y;x++){const b=M[x];for(;x+1<y&&M[x+1].candidate===b.candidate;)M.splice(x+1,1),y--}for(let x=u;x<d;x+=6){const b=e[x+2*f];for(let E=0;E<y;E++){const S=M[E];b>=S.candidate?_p(x,e,S.rightCacheBounds):(_p(x,e,S.leftCacheBounds),S.count++)}}for(let x=0;x<y;x++){const b=M[x],E=b.count,S=n-b.count,A=b.leftCacheBounds,_=b.rightCacheBounds;let I=0;E!==0&&(I=Zu(A)/c);let D=0;S!==0&&(D=Zu(_)/c);const O=Xb+h1*(I*E+D*S);O<l&&(r=f,l=O,a=b.candidate)}}else{for(let y=0;y<io;y++){const x=Ho[y];x.count=0,x.candidate=p+v+y*v;const b=x.bounds;for(let E=0;E<3;E++)b[E]=1/0,b[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/v);E>=io&&(E=io-1);const S=Ho[E];S.count++,_p(y,e,S.bounds)}const M=Ho[io-1];$b(M.bounds,M.rightCacheBounds);for(let y=io-2;y>=0;y--){const x=Ho[y],b=Ho[y+1];Yb(x.bounds,b.rightCacheBounds,x.rightCacheBounds)}let w=0;for(let y=0;y<io-1;y++){const x=Ho[y],b=x.count,E=x.bounds,A=Ho[y+1].rightCacheBounds;b!==0&&(w===0?$b(E,Tp):Yb(E,Tp,Tp)),w+=b;let _=0,I=0;w!==0&&(_=Zu(Tp)/c);const D=n-w;D!==0&&(I=Zu(A)/c);const O=Xb+h1*(_*w+I*D);O<l&&(r=f,l=O,a=x.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function RL(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 d1{constructor(){this.boundingData=new Float32Array(6)}}function IL(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 D3,M0,_M,C3;const DL=Math.pow(2,32);function TM(o){return"count"in o?1:1+TM(o.left)+TM(o.right)}function CL(o,t,e){return D3=new Float32Array(e),M0=new Uint32Array(e),_M=new Uint16Array(e),C3=new Uint8Array(e),RM(o,t)}function RM(o,t){const e=o/4,i=o/2,n="count"in t,s=t.boundingData;for(let r=0;r<6;r++)D3[e+r]=s[r];if(n)return t.buffer?(C3.set(new Uint8Array(t.buffer),o),o+t.buffer.byteLength):(M0[e+6]=t.offset,_M[i+14]=t.count,_M[i+15]=R3,o+ps);{const{left:r,right:a,splitAxis:c}=t,l=o+ps;let h=RM(l,r);const u=o/ps,f=h/ps-u;if(f>DL)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return M0[e+6]=f,M0[e+7]=c,RM(h,a)}}function OL(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 d1;return u1(t,e,i,g.boundingData,p),M(g,e,i,p),g;function v(w){u&&u((w-s.offset)/s.count)}function M(w,y,x,b=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const S=x>l;if(x<=c&&!S||E>=r)return v(y+x),w.offset=y,w.count=x,w;const A=TL(w.boundingData,b,t,y,x,h);let _=A.axis===-1?-1:IL(d,f,t,y,x,A);if(A.axis===-1||_===y||_===y+x){if(!S)return v(y+x),w.offset=y,w.count=x,w;A.axis=Math.max(0,AM(w.boundingData)),_=y+Math.max(1,Math.floor(x/2))}w.splitAxis=A.axis;const I=new d1,D=y,O=_-y;w.left=I,u1(t,D,O,I.boundingData,p),M(I,D,O,p,E+1);const P=new d1,N=_,k=x-O;return w.right=P,u1(t,N,k,P.boundingData,p),M(P,N,k,p,E+1),w}}function PL(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=OL(o,a,c.offset,c.count,t,r),h=TM(l),u=new e(ps*h);return CL(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 NL{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 Hi=new NL;let mc,Fh;const nh=[],Rp=new Uy(()=>new Je);function LL(o,t,e,i,n,s){mc=Rp.getPrimitive(),Fh=Rp.getPrimitive(),nh.push(mc,Fh),Hi.setBuffer(o._roots[t]);const r=IM(0,o.geometry,e,i,n,s);Hi.clearBuffer(),Rp.releasePrimitive(mc),Rp.releasePrimitive(Fh),nh.pop(),nh.pop();const a=nh.length;return a>0&&(Fh=nh[a-1],mc=nh[a-2]),r}function IM(o,t,e,i,n=null,s=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:l}=Hi;let h=o*2;if(cn(h,c)){const d=Vn(o,l),f=ms(h,c);return ji(o,a,mc),i(d,f,!1,r,s+o/Rn,mc)}else{let _=function(D){const{uint16Array:O,uint32Array:P}=Hi;let N=D*2;for(;!cn(N,O);)D=In(D),N=D*2;return Vn(D,P)},I=function(D){const{uint16Array:O,uint32Array:P}=Hi;let N=D*2;for(;!cn(N,O);)D=Dn(D,P),N=D*2;return Vn(D,P)+ms(N,O)};const d=In(o),f=Dn(o,l);let p=d,m=f,g,v,M,w;if(n&&(M=mc,w=Fh,ji(p,a,M),ji(m,a,w),g=n(M),v=n(w),v<g)){p=f,m=d;const D=g;g=v,v=D,M=w}M||(M=mc,ji(p,a,M));const y=cn(p*2,c),x=e(M,y,g,r+1,s+p/Rn);let b;if(x===Wb){const D=_(p),P=I(p)-D;b=i(D,P,!0,r+1,s+p/Rn,M)}else b=x&&IM(p,t,e,i,n,s,r+1);if(b)return!0;w=Fh,ji(m,a,w);const E=cn(m*2,c),S=e(w,E,v,r+1,s+m/Rn);let A;if(S===Wb){const D=_(m),P=I(m)-D;A=i(D,P,!0,r+1,s+m/Rn,w)}else A=S&&IM(m,t,e,i,n,s,r+1);return!!A}}const Rd=new Hi.constructor,cm=new Hi.constructor,Jo=new Uy(()=>new Je),sh=new Je,rh=new Je,f1=new Je,p1=new Je;let m1=!1;function kL(o,t,e,i){if(m1)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");m1=!0;const n=o._roots,s=t._roots;let r,a=0,c=0;const l=new Gt().copy(e).invert();for(let h=0,u=n.length;h<u;h++){Rd.setBuffer(n[h]),c=0;const d=Jo.getPrimitive();ji(0,Rd.float32Array,d),d.applyMatrix4(l);for(let f=0,p=s.length;f<p&&(cm.setBuffer(s[f]),r=Or(0,0,e,l,i,a,c,0,0,d),cm.clearBuffer(),c+=s[f].byteLength/ps,!r);f++);if(Jo.releasePrimitive(d),Rd.clearBuffer(),a+=n[h].byteLength/ps,r)break}return m1=!1,r}function Or(o,t,e,i,n,s=0,r=0,a=0,c=0,l=null,h=!1){let u,d;h?(u=cm,d=Rd):(u=Rd,d=cm);const f=u.float32Array,p=u.uint32Array,m=u.uint16Array,g=d.float32Array,v=d.uint32Array,M=d.uint16Array,w=o*2,y=t*2,x=cn(w,m),b=cn(y,M);let E=!1;if(b&&x)h?E=n(Vn(t,v),ms(t*2,M),Vn(o,p),ms(o*2,m),c,r+t/Rn,a,s+o/Rn):E=n(Vn(o,p),ms(o*2,m),Vn(t,v),ms(t*2,M),a,s+o/Rn,c,r+t/Rn);else if(b){const S=Jo.getPrimitive();ji(t,g,S),S.applyMatrix4(e);const A=In(o),_=Dn(o,p);ji(A,f,sh),ji(_,f,rh);const I=S.intersectsBox(sh),D=S.intersectsBox(rh);E=I&&Or(t,A,i,e,n,r,s,c,a+1,S,!h)||D&&Or(t,_,i,e,n,r,s,c,a+1,S,!h),Jo.releasePrimitive(S)}else{const S=In(t),A=Dn(t,v);ji(S,g,f1),ji(A,g,p1);const _=l.intersectsBox(f1),I=l.intersectsBox(p1);if(_&&I)E=Or(o,S,e,i,n,s,r,a,c+1,l,h)||Or(o,A,e,i,n,s,r,a,c+1,l,h);else if(_)if(x)E=Or(o,S,e,i,n,s,r,a,c+1,l,h);else{const D=Jo.getPrimitive();D.copy(f1).applyMatrix4(e);const O=In(o),P=Dn(o,p);ji(O,f,sh),ji(P,f,rh);const N=D.intersectsBox(sh),k=D.intersectsBox(rh);E=N&&Or(S,O,i,e,n,r,s,c,a+1,D,!h)||k&&Or(S,P,i,e,n,r,s,c,a+1,D,!h),Jo.releasePrimitive(D)}else if(I)if(x)E=Or(o,A,e,i,n,s,r,a,c+1,l,h);else{const D=Jo.getPrimitive();D.copy(p1).applyMatrix4(e);const O=In(o),P=Dn(o,p);ji(O,f,sh),ji(P,f,rh);const N=D.intersectsBox(sh),k=D.intersectsBox(rh);E=N&&Or(A,O,i,e,n,r,s,c,a+1,D,!h)||k&&Or(A,P,i,e,n,r,s,c,a+1,D,!h),Jo.releasePrimitive(D)}}return E}const g1=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(;!cn(r,e);)s=In(s),r=s*2;return Vn(s,t)},this.getRangeEnd=s=>{let r=s*2;for(;!cn(r,e);)s=Dn(s,t),r=s*2;return Vn(s,t)+ms(r,e)};const n=(s,r,a)=>{const c=r*2,l=cn(c,e);if(!s(a,l,r)&&!l){const u=In(r),d=Dn(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=Fy(c,t);return s(r,a,new Float32Array(o,c*4,6),l)}})}}},Kb=new Je,ah=new Float32Array(6);class FL{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...I3,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),PL(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,ah,0);const[f,p,m,g,v,M]=ah;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,ah,0);const[a,c,l,h,u,d]=ah,f=(a+h)/2,p=(c+u)/2,m=(l+d)/2,g=(h-a)/2,v=(u-c)/2,M=(d-l)/2,w=(s-n)*6;i[w+0]=f,i[w+1]=g+(Math.abs(f)+g)*v0,i[w+2]=p,i[w+3]=v+(Math.abs(p)+v)*v0,i[w+4]=m,i[w+5]=M+(Math.abs(m)+M)*v0}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/ps;for(let l=0;l<c;l++){const h=Rn*l,u=2*h;cn(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){g1.setBVH(this,e),g1.traverse(t),g1.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/ps;for(let l=c-1;l>=0;l--){const h=l*Rn,u=h*2;if(cn(u,r)){const f=Vn(h,s),p=ms(u,r);this.writePrimitiveRangeBounds(f,p,ah,0),a.set(ah,h)}else{const f=In(h),p=Dn(h,s);for(let m=0;m<3;m++){const g=a[f+m],v=a[f+m+3],M=a[p+m],w=a[p+m+3];a[h+m]=g<M?g:M,a[h+m+3]=v>w?v:w}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{ji(0,new Float32Array(i),Kb),t.union(Kb)}),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=LL(this,u,i,n,e,l),c)break;l+=f.byteLength/ps}return c}bvhcast(t,e,i){let{intersectsRanges:n}=i;return kL(this,t,e,n)}}function UL(){return typeof SharedArrayBuffer<"u"}function zy(o){return o.index?o.index.count:o.attributes.position.count}function zm(o){return zy(o)/3}function zL(o,t=ArrayBuffer){return o>65535?new Uint32Array(new t(4*o)):new Uint16Array(new t(2*o))}function BL(o,t){if(!o.index){const e=o.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=zL(e,i);o.setIndex(new we(n,1));for(let s=0;s<e;s++)n[s]=s}}function HL(o,t,e){const i=zy(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 GL(o,t){return o.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function qb(o,t,e){const i=HL(o,t,e),n=GL(o,e);if(!n.length)return[i];const s=[],r=i.offset,a=i.offset+i.count,c=zy(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 VL(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 WL extends FL{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&&!UL())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={...I3,...e},e[ky]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=qb(e,t.range,i),s=VL(n,t.useSharedArrayBuffer);this._indirectBuffer=s}else BL(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Je))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:qb(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Ao{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}}Ao.prototype.setFromBox=(function(){const o=new T;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 XL=(function(){const o=new T,t=new T,e=new T;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}})(),By=(function(){const o=new tt,t=new T,e=new T;return function(n,s,r,a){XL(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}}}})(),$L=(function(){const o=new T,t=new T,e=new Hr,i=new Eo;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}})(),YL=["x","y","z"],ro=1e-15,Zb=ro*ro;function mr(o){return Math.abs(o)<ro}class Kr extends Hn{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new T),this.satBounds=new Array(4).fill().map(()=>new Ao),this.points=[this.a,this.b,this.c],this.plane=new Hr,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Eo,this.needsUpdate=!0}intersectsSphere(t){return $L(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<ro?g<ro||v<ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):g<ro?v<ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):v<ro&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}Kr.prototype.closestPointToSegment=(function(){const o=new T,t=new T,e=new Eo;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]),By(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)}})();Kr.prototype.intersectsTriangle=(function(){const o=new Kr,t=new Ao,e=new Ao,i=new T,n=new T,s=new T,r=new T,a=new Eo,c=new Eo,l=new T,h=new tt,u=new tt;function d(w,y,x,b){const E=i;!w.isDegenerateIntoPoint&&!w.isDegenerateIntoSegment?E.copy(w.plane.normal):E.copy(y.plane.normal);const S=w.satBounds,A=w.satAxes;for(let D=1;D<4;D++){const O=S[D],P=A[D];if(t.setFromPoints(P,y.points),O.isSeparated(t)||(r.copy(E).cross(P),t.setFromPoints(r,w.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],P=I[D];if(t.setFromPoints(P,w.points),O.isSeparated(t)||(r.crossVectors(E,P),t.setFromPoints(r,w.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}return x&&(b||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),x.start.set(0,0,0),x.end.set(0,0,0)),!0}function f(w,y,x,b,E,S,A,_,I,D,O){let P=A/(A-_);D.x=b+(E-b)*P,O.start.subVectors(y,w).multiplyScalar(P).add(w),P=A/(A-I),D.y=b+(S-b)*P,O.end.subVectors(x,w).multiplyScalar(P).add(w)}function p(w,y,x,b,E,S,A,_,I,D,O){if(E>0)f(w.c,w.a,w.b,b,y,x,I,A,_,D,O);else if(S>0)f(w.b,w.a,w.c,x,y,b,_,A,I,D,O);else if(_*I>0||A!=0)f(w.a,w.b,w.c,y,x,b,A,_,I,D,O);else if(_!=0)f(w.b,w.a,w.c,x,y,b,_,A,I,D,O);else if(I!=0)f(w.c,w.a,w.b,b,y,x,I,A,_,D,O);else return!0;return!1}function m(w,y,x,b){const E=y.degenerateSegment,S=w.plane.distanceToPoint(E.start),A=w.plane.distanceToPoint(E.end);return mr(S)?mr(A)?d(w,y,x,b):(x&&(x.start.copy(E.start),x.end.copy(E.start)),w.containsPoint(E.start)):mr(A)?(x&&(x.start.copy(E.end),x.end.copy(E.end)),w.containsPoint(E.end)):w.plane.intersectLine(E,i)!=null?(x&&(x.start.copy(i),x.end.copy(i)),w.containsPoint(i)):!1}function g(w,y,x){const b=y.a;return mr(w.plane.distanceToPoint(b))&&w.containsPoint(b)?(x&&(x.start.copy(b),x.end.copy(b)),!0):!1}function v(w,y,x){const b=w.degenerateSegment,E=y.a;return b.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<Zb?(x&&(x.start.copy(E),x.end.copy(E)),!0):!1}function M(w,y,x,b){if(w.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=w.degenerateSegment,S=y.degenerateSegment,A=n,_=s;E.delta(A),S.delta(_);const I=i.subVectors(S.start,E.start),D=A.x*_.y-A.y*_.x;if(mr(D))return!1;const O=(I.x*_.y-I.y*_.x)/D,P=-(A.x*I.y-A.y*I.x)/D;if(O<0||O>1||P<0||P>1)return!1;const N=E.start.z+A.z*O,k=S.start.z+_.z*P;return mr(N-k)?(x&&(x.start.copy(E.start).addScaledVector(A,O),x.end.copy(E.start).addScaledVector(A,O)),!0):!1}else return y.isDegenerateIntoPoint?v(w,y,x):m(y,w,x,b);else{if(w.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(w.a)<Zb?(x&&(x.start.copy(w.a),x.end.copy(w.a)),!0):!1:y.isDegenerateIntoSegment?v(y,w,x):g(y,w,x);if(y.isDegenerateIntoPoint)return g(w,y,x);if(y.isDegenerateIntoSegment)return m(w,y,x,b)}}return function(y,x=null,b=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(o.copy(y),o.update(),y=o);const E=M(this,y,x,b);if(E!==void 0)return E;const S=this.plane,A=y.plane;let _=A.distanceToPoint(this.a),I=A.distanceToPoint(this.b),D=A.distanceToPoint(this.c);mr(_)&&(_=0),mr(I)&&(I=0),mr(D)&&(D=0);const O=_*I,P=_*D;if(O>0&&P>0)return!1;let N=S.distanceToPoint(y.a),k=S.distanceToPoint(y.b),B=S.distanceToPoint(y.c);mr(N)&&(N=0),mr(k)&&(k=0),mr(B)&&(B=0);const W=N*k,Q=N*B;if(W>0&&Q>0)return!1;n.copy(S.normal),s.copy(A.normal);const Z=n.cross(s);let nt=0,ot=Math.abs(Z.x);const Ut=Math.abs(Z.y);Ut>ot&&(ot=Ut,nt=1),Math.abs(Z.z)>ot&&(nt=2);const jt=YL[nt],K=this.a[jt],lt=this.b[jt],ct=this.c[jt],V=y.a[jt],Lt=y.b[jt],Xt=y.c[jt];if(p(this,K,lt,ct,O,P,_,I,D,h,a))return d(this,y,x,b);if(p(y,V,Lt,Xt,W,Q,N,k,B,u,c))return d(this,y,x,b);if(h.y<h.x){const kt=h.y;h.y=h.x,h.x=kt,l.copy(a.start),a.start.copy(a.end),a.end.copy(l)}if(u.y<u.x){const kt=u.y;u.y=u.x,u.x=kt,l.copy(c.start),c.start.copy(c.end),c.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(x&&(u.x>h.x?x.start.copy(c.start):x.start.copy(a.start),u.y<h.y?x.end.copy(c.end):x.end.copy(a.end)),!0)}})();Kr.prototype.distanceToPoint=(function(){const o=new T;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Kr.prototype.distanceToTriangle=(function(){const o=new T,t=new T,e=["a","b","c"],i=new Eo,n=new Eo;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]),By(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 Cs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new T,this.max=new T,this.matrix=new Gt,this.invMatrix=new Gt,this.points=new Array(8).fill().map(()=>new T),this.satAxes=new Array(3).fill().map(()=>new T),this.satBounds=new Array(3).fill().map(()=>new Ao),this.alignedSatBounds=new Array(3).fill().map(()=>new Ao),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}}Cs.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}})();Cs.prototype.intersectsBox=(function(){const o=new Ao;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}})();Cs.prototype.intersectsTriangle=(function(){const o=new Kr,t=new Array(3),e=new Ao,i=new Ao,n=new T;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}})();Cs.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}})();Cs.prototype.distanceToPoint=(function(){const o=new T;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Cs.prototype.distanceToBox=(function(){const o=["x","y","z"],t=new Array(12).fill().map(()=>new Eo),e=new Array(12).fill().map(()=>new Eo),i=new T,n=new T;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 w=(g+1)%3,y=(g+2)%3,x=v<<w|M<<y,b=1<<g|v<<w|M<<y,E=f[x],S=f[b];t[m].set(E,S);const _=o[g],I=o[w],D=o[y],O=e[m],P=O.start,N=O.end;P[_]=u[_],P[I]=v?u[I]:d[I],P[D]=M?u[D]:d[I],N[_]=d[_],N[I]=v?u[I]:d[I],N[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 w=n.distanceToSquared(i);if(w<p&&(p=w,c&&c.copy(i),l&&l.copy(n),w<h))return Math.sqrt(w)}for(let g=0;g<12;g++){const v=t[g];for(let M=0;M<12;M++){const w=e[M];By(v,w,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 KL extends Uy{constructor(){super(()=>new Kr)}}const Er=new KL,Ju=new T,v1=new T;function qL(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=>(Ju.copy(t).clamp(h.min,h.max),Ju.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<a&&d<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Ju);const d=t.distanceToSquared(Ju);return d<a&&(v1.copy(Ju),a=d,c=u),d<s}}),a===1/0)return null;const l=Math.sqrt(a);return e.point?e.point.copy(v1):e.point=v1.clone(),e.distance=l,e.faceIndex=c,e}const Ip=parseInt(_f)>=169,ZL=parseInt(_f)<=161,Lc=new T,kc=new T,Fc=new T,Dp=new tt,Cp=new tt,Op=new tt,Jb=new T,jb=new T,Qb=new T,ju=new T;function JL(o,t,e,i,n,s,r,a){let c;if(s===zi?c=o.intersectTriangle(i,e,t,!0,n):c=o.intersectTriangle(t,e,i,s!==Tn,n),c===null)return null;const l=o.origin.distanceTo(n);return l<r||l>a?null:{distance:l,point:n.clone()}}function tS(o,t,e,i,n,s,r,a,c,l,h){Lc.fromBufferAttribute(t,s),kc.fromBufferAttribute(t,r),Fc.fromBufferAttribute(t,a);const u=JL(o,Lc,kc,Fc,ju,c,l,h);if(u){if(i){Dp.fromBufferAttribute(i,s),Cp.fromBufferAttribute(i,r),Op.fromBufferAttribute(i,a),u.uv=new tt;const f=Hn.getInterpolation(ju,Lc,kc,Fc,Dp,Cp,Op,u.uv);Ip||(u.uv=f)}if(n){Dp.fromBufferAttribute(n,s),Cp.fromBufferAttribute(n,r),Op.fromBufferAttribute(n,a),u.uv1=new tt;const f=Hn.getInterpolation(ju,Lc,kc,Fc,Dp,Cp,Op,u.uv1);Ip||(u.uv1=f),ZL&&(u.uv2=u.uv1)}if(e){Jb.fromBufferAttribute(e,s),jb.fromBufferAttribute(e,r),Qb.fromBufferAttribute(e,a),u.normal=new T;const f=Hn.getInterpolation(ju,Lc,kc,Fc,Jb,jb,Qb,u.normal);u.normal.dot(o.direction)>0&&u.normal.multiplyScalar(-1),Ip||(u.normal=f)}const d={a:s,b:r,c:a,normal:new T,materialIndex:0};if(Hn.getNormal(Lc,kc,Fc,d.normal),u.face=d,u.faceIndex=s,Ip){const f=new T;Hn.getBarycoord(ju,Lc,kc,Fc,f),u.barycoord=f}}return u}function eS(o){return o&&o.isMaterial?o.side:o}function Bm(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,w=d.length;M<w;M++){const{start:y,count:x,materialIndex:b}=d[M];if(v>=y&&v<y+x){const E=eS(t[b]),S=tS(e,f,p,m,g,c,l,h,E,s,r);if(S)if(S.faceIndex=i,S.face.materialIndex=b,n)n.push(S);else return S}}}else{const v=eS(t),M=tS(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 xn(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 jL(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++)Bm(c,t,e,h,s,r,a)}function QL(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=Bm(a,t,e,u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function t9(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,xn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function e9(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(cn(m,a)){const g=Vn(d,r),v=ms(m,a);let M=1/0,w=1/0,y=1/0,x=-1/0,b=-1/0,E=-1/0;for(let S=3*g,A=3*(g+v);S<A;S++){let _=i[S];const I=n.getX(_),D=n.getY(_),O=n.getZ(_);I<M&&(M=I),I>x&&(x=I),D<w&&(w=D),D>b&&(b=D),O<y&&(y=O),O>E&&(E=O)}return c[d+0]!==M||c[d+1]!==w||c[d+2]!==y||c[d+3]!==x||c[d+4]!==b||c[d+5]!==E?(c[d+0]=M,c[d+1]=w,c[d+2]=y,c[d+3]=x,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=In(d),v=Dn(d,r);let M=p,w=!1,y=!1;if(t){if(!M){const _=g/Rn+f/ps,I=v/Rn+f/ps;w=t.has(_),y=t.has(I),M=!w&&!y}}else w=!0,y=!0;const x=M||w,b=M||y;let E=!1;x&&(E=u(g,f,M));let S=!1;b&&(S=u(v,f,M));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],P=c[I+3],N=c[D],k=c[D+3];c[d+_]=O<N?O:N,c[d+_+3]=P>k?P:k}return A}}}function Ec(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],w=t[o+1],y=t[o+3+1],x=t[o+2],b=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=(w-m)*d,c=(y-m)*d):(a=(y-m)*d,c=(w-m)*d),s>c||a>r||((a>s||isNaN(s))&&(s=a),(c<r||isNaN(r))&&(r=c),f>=0?(l=(x-g)*f,h=(b-g)*f):(l=(b-g)*f,h=(x-g)*f),s>h||l>r)?!1:((l>s||s!==s)&&(s=l),(h<r||r!==r)&&(r=h),s<=n&&r>=i)}function i9(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;Bm(c,t,e,d,s,r,a)}}function n9(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=Bm(a,t,e,c?c[u]:u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function s9(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),xn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function r9(o,t,e,i,n,s,r){Hi.setBuffer(o._roots[t]),DM(0,o,e,i,n,s,r),Hi.clearBuffer()}function DM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Hi,h=o*2;if(cn(h,c)){const d=Vn(o,l),f=ms(h,c);jL(t,e,i,d,f,n,s,r)}else{const d=In(o);Ec(d,a,i,s,r)&&DM(d,t,e,i,n,s,r);const f=Dn(o,l);Ec(f,a,i,s,r)&&DM(f,t,e,i,n,s,r)}}const a9=["x","y","z"];function o9(o,t,e,i,n,s){Hi.setBuffer(o._roots[t]);const r=CM(0,o,e,i,n,s);return Hi.clearBuffer(),r}function CM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Hi;let l=o*2;if(cn(l,a)){const u=Vn(o,c),d=ms(l,a);return QL(t,e,i,u,d,n,s)}else{const u=Fy(o,c),d=a9[u],p=i.direction[d]>=0;let m,g;p?(m=In(o),g=Dn(o,c)):(m=Dn(o,c),g=In(o));const M=Ec(m,r,i,n,s)?CM(m,t,e,i,n,s):null;if(M){const x=M.point[d];if(p?x<=r[g+u]:x>=r[g+u+3])return M}const y=Ec(g,r,i,n,s)?CM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const Pp=new Je,oh=new Kr,ch=new Kr,Qu=new Gt,iS=new Cs,Np=new Cs;function c9(o,t,e,i){Hi.setBuffer(o._roots[t]);const n=OM(0,o,e,i);return Hi.clearBuffer(),n}function OM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Hi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),iS.set(e.boundingBox.min,e.boundingBox.max,i),n=iS),cn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Vn(o,a),g=ms(c,r);if(Qu.copy(i).invert(),e.boundsTree)return ji(o,s,Np),Np.matrix.copy(Qu),Np.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>Np.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let w=m*3,y=(g+m)*3;w<y;w+=3)if(xn(ch,w,u,d),ch.needsUpdate=!0,M.intersectsTriangle(ch))return!0;return!1}});{const v=zm(e);for(let M=m*3,w=(g+m)*3;M<w;M+=3){xn(oh,M,u,d),oh.a.applyMatrix4(Qu),oh.b.applyMatrix4(Qu),oh.c.applyMatrix4(Qu),oh.needsUpdate=!0;for(let y=0,x=v*3;y<x;y+=3)if(xn(ch,y,f,p),ch.needsUpdate=!0,oh.intersectsTriangle(ch))return!0}}}else{const h=In(o),u=Dn(o,a);return ji(h,s,Pp),!!(n.intersectsBox(Pp)&&OM(h,t,e,i,n)||(ji(u,s,Pp),n.intersectsBox(Pp)&&OM(u,t,e,i,n)))}}const Lp=new Gt,M1=new Cs,td=new Cs,l9=new T,h9=new T,u9=new T,d9=new T;function f9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),M1.set(t.boundingBox.min,t.boundingBox.max,e),M1.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=Er.getPrimitive(),f=Er.getPrimitive();let p=l9,m=h9,g=null,v=null;n&&(g=u9,v=d9);let M=1/0,w=null,y=null;return Lp.copy(e).invert(),td.matrix.copy(Lp),o.shapecast({boundsTraverseOrder:x=>M1.distanceToBox(x),intersectsBounds:(x,b,E)=>E<M&&E<r?(b&&(td.min.copy(x.min),td.max.copy(x.max),td.needsUpdate=!0),!0):!1,intersectsRange:(x,b)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:S=>td.distanceToBox(S),intersectsBounds:(S,A,_)=>_<M&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){xn(f,3*_,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let D=x,O=x+b;D<O;D++){xn(d,3*D,l,c),d.needsUpdate=!0;const P=d.distanceToTriangle(f,p,g);if(P<M&&(m.copy(p),v&&v.copy(g),M=P,w=D,y=_),P<s)return!0}}}});{const E=zm(t);for(let S=0,A=E;S<A;S++){xn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=x,I=x+b;_<I;_++){xn(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,w=_,y=S),D<s)return!0}}}}}),Er.releasePrimitive(d),Er.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=w,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(Lp),m.applyMatrix4(Lp),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function p9(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(cn(m,a)){const g=Vn(d,r),v=ms(m,a);let M=1/0,w=1/0,y=1/0,x=-1/0,b=-1/0,E=-1/0;for(let S=g,A=g+v;S<A;S++){const _=3*o.resolveTriangleIndex(S);for(let I=0;I<3;I++){let D=_+I;D=i?i[D]:D;const O=n.getX(D),P=n.getY(D),N=n.getZ(D);O<M&&(M=O),O>x&&(x=O),P<w&&(w=P),P>b&&(b=P),N<y&&(y=N),N>E&&(E=N)}}return c[d+0]!==M||c[d+1]!==w||c[d+2]!==y||c[d+3]!==x||c[d+4]!==b||c[d+5]!==E?(c[d+0]=M,c[d+1]=w,c[d+2]=y,c[d+3]=x,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=In(d),v=Dn(d,r);let M=p,w=!1,y=!1;if(t){if(!M){const _=g/Rn+f/ps,I=v/Rn+f/ps;w=t.has(_),y=t.has(I),M=!w&&!y}}else w=!0,y=!0;const x=M||w,b=M||y;let E=!1;x&&(E=u(g,f,M));let S=!1;b&&(S=u(v,f,M));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=v+_,O=c[I],P=c[I+3],N=c[D],k=c[D+3];c[d+_]=O<N?O:N,c[d+_+3]=P>k?P:k}return A}}}function m9(o,t,e,i,n,s,r){Hi.setBuffer(o._roots[t]),PM(0,o,e,i,n,s,r),Hi.clearBuffer()}function PM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Hi,h=o*2;if(cn(h,c)){const d=Vn(o,l),f=ms(h,c);i9(t,e,i,d,f,n,s,r)}else{const d=In(o);Ec(d,a,i,s,r)&&PM(d,t,e,i,n,s,r);const f=Dn(o,l);Ec(f,a,i,s,r)&&PM(f,t,e,i,n,s,r)}}const g9=["x","y","z"];function v9(o,t,e,i,n,s){Hi.setBuffer(o._roots[t]);const r=NM(0,o,e,i,n,s);return Hi.clearBuffer(),r}function NM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Hi;let l=o*2;if(cn(l,a)){const u=Vn(o,c),d=ms(l,a);return n9(t,e,i,u,d,n,s)}else{const u=Fy(o,c),d=g9[u],p=i.direction[d]>=0;let m,g;p?(m=In(o),g=Dn(o,c)):(m=Dn(o,c),g=In(o));const M=Ec(m,r,i,n,s)?NM(m,t,e,i,n,s):null;if(M){const x=M.point[d];if(p?x<=r[g+u]:x>=r[g+u+3])return M}const y=Ec(g,r,i,n,s)?NM(g,t,e,i,n,s):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const kp=new Je,lh=new Kr,hh=new Kr,ed=new Gt,nS=new Cs,Fp=new Cs;function M9(o,t,e,i){Hi.setBuffer(o._roots[t]);const n=LM(0,o,e,i);return Hi.clearBuffer(),n}function LM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Hi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),nS.set(e.boundingBox.min,e.boundingBox.max,i),n=nS),cn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Vn(o,a),g=ms(c,r);if(ed.copy(i).invert(),e.boundsTree)return ji(o,s,Fp),Fp.matrix.copy(ed),Fp.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>Fp.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let w=m,y=g+m;w<y;w++)if(xn(hh,3*t.resolveTriangleIndex(w),u,d),hh.needsUpdate=!0,M.intersectsTriangle(hh))return!0;return!1}});{const v=zm(e);for(let M=m,w=g+m;M<w;M++){const y=t.resolveTriangleIndex(M);xn(lh,3*y,u,d),lh.a.applyMatrix4(ed),lh.b.applyMatrix4(ed),lh.c.applyMatrix4(ed),lh.needsUpdate=!0;for(let x=0,b=v*3;x<b;x+=3)if(xn(hh,x,f,p),hh.needsUpdate=!0,lh.intersectsTriangle(hh))return!0}}}else{const h=In(o),u=Dn(o,a);return ji(h,s,kp),!!(n.intersectsBox(kp)&&LM(h,t,e,i,n)||(ji(u,s,kp),n.intersectsBox(kp)&&LM(u,t,e,i,n)))}}const Up=new Gt,y1=new Cs,id=new Cs,y9=new T,w9=new T,x9=new T,b9=new T;function S9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),y1.set(t.boundingBox.min,t.boundingBox.max,e),y1.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=Er.getPrimitive(),f=Er.getPrimitive();let p=y9,m=w9,g=null,v=null;n&&(g=x9,v=b9);let M=1/0,w=null,y=null;return Up.copy(e).invert(),id.matrix.copy(Up),o.shapecast({boundsTraverseOrder:x=>y1.distanceToBox(x),intersectsBounds:(x,b,E)=>E<M&&E<r?(b&&(id.min.copy(x.min),id.max.copy(x.max),id.needsUpdate=!0),!0):!1,intersectsRange:(x,b)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:S=>id.distanceToBox(S),intersectsBounds:(S,A,_)=>_<M&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){const D=E.resolveTriangleIndex(_);xn(f,3*D,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let O=x,P=x+b;O<P;O++){const N=o.resolveTriangleIndex(O);xn(d,3*N,l,c),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,g);if(k<M&&(m.copy(p),v&&v.copy(g),M=k,w=O,y=_),k<s)return!0}}}})}else{const E=zm(t);for(let S=0,A=E;S<A;S++){xn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=x,I=x+b;_<I;_++){const D=o.resolveTriangleIndex(_);xn(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,w=_,y=S),O<s)return!0}}}}}),Er.releasePrimitive(d),Er.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=M,i.faceIndex=w,n&&(n.point?n.point.copy(v):n.point=v.clone(),n.point.applyMatrix4(Up),m.applyMatrix4(Up),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function sS(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 zp=new Cs,Bp=new El,rS=new T,aS=new Gt,oS=new T,w1=["getX","getY","getZ"];class lm extends WL{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 lm(e,{...i,[ky]:!0});if(a._roots=s,a._indirectBuffer=r||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new we(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/ps;p<m;p++){const g=Rn*p,v=2*g;cn(v,f)||(d[g+6]=d[g+6]/Rn-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[w1[f]](h),m=r[w1[f]](u),g=r[w1[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 w=v+0,y=v+1,x=v+2;a&&(w=a[w],y=a[y],x=a[x]),c||(w=w*u+h,y=y*u+h,x=x*u+h);for(let b=0;b<3;b++){let E,S,A;c?(E=r[d[b]](w),S=r[d[b]](y),A=r[d[b]](x)):(E=l[w+b],S=l[y+b],A=l[x+b]);let _=E;S<_&&(_=S),A<_&&(_=A);let I=E;S>I&&(I=S),A>I&&(I=A);const D=(I-_)/2,O=b*2;i[M+O+0]=_+D,i[M+O+1]=D+(Math.abs(_)+D)*v0}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(n===void 0)return;aS.copy(t.matrixWorld).invert(),Bp.copy(e.ray).applyMatrix4(aS),oS.setFromMatrixScale(t.matrixWorld),rS.copy(Bp.direction).multiply(oS);const s=rS.length(),r=e.near/s,a=e.far/s;if(e.firstHitOnly===!0){let c=this.raycastFirst(Bp,n,r,a);c=sS(c,t,e),c&&i.push(c)}else{const c=this.raycast(Bp,n,r,a);for(let l=0,h=c.length;l<h;l++){const u=sS(c[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?p9:e9)(this,t)}raycast(t,e=Ba,i=0,n=1/0){const s=this._roots,r=[],a=this.indirect?m9:r9;for(let c=0,l=s.length;c<l;c++)a(this,c,e,t,r,i,n);return r}raycastFirst(t,e=Ba,i=0,n=1/0){const s=this._roots;let r=null;const a=this.indirect?v9:o9;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?M9:c9;for(let r=0,a=n.length;r<a&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=Er.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?s9:t9});return Er.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=Er.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,l=this.indirect?p=>{const m=this.resolveTriangleIndex(p);xn(r,m*3,a,c)}:p=>{xn(r,p*3,a,c)},h=Er.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const m=t.resolveTriangleIndex(p);xn(h,m*3,u,d)}:p=>{xn(h,p*3,u,d)};if(s){if(!(t instanceof lm))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(m,g,v,M,w,y,x,b)=>{for(let E=v,S=v+M;E<S;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,w,y,x,b))return!0}return!1};if(n){const m=n;n=function(g,v,M,w,y,x,b,E){return m(g,v,M,w,y,x,b,E)?!0:p(g,v,M,w,y,x,b,E)}}else n=p}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return zp.set(t.min,t.max,e),zp.needsUpdate=!0,this.shapecast({intersectsBounds:i=>zp.intersectsBox(i),intersectsTriangle:i=>zp.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?S9:f9)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return qL(this,t,e,i,n)}}class aa{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new Tr;static install(){if(aa.installed)return;aa.installed=!0;const t=yt.prototype.raycast;yt.prototype.raycast=function(e,i){const n=aa.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 we)||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<aa.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=aa.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(r))return null;const a=aa.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;aa.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const c=new lm(i,{indirect:!0});return aa.trees.set(i,{bvh:c,position:n,positionVersion:n.version,index:s,indexVersion:s?.version??0}),c}}function E9(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.visibilityKm===t.visibilityKm&&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 Hp=900,x1=1,cS=4,b1=5,Gp=.5,Vp=We.GROUND_RADIUS_M;function lS(o){return We.groundRadiusFor(o)}const S1=.5,E1=850,Wp=.03,A9=.015,ys=850,uh=300,Za=120,_9=700,A1=.03,T9=3.5,Xp=20,_1=.04,R9=.26,hS=4,T1=1.5,uS=-1,I9=.01,y0=-4,D9=2,C9=20,$p=2600,O9=.97,P9=.38,nd=y0,N9=8,L9=2,dS=1500,k9=.7,F9=.3,U9=.32,z9=.65,fS=2.4,B9=.9,H9=400,G9=[0,45,90,135,180,225,270,315],V9=2,W9=16,pS=4e3,mS=880,Yp=40,gS=60,X9=10,vS=1,$9=We.REBUILD_DISTANCE_M,MS=.265,yS=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*MS,Math.sin(e)*MS]})],R1=700,I1=250/UM,Y9=12,wS=5,D1=6,Uc=[.92,.92,.95],C1=[.15,.15,.19],O1={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}},gh=0,P1=0,K9=150,N1=3e3,sd=20,q9=15,xS=gh,Z9=40,bS=1,J9=9;function L1(o){return bS+(J9-bS)*o}const SS=new rt(.75,.82,.92),j9=10,Q9=.5;function ES(o){return oa(o/j9,Q9,1)}const zc=200,AS=.18,_S=.32,t7=.35,TS=new rt(.85,.9,.98),RS=5,IS=.85,DS=.01;function e7(o,t,e=1){return Math.round(o*(DS+(1-DS)*t)*e)}function i7(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 CS=230,OS=.7,PS=.05,n7=.6,s7=.7,r7=.15,NS=.35,a7=3,o7=1/12,c7=.5,ia=new rt(.82,.86,1),l7=2500,h7=1.6,k1=15,u7={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 ht{renderer;scene=new hr;phenomena=new Fr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Ke;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()+pS,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),pS+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new xe;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new tt;decorModelProvider=new S3;decorModelToken=0;decorModelCredits=new Map;emitterLights=new bs(this.scene,()=>this.relativeScale,{halfExtentM:Za,depthHalfRangeM:uh,biasM:A1,normalBiasM:_1,mapSize:1024});bodySystem=new oe(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??ht.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*ht.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 q0(16777215,0);celestialLightTarget=new Bi;skyLight=new GI(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 l0;weather=gm;observerElevationM=0;siteElevationM=0;air=new ls;groundRadius=Vp;terrainRadius=Vp;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new T;cloudFieldOffset=new T;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new T;rainLastVerticalFacing=-1;rainViewportSize=new tt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new q0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new T;sunVisible=!1;lensFlareScratch=new T;sunOcclusionRaycaster=new l0;sunOcclusionDirectionScratch=new T;sunOcclusionRightScratch=new T;sunOcclusionUpScratch=new T;ufoOcclusionRaycaster=new l0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=ke.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 Mf;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=jA()){xd.install(),aa.install(),this.renderer=new n8({canvas:t,antialias:!0}),this.resolution=new ni(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=dd,this.camera=new jn(60,t.width/Math.max(t.height,1),.1,Hp*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=-Za,this.celestialLight.shadow.camera.right=Za,this.celestialLight.shadow.camera.top=Za,this.celestialLight.shadow.camera.bottom=-Za,this.celestialLight.shadow.camera.near=ys-uh,this.celestialLight.shadow.camera.far=ys+uh,this.celestialLight.shadow.bias=-A1/(2*uh),this.celestialLight.shadow.normalBias=_1,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(ia),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 fe(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*I1,0,t.z*I1);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)*ei,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ei;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ei,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(lS(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Vp),this.camera.far=Math.max(Hp*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=ht.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return We.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=re(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=vS+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=We.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=re(n,s,r.lat,r.lng);if(Math.hypot(l.x,l.z)<r.radiusM*ht.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:n,lng:s,radiusM:e.radiusM};const a=++this.lookPatchToken,c=this.terrainProviders;e1(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=ht.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=re(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)}),ht.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(We.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=re(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<$9*(r/Vp))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(re(t,e,c.lat,c.lng).x,re(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(e1(t,e,this.terrainProviders,r,{route:this.observerRoute}),ht.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?re(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=vS,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(!We.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=re(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*ht.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??We.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(e1(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*ht.FAR_RING_OPEN_SHARE,referenceElevationM:s}),ht.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=ht.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-ht.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=re(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=re(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)/ht.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=We.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>ht.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(re(t,e,s.lat,s.lng).x,re(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(bd(t,e,i)),ht.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>ht.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),ht.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(re(t,e,a.lat,a.lng).x,re(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(bd(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)}),ht.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)),hs.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=at(async()=>{const{WaterSystem:t}=await import("./WaterSystem-DrSAhM5g.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>ht.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(re(t,e,s.lat,s.lng).x,re(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(bd(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)}),ht.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),hs.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=at(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-C1nfRJfj.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??=at(async()=>{const{TraceSystem:t}=await import("./TraceSystem-BkUPo1Xf.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(b1);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=dt.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?re(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 Ii(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?An.LENS_K:An.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(E9(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!i7(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||e.visibilityKm!==t.visibilityKm||n||s)&&this.restateHaze(),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>=c7,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(ht.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=ht.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=ht.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),dt.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,N9);for(const i of t){const n=dt.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)<L9,i.lamp),i.model&&i.id.startsWith(Li.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=ht.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??=at(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-CqpZgLkb.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=ht.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=Ts.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Be.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 yM){const a=go.of(r);s.add(a.key);const c=go.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}=Ei(s.position.altitudeDeg,s.position.azimuthDeg,ys),[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,ht.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):m0(-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*ei)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*ei)*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?Ei(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*ei)/Math.cos(t.lat*ei)}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 l1(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(_0(t))||!dt.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=E3(i.scene);n.traverse(s=>{s instanceof yt&&(s.userData.sharedModel=!0)}),dt.applyModelParameters(n,t.modelParameters,i.bindings),dt.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new zs;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?cE[t.kind]:_0(t);if(!(!n||!dt.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 l1(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"&&(oe.glaze(c),hs.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=l1(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||hs.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?re(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&du(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=Xr(s,i),m=dt.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*ei,v=m.x*Math.cos(g)+m.z*Math.sin(g),M=-m.x*Math.sin(g)+m.z*Math.cos(g),w=p.eastM+n.x,y=-p.northM+n.z;r.x=-(w+v),r.z=-(y+M),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ei,-(m.headingDeg+this.indoorLookYawDeg)*ei,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=Xr(p,i),v=this.lampNudges.get(p.id),M=g.eastM+(v?.eastM??0)+n.x+r.x,w=-(g.northM+(v?.northM??0))+n.z+r.z,y=this.terrainMesh,x=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(m.userData.footprintKey!==x){if(p.kind==="wire"){const O=dt.wireGround(p,M,w,g.headingDeg,(P,N)=>this.groundYUnder(P,N));m.userData.footprintGroundY=O.startY,dt.shearWire(m,dt.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(M,w),P=-(g.headingDeg??0)*ei,N=Math.cos(P),k=Math.sin(P);m.userData.footprintGroundY=O,Te.drape(dt.bodyOf(m),(B,W)=>this.groundYUnder(M+B*N+W*k,w-B*k+W*N)-O)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,M,w,g.headingDeg,g.altitudeM);m.userData.footprintKey=x}const E=g.altitudeM>ht.AIRBORNE_M&&Math.hypot(M,w)<ht.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,S=p.id.startsWith(Li.ID_PREFIX)?ht.trafficHeight(g.altitudeM,m.userData.footprintGroundY):E+g.altitudeM;if(m.position.set(M,S,w),p.kind==="crop"){const O=Math.hypot(M,w);m.visible=O<=K9}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*ei);const D=yT(p,i);if(D!==void 0&&ht.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const O=this.terrainMesh,P=[O?.geometry.uuid,M-(O?.position.x??0),w-(O?.position.z??0),m.position.y-(O?.position.y??0),g.headingDeg,g.altitudeM].map(N=>typeof N=="number"?N.toFixed(4):N).join(":");m.userData.cropGroundKey!==P&&(dt.fitCropToGround(m,(N,k)=>this.groundYUnder(N,k)+g.altitudeM),m.userData.cropGroundKey=P)}if(!_){const O=m.position.distanceTo(this.camera.position);a=Math.max(a,O),O<ht.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(Hp*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=Xr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=dt.sizeOf(s),u=-(a.headingDeg??0)*ei,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=dt.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):P1}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))+ht.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*ht.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 P1;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=oa((e-r)/(a-r)*(s-1),0,s-1),u=oa((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return P1;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,m=u-f,g=(x,b)=>n.getY(x*s+b),v=g(f,d),M=g(f,d+1),w=g(f+1,d),y=g(f+1,d+1);return p+m<=1?v+(M-v)*p+(w-v)*m:y+(w-y)*(1-p)+(M-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return dt.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=Ks.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?Ks.NONE:this.perception??Ks.NONE;if(ki.uColorVision.value.set(...i.colorMatrix),ki.uContrast.value=i.contrastGain,!t){ki.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";ki.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,ht.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),h!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(h=Math.min(h,ht.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);ki.uMediumExposure.value=u,ki.uPhoneStrength.value=n&&c!==void 0&&c>0?Lr.strengthFor(Lr.MID_GREY*u*e*c):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new T;let r=0,a=0;for(const{position:c,luminanceCdM2: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/(ht.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&&dt.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"?lE(n,t):void 0,c=a!==void 0?ml.lamps(a):Sm(n,t,this.lastAstronomy?.sun.altitudeDeg);dt.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??=at(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-B4RR270O.js");return{HeadlightSystem:t}},[],import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new T(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=dt.sizeOf(t).lengthM,r=e.getWorldPosition(new T).addScaledVector(n,s/2-F9);r.y+=k9;const a=dt.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*U9,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?ml.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new T(Math.sin(i),0,-Math.cos(i)),s=new T(n.x*fS,this.camera.position.y-B9,n.z*fS);this.headlightSystem.aim("observer",e,s,n,z9,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=dt.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=dS*dt.lampShare(n),c=new CA(16764006,a*this.relativeScale,H9);n?.colorTemperatureK&&c.color.setRGB(...dt.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;dt.setLitWindowShare(t?$n.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=Gs.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Bt.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=an.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,hS,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<y0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=hS/ys*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ei(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ei(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(oa(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?oa(e.separationDeg*n*ei/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 T(s.x,s.y,s.z).normalize(),moon:new T(d.x,d.y,d.z).normalize(),sunRadiusRad:i*ei,moonRadiusRad:f*ei};const p=.01,m=(M,w)=>Ei(t.sun.altitudeDeg+M,t.sun.azimuthDeg+w,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},v={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new kh(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??ht.relativeSkyOf(MM(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),Vt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??dS)*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.hazeOpticalDepth()??Dt.DEFAULT_AEROSOL_OPTICAL_DEPTH)*Dt.aerosolDensity(this.siteElevationM+this.observerElevationM),n=this.cloudTransmission(t),s=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),r=Be.aureoleScale(i,Be.airMass(t.altitudeDeg))*n,a=Be.coronaScale(s),c=Be.illuminanceOf(t.magnitude),l=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),r.toExponential(2),a.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(l===this.lunarDiffractionKey)return;this.lunarDiffractionKey=l,this.lunarDiffraction||(this.lunarDiffraction=new Ly,this.celestialGroup.add(this.lunarDiffraction.object));const h=Be.profile(Be.HAZE_COARSE_MODE),u=Be.profile(Be.CLOUD_DROPLETS),d=MN(t.altitudeDeg),f=new Float32Array(Be.STEPS*3);let p=0;for(let M=0;M<Be.STEPS;M++){const w=M*3,y=[0,1,2].map(b=>c*d[b]*(r*h[w+b]+a*u[w+b])),x=Gs.shown(y,Gs.luminanceOf(y),(b,E)=>e.relativeOfLuminance(b,E));f.set(x,w),p=Math.max(p,Gs.response(x))}const{x:m,y:g,z:v}=Ei(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(p>1/200?{x:m,y:g,z:v}:void 0,f)}applyAir(){this.scene.fog instanceof yc||(this.scene.fog=new yc),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)}hazeOpticalDepth(){return ls.aerosolOpticalDepthOf(this.weather,this.siteElevationM)}restateHaze(){this.air=ls.of(this.weather,this.siteElevationM),this.applyAir();const t=this.hazeOpticalDepth(),e=rl.OPTICAL_DEPTH_STEP;this.scatteredSky?.setConditions({aerosolOpticalDepth:t===void 0?void 0:Math.round(t/e)*e}),this.pumpScatteredSky()}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.weather.visibilityKm!==void 0&&this.restateHaze(),this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,ht.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:an.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?an.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?W9:V9),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 WN(E1),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):m0(-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=`${Li.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(e))continue;const s=this.screenPointOf(new T().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(Wp*this.camera.fov*Math.PI/180);let s,r=n;const a=new T;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(Li.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(Wp*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>=nd,s=!n&&t.moon.altitudeDeg>=nd,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ei)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?Vb.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=nd&&(h=t.moon,u=Vb.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*ei)),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 b=Be.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)g[I]=b*E[I]*m*c,this.cloudBeam[I]=b*E[I];const{x:S,y:A,z:_}=Ei(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(S,A,_),u>0){const I=Be.illuminanceOf(h.magnitude)*i,D=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),O=h===r?f:this.cloudTransmission(h);for(let P=0;P<3;P++)a[P]=I*D[P]*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 b=this.skyCloudTransmission(),E=e.skyIrradiance,S=[0,1,2].map(_=>E[_]*b+g[_]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const A=Jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(S[0]+a[0]*d),A*(S[1]+a[1]*d),A*(S[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:w,z:y}=Ei(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(M,w,y),this.celestialLight.shadow.normalBias=_1*oa(w/R9,.1,1),this.placeShadowFrustum();const x=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/x,a[1]/x,a[2]/x),this.celestialLight.intensity=x,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=Ts.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Be.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=ht.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 Rr||r instanceof ec)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=ht.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new T(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=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=T9;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Xp+5,i.near=this.shadowLightDistanceM-Xp,i.far=this.shadowLightDistanceM+Xp,i.updateProjectionMatrix(),e.bias=-.004/(2*Xp),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!==ht.CABIN_SKY_SHARE&&(r.envMapIntensity=ht.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(_9,Math.max(Za,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(uh,e*(uh/Za));this.shadowLightDistanceM=Math.max(ys,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-A1/(2*s);const r=e>2*Za?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Za;shadowLightDistanceM=ys;shadowUp=new T(0,1,0);shadowAxisX=new T;shadowAxisY=new T;shadowWorld=new T;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*ei,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new T(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Bt.semiSaturation(Bt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new kn,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}=Ei(t.altitudeDeg,t.azimuthDeg,1);return{direction:new T(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=_i.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 m0(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.references?.release(),this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+ht.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.scatteredSky?.invalidate(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;if(this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e),!this.pixelRatioHeld){const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}}this.drawIfDirty()}get maxPixelRatio(){return this.resolution.maximum}pixelRatioHeld=!1;holdPixelRatio(t){this.pixelRatioHeld=t!==void 0;const e=t??this.resolution.maximum;this.renderer.getPixelRatio()!==e&&this.applyPixelRatio(e)}async controlFrame(){await this.loadControlPasses(),this.render();const t=this.drawn;return this.drawIfDirty(),this.drawn===t?void 0:{image:this.renderer.domElement.toDataURL("image/png"),...this.drawControlPasses()}}async loadControlPasses(){if(this.controlPasses)return;const{ControlPasses:t}=await at(async()=>{const{ControlPasses:e}=await import("./ControlPasses-BxgSO3B9.js");return{ControlPasses:e}},[],import.meta.url);this.controlPasses??=new t}drawControlPasses(){if(!this.controlPasses)throw new Error("The control passes are not loaded: see loadControlPasses");return this.controlPasses.draw({renderer:this.renderer,scene:this.scene,camera:this.camera,equidistant:this.usableEquidistantPass(),sky:[this.celestialGroup,...this.pointLayerHost.clouds(),...this.lensFlare?[this.lensFlare.mesh]:[]],isSolid:t=>ht.isSolidSurface(t),drawPhenomena:t=>this.renderPhenomenaPass(t)})}controlPasses;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&&du(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Xr(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=dt.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 hs(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 ir),...[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:hs.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,ht.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new Oh,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>Ei(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(ht.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>=nd?t.sun:t.moon.altitudeDeg>=nd?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 Nr;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?Ei(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??ht.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>ht.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(ki.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:Gs.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>he.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new he,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 he,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(ki.uRetina.value=this.retina.texture,ki.uRetinaOn.value=1,ki.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)*ei,-(n?.headingDeg??0)*ei,(n?.rollDeg??0)*ei,"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:Gs.luminanceOf(l.lux)})}return a}historicQuaternion=new es;historicEuler=new Yr;historicDirection=new T;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<ht.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,o7);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(),dt.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?[EM]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},zs.INTERVAL_MS)),ki.uRodShare.value=this.scatteredSky?.rodShare??0,ki.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);ki.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 ir&&e.userData.pointSource||e instanceof yt&&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(b1),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(_3),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 Is({blending:Ml,blendSrc:Ta,blendDst:Ta,blendSrcAlpha:Ta,blendDstAlpha:Ta,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??=at(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-BRTCOQHk.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 T)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}get areReferencesShown(){return this.referencesShown}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const 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);ht.markDecorDepth(h,u),u&&c++}c>0&&(t.layers.set(x1),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(EM),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new Cm;phenomenaViewProjection=new Gt;occluderSphere=new Tr;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 Je().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new Tr).applyMatrix4(new Gt().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=ht.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 jn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new Is({colorWrite:!1,side:Tn});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(ht.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*ei}static isSolidSurface(t){if(!(t instanceof yt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==Cn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof yt))return;e&&ht.isSolidSurface(i)?i.layers.enable(x1):i.layers.disable(x1)})}startExposure(){this.cancelExposure(),this.references?.hold(this.camera),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 rN(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()+ht.EXPOSURE_BUDGET_MS,s=ht.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(){ki.uRodShare.value=this.scatteredSky?.rodShare??0,ki.uHasOverlay.value=1,ki.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 hr,n=new ur(-1,1,1,-1,0,2),s=Yp/(mS*Math.tan(gS*ei/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new T).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new Uu(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 Je,i=new T,n=this.camera.getWorldDirection(new T),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<ht.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 Ed(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,ki.uMediumExposure.value,this.sunBeyondPicture())}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new tt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Di(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 Ny(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 Ni(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=ht.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 T)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ni.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*ei);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new T;screenPointQuaternion=new es;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-ht.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=ke.offFrameShare(Math.atan(Math.hypot(s.x*a,s.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI,this.ghostOptics.reachDeg);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(cS),this.camera.layers.set(cS),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 yS)this.isSunOccluded(e[0],e[1])||t++;return t/yS.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 xo));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?ht.VEIL_SAMPLES:ht.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 ks;veilTargetScratch=new T;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const v=t.x+e.x*g-s.position.x,M=t.z+e.z*g-s.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const 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 w=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(g<w||g>y)return!1;continue}const x=(w-g)/v,b=(y-g)/v;d=Math.max(d,Math.min(x,b)),f=Math.min(f,Math.max(x,b))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const v=d+(f-d)*g/m,M=t.x+e.x*v,w=t.y+e.y*v,y=t.z+e.z*v;if(w<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=Gp;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=>ht.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=I9*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new T).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=ht.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(oa(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=A9*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?ht.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new Je,d=new T;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new T).length()/2,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const v=Math.acos(Math.min(1,m.normalize().dot(n))),M=Math.atan(p/g);if(M>r){const w=this.raycaster.intersectObject(f,!0)[0];if(!w||c!==void 0&&c<w.distance)continue}else if(v>r)continue;M<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(Wp*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,Gp)}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 Je;bodyCornerScratch=new T;decorFrameScratch=new Gt;decorPartMatrix=new Gt;decorPartScratch=new Je;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const i=this.decorFrameScratch.copy(e.matrixWorld).invert(),n=this.bodyBoxScratch.makeEmpty();if(e.traverse(l=>{const h=l.geometry;!h||!l.visible||(h.boundingBox||h.computeBoundingBox(),h.boundingBox&&n.union(this.decorPartScratch.copy(h.boundingBox).applyMatrix4(this.decorPartMatrix.multiplyMatrices(i,l.matrixWorld))))}),n.isEmpty())return;let s=1/0,r=1/0,a=-1/0,c=-1/0;for(let l=0;l<8;l++){const h=this.bodyCornerScratch.set(l&1?n.max.x:n.min.x,l&2?n.max.y:n.min.y,l&4?n.max.z:n.min.z).applyMatrix4(e.matrixWorld),u=this.screenPointOf(h.sub(this.camera.position).normalize());if(!u)return;s=Math.min(s,u.ndcX),a=Math.max(a,u.ndcX),r=Math.min(r,u.ndcY),c=Math.max(c,u.ndcY)}return{minX:s,minY:r,maxX:a,maxY:c}}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*ei/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 Hr;decorHitScratch=new T;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&(s.transparent&&s.opacity<ht.SEE_THROUGH_BELOW||s instanceof xo))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=ht.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 El().copy(n).applyMatrix4(new Gt().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new T(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,ht.RAILWAY_PICK_ABOVE_M))return;const c=ht.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-ht.RAILWAY_GROUND_MARGIN_M,Gp))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:ht.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(Wp*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,Gp))return;const c=ht.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())dt.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new T;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<ht.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 hn(Hp,32,16),i=e.attributes.position,n=e.getAttribute("color")??new pe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=m3(i.getX(r),i.getY(r),i.getZ(r)),l=mN(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 Is({vertexColors:!0,side:zi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new yt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=lS(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new xy(this.groundRadius,48),i=new Rr({color:new rt(S1,S1,S1),fog:!0});yc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new yt(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=Ei(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-Fe.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*O9);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Fe.iceAlphaAt(i,$p,r,this.cloudFieldOffset)*P9),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<y0){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}=Ei(e.altitudeDeg,e.azimuthDeg,ys),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,s,l),u=ht.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/ys)**2,p=[0,1,2].map(g=>u[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(ht.BRIGHTEST_RELATIVE,g));d instanceof yt||(this.disposeMesh(d),d=new yt(new hn(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 ir)){this.disposeMesh(d);const m=new be;m.setAttribute("position",new we(new Float32Array(3),3)),m.setAttribute("color",new we(new Float32Array(3),3)),d=new ir(m,Vt.material(iu[iu.length-1].size,!1)),Vt.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/ys*(180/Math.PI),ht.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=VN(),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<y0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ei(t.altitudeDeg,t.azimuthDeg,ys),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??wa.MEAN_RADIUS_DEG,h=ys*Math.tan(l*ei),u=Math.max(oa(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/ys)**2,d=new rt(...c.map(m=>Math.min(ht.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(oa(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Uu?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=kS(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Uu(new c0({map:kS(t.phase),color:d,fog:!1,blending:Cn,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=D9){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 ht.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,Vt.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=Be.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Gs.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 c0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Uu(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(An.radiusDeg(An.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new An(`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=Ch(t.magnitude,e),s=Qg(n);this.cometKey=i,this.setBodyMesh(i,t.position,T1*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new er(ys),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Zi,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:$p},0);return}const s=this.lowerCloudCover(),r=Ee.deckLitUntilDeg(Ee.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?fe.SUN_MAGNITUDE:e.magnitude),l=Ee.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=Ei(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??$p},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??i_,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new sl,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?fe.SUN_MAGNITUDE:e.magnitude,C9),c=tr.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}=Ei(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 qo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=kr.galactic(i,n),r=ht.directionOf(s.centre),a=ht.directionOf(s.rotation),c=ht.directionOf(s.pole),l=new de().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=ht.directionOf(kr.eclipticPole(i,n)),u=ht.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:ht.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:_t.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new T(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ei(t.altitudeDeg,t.azimuthDeg,1);return new T(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=Ch(n.magnitude,e),a=Qg(r);this.setBodyMesh(s,n.position,T1*(.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=Ch(n.magnitude,e),r=Qg(s),a=u7[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),l=T1*(.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 Br(n,s),a=F1(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<uS)continue;const{x:p,y:m,z:g}=Ei(d,f,E1);c.push({x:p,y:m,z:g,brightness:Ch(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Be.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of yN){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<uS)continue;const{x:f,y:p,z:m}=Ei(u,d,E1);this.namedStars.push({star:h,direction:new T(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=iu.map((h,u)=>{const d=c.filter(x=>Py(x.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((x,b)=>{f[b*3]=x.x,f[b*3+1]=x.y,f[b*3+2]=x.z,p[b]=x.brightness,m.set(x.illuminance,b*3),g[b]=x.phase,v[b]=x.speedFactor});const M=new be;M.setAttribute("position",new we(f,3)),M.setAttribute("seed",new we(g.map(x=>x/(2*Math.PI)),1));const w=new we(new Float32Array(d.length*3),3);M.setAttribute("color",w);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new ir(M,Vt.material(h.size)),Vt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:p,illuminance:m,phase:g,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Vt.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 eu(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(Uc[0]+(C1[0]-Uc[0])*e,Uc[1]+(C1[1]-Uc[1])*e,Uc[2]+(C1[2]-Uc[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}=fM(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=pM(R1);this.cloudMesh=new yt(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}=fM(new rt(...Uc),t,$p,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new yt(pM(R1*1.04),e),this.cirrusMesh.renderOrder=wS-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?eu.deckOrder(!0,0,1):wS}cloudLayerOffset(){const e=((this.weather.cloudBaseM??UM)-this.observerElevationM)*I1;return Math.sign(e||1)*Math.max(Math.abs(e),Y9)}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*k1*this.relativeScale/Math.PI,l=new rt(e[0]+ia.r*c,e[1]+ia.g*c,e[2]+ia.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 e7(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,N1],[this.rainSplashSystem?.points,zc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:O1[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=ES(L1(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=O1[t],i=e.poolSize,n=F1(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 w=0;w<i;w++){const y=n()*Math.PI*2,x=n()*e.radiusM;s[w*3]=Math.cos(y)*x,s[w*3+1]=gh+n()*(e.topYM-gh),s[w*3+2]=Math.sin(y)*x,r[w]=n()*Math.PI*2,a[w]=.7+n()*.6,c[w]=.6+n()*.8,l[w]=.4+n()*1.2}const m=new be;m.setAttribute("position",new we(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:d7(t)},uNearFocusDistance:{value:RS},uHazeDistance:{value:e.radiusM*IS}},v=new De({uniforms:g,vertexShader:M7,fragmentShader:y7,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const M=new ir(m,v);M.renderOrder=D1,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=O1[i];if(this.precipitationUniforms?.uColor.value.copy(ht.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*ei,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,w=i==="hail"&&f&&p&&m&&g&&v;for(let y=0,x=0;y<c.length;y+=3,x++){if(w&&f[x]>0){if(f[x]-=e,f[x]<=0){const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A,f[x]=0}else{const S=1-f[x]/m[x];c[y+1]=gh+Math.sin(Math.PI*S)*p[x],c[y]=Kp(c[y]+(r+g[x])*e,n.radiusM),c[y+2]=Kp(c[y+2]+(a+v[x])*e,n.radiusM)}continue}let b=0,E=0;if(M){const S=n7*u[x],A=s7*d[x];b=Math.sin(t*S*Math.PI*2+l[x])*A,E=Math.sin(t*S*Math.PI*2+l[x]+Math.PI/2)*A}if(c[y]+=(r+b)*e,c[y+1]-=n.fallSpeedMPerS*h[x]*e,c[y+2]+=(a+E)*e,c[y]=Kp(c[y],n.radiusM),c[y+2]=Kp(c[y+2],n.radiusM),c[y+1]<gh){if(w){p[x]=NS*(.2+Math.random()*1.6),m[x]=r7*(.5+Math.random()),f[x]=m[x];const _=Math.random()*Math.PI*2,I=a7*(p[x]/NS);g[x]=Math.cos(_)*I,v[x]=Math.sin(_)*I,c[y+1]=gh;continue}const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=L1(this.weather.precipitationIntensity);this.rainSystem=BN({count:N1,radiusM:sd,heightM:q9,bottomYM:xS,overallSpeed:Z9,color:SS.clone(),opacity:.85,visibleCount:this.precipitationCount(N1),speedStreak:ES(t),pixelSize:CS,seed:9001,nearFocusDistanceM:RS,hazeDistanceM:sd*IS,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=D1,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=F1(4242),e=new Float32Array(zc*3),i=new Float32Array(zc),n=new Float32Array(zc),s=new Float32Array(zc);for(let h=0;h<zc;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*sd;e[h*3]=Math.cos(u)*d,e[h*3+1]=xS,e[h*3+2]=Math.sin(u)*d,n[h]=LS(AS,_S),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new be;r.setAttribute("position",new we(e,3));const a=new we(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(zc));const c=new De({uniforms:{uMaxSize:{value:t7},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:TS.clone()},uTexture:{value:m7()}},vertexShader:g7,fragmentShader:v7,transparent:!0,depthWrite:!1}),l=new ir(r,c);l.renderOrder=D1,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*ei;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-L1(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(ht.litBySky(SS,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(ht.litBySky(TS,this.baseFogColor));const n=this.weather.windDirectionDeg*ei,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=sd,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=OS+(1-OS)*(1-l),u=PS+(1-PS)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=CS*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())*sd;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=LS(AS,_S),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,(l7/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*k1*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+ia.r*l,this.airlight[1]+ia.g*l,this.airlight[2]+ia.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*h7;r.setRGB(1+c*ia.r,1+c*ia.g,1+c*ia.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*k1*this.relativeScale,e){const{x:c,y:l,z:h}=Ei(25,e.azimuthDeg,ys);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new Zo(ys*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=G9.map(t=>{const e=ul.point(t,this.compassPoints),i=new c0({map:w7(e),depthTest:!1,fog:!1}),n=new Uu(i),{x:s,y:r,z:a}=Ei(0,t,mS);return n.position.set(s,r,a),n.scale.set(Yp,Yp,1),n.renderOrder=X9,n.layers.set(b1),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=gS*Math.PI/360,i=Yp*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 ei=Math.PI/180;function oa(o,t,e){return Math.max(t,Math.min(e,o))}function LS(o,t){return o+Math.random()*(t-o)}function Kp(o,t){return(o%(t*2)+t*3)%(t*2)-t}let qp,Zp;function d7(o){switch(o){case"snow":return f7();case"hail":return p7()}}function f7(){if(qp)return qp;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),qp=new Tc(t),qp}function p7(){if(Zp)return Zp;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),Zp=new Tc(t),Zp}let Jp;function m7(){if(Jp)return Jp;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),Jp=new Tc(t),Jp}const g7=`
|
|
9577
9588
|
uniform float uMaxSize;
|
|
9578
9589
|
uniform float uScale;
|
|
9579
9590
|
attribute float aLife;
|
|
@@ -9868,9 +9879,9 @@ ${Mi.generation}`;return this.snapshotMap?.key!==i&&(this.snapshotMap={key:i,ima
|
|
|
9868
9879
|
<button id="copy" class="share-copy" type="button"></button>
|
|
9869
9880
|
</div>
|
|
9870
9881
|
</dialog>
|
|
9871
|
-
`;class fl extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(fl.TAG)||customElements.define(fl.TAG,fl)}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=$7;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 kT.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(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.pin.checked;this.linkField.value=e?ba.pinnedLink(t.link(),"0.
|
|
9872
|
-
${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.178.4")),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??=at(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 Zn{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(Zn.PLAIN.test(e))return Zn.num(e);const i=Zn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||Zn.num(a)>=60?void 0:Zn.num(s)*3600+Number(r)*60+Zn.num(a)}const n=Zn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?Zn.num(n[1])*3600+Zn.num(n[2])*60+Zn.num(n[3]):/^P/i.test(e)?Gh.seconds(e.toUpperCase()):void 0}static isClock(t){return Zn.clock(t)!==void 0}static clock(t){const e=Zn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,l={hour:Number(r),minute:Number(a),second:Zn.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)}}Yy();fl.register();const w0=wu.home(),Qp="compare-account",G1="start-time",KS="start-clock",Kc="observer",x0="case-named",Od="show-info",b0="interpretation",Bh="hide-pickers",t0="case",e0="account",i0="variant-",V1=`${w0}/edit/`;class qc extends HTMLElement{static get observedAttributes(){return["src","show-labels",Od,Bh,b0,x0,G1,KS,Kc,Pa,Na,Qp]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;caseOfElement;observerText;observerSelect;infoButton;infoPanel;infoAppLink;editLink;readingFindingsElement;readingSensible=!1;readingCheck;bestCases;readingScene=!1;readingEntry;static VERDICT_COLOURS={incompatible:"#e04848",unsettled:"#e08a2c",compatible:"#2e9d5b"};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>${WT}</style>${VT}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(wf),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.caseOfElement=this.shadow.getElementById("case-of"),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("labels-button"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=Kt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=n=>({input:this.shadow.getElementById(`share-opt-${n}`),label:this.shadow.getElementById(`share-opt-${n}-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"),As.register(),this.readingFindingsElement=this.shadow.getElementById("reading-findings");const i=this.shadow.getElementById("reading-chip");i.addEventListener("click",()=>{const n=i.getAttribute("aria-expanded")!=="true";i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById("reading-findings-list").hidden=!n}),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($y,n=>this.showConfrontation(n.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",n=>{n.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",n=>this.syncInfoOpen(n.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 n of[this.shareStartOn,this.shareStart,...Object.values(this.shareOptions).map(s=>s.input)])n.addEventListener("input",()=>this.refreshShareLinks());for(const n of[this.shareScope,this.shareOpens])n.addEventListener("change",()=>this.refreshShareLinks());this.isConnected&&(this.ready=this.loadLocaleMessages())}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=Ws.preferencesFor(this);this.preferences=e;const i=vo(e,Mo),[n,s,r,a]=await Promise.all([CT.load(i),FT(i),ME(i),r8.load(i)]);if(t!==this.localeToken)return;const c=i!==this.language||this.messages===void 0;this.language=i,this.messages=n,this.readingCheck=new fn(a),this.bestCases=new ee(a),this.tags=new lM(s),this.said=new Qn(e),this.summaryBuilder=new Vc(this.messages,new kM(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 l=this.entries.find(h=>h.src===this.currentSrc);l&&this.offerInterpretations(l),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(),c&&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 Qn(["en"]);tags=new lM({});connectedCallback(){Ws.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=this.loadLocaleMessages()),this.applyAskedInfo();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}applyAskedInfo(){this.isConnected&&this.hasAttribute(Od)!==this.infoOpen&&this.toggleInfoPanel()}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===b0){const n=this.entries.find(s=>s.src===this.currentSrc);n&&this.offerInterpretations(n)}if(t===Bh){const n=this.entries.find(s=>s.src===this.currentSrc);this.setEntries(this.entries,this.caseSource),n&&this.offerInterpretations(n)}if(t===Od&&this.applyAskedInfo(),t==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(t===Pa||t===Na)&&this.forwardPlayerAttributes(),t===Kc&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===Qp&&this.setComparing(this.hasAttribute(Qp))}forwardPlayerAttributes(){for(const t of[Pa,Na]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=Sr.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(Ui.isCase(i)){Ui.check(i);const n=Ui.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=ar.recording(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?Ui.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}set citedMoments(t){this.sceneElement.ufoElement.citedMoments=t}get playedSeconds(){return this.sceneElement.ufoElement.currentTime/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 Sr.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=Ui.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:ar.recording(r.sighting)})),this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1&&!this.hasAttribute(Bh);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(Kc)?.trim();if(!e)return;const i=t.find(r=>this.plain(r).observer?.id===e);if(i)return i;const n=this.caseSource;if(n){const r=t.find(a=>Ui.accountIds(n.json,n.url,a.src,this.plain(a).id).includes(e));if(r)return r}const s=t.find(r=>r.src.split("/").pop()===e.split("/").pop());return s||(/^\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===t0))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===t0}editorUrl(){if(!this.currentSrc)return V1;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${V1}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${V1}?file=${encodeURIComponent(t.href)}`}get editorHref(){return this.editorUrl()}shownTrackUrl(){return this.readingUrlOf(this.interpretationSelect.value)}shareSubject={module:"rr0-sighting",link:()=>this.playUrl(),element:()=>this.replayElement()};replayElement(){const t=this.sharedAddress(),i=[...t.observer?[[Kc,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?[`${Kc}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${w0}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${w0}/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([G1,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Pa,""]),t.milestones.input.checked||e.push([Na,""]),t.compare.input.checked&&e.push([Qp,""]),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&&!this.hasAttribute(x0);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,t0,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=t0,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(e0,this.messages?.account??"",()=>Promise.resolve(r));const a=this.caseSource;a&&Ui.interpretationEvents(a.json,Ui.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,()=>Ui.interpretationOf(u,a.url,m=>Sr.recording(m)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${i0}${u}`,`${this.variantLabel(d)} (${this.messages?.verdicts[d.variant.verdict]??""})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const l=e&&[...this.interpretationSelect.options].some(u=>u.value===i),h=this.askedInterpretation()??(l?i:e0);this.interpretationSelect.value=h,h===e0?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(h),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2||this.hasAttribute(Bh),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(e0,this.messages?.account??"");for(const{index:i,kept:n}of t)e(`${i0}${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(i0)?Number(t.slice(i0.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"?" : ":": "}askedInterpretation(){const t=this.getAttribute(b0)?.trim(),e=this.caseSource;if(!t||!e)return;const i=this.entries.find(r=>r.src===this.currentSrc);if(!i)return;const s=Ui.interpretationEvents(e.json,Ui.accountIds(e.json,e.url,i.src,this.plain(i).id)).findIndex(r=>r.id===t||typeof r.url=="string"&&new URL(r.url,e.url).href===new URL(t,location.href).href);return s>=0?`case-${s}`:void 0}async chooseInterpretation(t){const e=++this.interpretationToken,i=this.interpretationLoaders.get(t),n=i?await i().catch(d=>{console.warn(`<rr0-sighting>: could not read interpretation "${t}":`,d)}):void 0,s=this.readingUrlOf(t),r=s?await Sr.recording(s).catch(()=>{}):void 0;if(e!==this.interpretationToken)return;const a=this.entries.find(d=>d.src===this.currentSrc),c=a&&r&&"timeline"in r?this.bestCases?.bestSceneOf(a.sighting,r):void 0,l=c??r,h=c?.interpretation&&n?{...n,bodies:[...n.bodies.map(d=>{const f=c.interpretation.bodies.find(p=>p.id===d.id);return f?{...d,track:f.track}:d}),...c.interpretation.bodies.filter(d=>!n.bodies.some(f=>f.id===d.id))]}:n,u=a&&l&&"timeline"in l&&qc.changesTheScene(a.sighting,l)?{...l,timeline:l.timeline.keyframes?.length?l.timeline:a.sighting.timeline}:void 0;u&&s?this.showScene(u,s):this.readingScene&&a&&this.showScene(a.sighting,a.src,!0),this.readingScene=u!==void 0,this.sceneElement.interpretation=h,this.showReadingFindings(a,l),this.editLink.href=this.editorUrl(),this.dispatchEvent(new CustomEvent("interpretationchange",{detail:{track:this.shownTrackUrl()}})),this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation),this.showVariantMoved()}readingUrlOf(t){const e=this.caseSource,i=this.entries.find(r=>r.src===this.currentSrc),n=/^case-(\d+)$/.exec(t);if(!e||!i||!n)return;const s=Ui.interpretationEvents(e.json,Ui.accountIds(e.json,e.url,i.src,this.plain(i).id))[Number(n[1])];return s?.url?new URL(s.url,e.url).href:void 0}static SCENE_FIELDS=["time","utcOffsetHours","place","observerTrack","weatherTrack","decor","instrument","lens","film","exposureSeconds","iso","references","lighting","lightPollution","vehicle"];static changesTheScene(t,e){const i=n=>JSON.stringify(qc.SCENE_FIELDS.map(s=>n[s]));return i(t)!==i(e)}showScene(t,e,i=!1){const n=this.sceneElement.ufoElement.currentTime;this.sceneElement.documentUrl=e?new URL(e,location.href).href:void 0;const s=!this.sceneElement.ufoElement.playRequested,r=e?new URL(e,location.href).href:void 0;t.image?this.sceneElement.showPoster(t.image,r,s):i?this.sceneElement.showPoster(this.caseSource?.json.image,this.caseSource?.url,s):this.sceneElement.showPoster(void 0,void 0,s),this.sceneElement.sightingData=t,this.sceneElement.ufoElement.currentTime=n}showReadingFindings(t,e){const i=this.readingFindingsElement,n=this.messages,s=e?.interpretation?.findings??[],r=t&&e&&this.readingCheck?this.readingCheck.findingsOf(t.sighting,e):[],a=[...s,...r],c=a8.of(a);this.readingEntry=n&&c?{group:"summary",field:"reading",label:n.readingLabel,unit:"",fromSource:!1,value:(a.length===1?n.readingChipOne:n.readingChip).replace("{verdict}",n.readingVerdict[c]).replace("{n}",String(a.length)),color:qc.VERDICT_COLOURS[c],full:a.map(u=>`${{holds:"✓",fails:"✗",untested:"?"}[u.outcome]} ${this.said.read(u.text)??""}`+(u.outcome==="fails"?` (${n.findingAgainst[u.against??"established"]})`:"")).join(`
|
|
9873
|
-
`)}:void 0,this.summarySignature="\0",this.refreshParamSummary();const l=i.querySelector("#reading-sensitivity");if(this.readingSensible=t&&e?As.resultOf(t.sighting,e)!==void 0:!1,l.show(t?.sighting,e),this.showReadingBox(),!n||!c){i.querySelector("#reading-findings-list").hidden=!0,delete i.dataset.verdict;return}i.dataset.verdict=c,i.querySelector("#reading-verdict").textContent=(a.length===1?n.readingChipOne:n.readingChip).replace("{verdict}",n.readingVerdict[c]).replace("{n}",String(a.length));const h=i.querySelector("#reading-findings-list");i.querySelector("#reading-chip").setAttribute("aria-expanded","false"),h.hidden=!0,h.replaceChildren(...a.map(u=>{const d=document.createElement("li");d.dataset.outcome=u.outcome;const f=document.createElement("span");f.className="finding-mark",f.textContent={holds:"✓",fails:"✗",untested:"?"}[u.outcome],f.title=n.findingOutcome[u.outcome],f.setAttribute("aria-label",n.findingOutcome[u.outcome]);const p=document.createElement("span");if(p.textContent=this.said.read(u.text)??"",d.append(f,p),u.outcome==="fails"){const m=document.createElement("span");m.className="finding-against",m.textContent=`(${n.findingAgainst[u.against??"established"]})`,d.append(m)}return d}))}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=Zn.clock(this.getAttribute(KS)),i=this.plain(t).time;return(e?Zn.elapsedSince(i===void 0?void 0:Xs(i),e):void 0)??Zn.delta(this.getAttribute(G1))}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.readingScene=!1,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(FM,{detail:{src:t}}))}async runAssessments(){if(!this.messages)return;const t=++this.assessmentToken,e=await new Oy(this.messages).read(this.sceneElement.ufoElement.sighting);t===this.assessmentToken&&(this.assessmentEntries=e.entries,this.refreshParamSummary())}updateAccountLine(){const t=this.entries.find(a=>a.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??"";const s=!this.hasAttribute(x0)&&this.caseSource&&(this.said.read(this.caseSource.json.title)??this.caseSource.json.id);this.caseOfElement.hidden=!s,this.caseOfElement.textContent=s?`${this.messages?.case??""} ${s}`:"";const r=e!==void 0?`${this.messages?.accountBy??""} ${e}`.trim():void 0;this.sceneElement.filmName=[s||void 0,r].filter(Boolean).join(" - ")||void 0,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=Ze.strip(t.sighting),this.plainRecordings.set(t.sighting,e)),e}basisOf(t,e){const i=this.stripped(t).provenance,n={established:-2,measured:-1,stated:0,derived:1,assumed:2,fitted:3},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=>this.said.read(c.rationale)??"").filter(c=>c!=="");return{basis:r,rationales:a}}formatDate(t){const e=t.place?.locations?.[0],i=so((t.time?Xs(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(){const t=this.labelsShown?this.messages?.hideLabels??"":this.messages?.showLabels??"";this.labelsToggle.title=t,this.labelsToggle.setAttribute("aria-label",t),this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}showReadingBox(){const t=this.readingFindingsElement,e=this.readingEntry!==void 0&&!this.labelsShown;t.hidden=!e&&!this.readingSensible,t.querySelector("#reading-chip").hidden=!e,e||(t.querySelector("#reading-findings-list").hidden=!0)}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,this.showReadingBox(),!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})??[],i=e.map(l=>l.group).lastIndexOf("summary"),n=this.readingEntry?[this.readingEntry]:[],s=[...e.slice(0,i+1),...n,...e.slice(i+1),...this.assessmentEntries],r=s.map(l=>`${l.field}=${l.label}=${l.value}${l.unit}${l.full??""}${l.fromSource?"*":""}`).join("|");if(r===this.summarySignature)return;this.summarySignature=r;const a=[];let c;for(const l of s){c&&c.group!==l.group&&(c=void 0);const h=l.group==="summary"?this.messages?.summaryGroup??"":l.group==="observer"?this.messages?.observerGroup??"":this.messages&&l.group in this.messages.summaryGroups?this.messages.summaryGroups[l.group]:l.group==="assessment"?this.messages?.assessmentGroup??"":void 0;if(h!==void 0&&!c){const d=document.createElement("span");d.className="param-nest";const f=document.createElement("span");f.className="param-nest-label",f.textContent=h,d.append(f),c={group:l.group,element:d},a.push(d)}const u=this.paramItem(l);c?c.element.append(u):a.push(u)}this.paramSummary.replaceChildren(...a),this.syncDescription(s)}openDescription;openDescriptionTitle;syncDescription(t){this.openDescription!==void 0&&!t.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),yE.sync(this.paramSummary,this.openDescription,this.openDescriptionTitle??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.openDescriptionTitle=t.label,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,qc.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages?.location??"",r,this.basisOf(t,qc.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=w0,this.infoAppLink.textContent="UFO@home v0.178.4",Yn.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(`
|
|
9882
|
+
`;class fl extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(fl.TAG)||customElements.define(fl.TAG,fl)}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=$7;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 kT.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(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.pin.checked;this.linkField.value=e?ba.pinnedLink(t.link(),"0.179.0"):t.link(),this.fitLink();const n=`<script type="module" src="${e?ba.pinned(t.module,"0.179.0"):ba.current(t.module,import.meta.url,wu.home())}"><\/script>
|
|
9883
|
+
${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.179.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??=at(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 Zn{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(Zn.PLAIN.test(e))return Zn.num(e);const i=Zn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||Zn.num(a)>=60?void 0:Zn.num(s)*3600+Number(r)*60+Zn.num(a)}const n=Zn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?Zn.num(n[1])*3600+Zn.num(n[2])*60+Zn.num(n[3]):/^P/i.test(e)?Gh.seconds(e.toUpperCase()):void 0}static isClock(t){return Zn.clock(t)!==void 0}static clock(t){const e=Zn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,l={hour:Number(r),minute:Number(a),second:Zn.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)}}Yy();fl.register();const w0=wu.home(),Qp="compare-account",G1="start-time",KS="start-clock",Kc="observer",x0="case-named",Od="show-info",b0="interpretation",Bh="hide-pickers",t0="case",e0="account",i0="variant-",V1=`${w0}/edit/`;class qc extends HTMLElement{static get observedAttributes(){return["src","show-labels",Od,Bh,b0,x0,G1,KS,Kc,Pa,Na,Qp]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;caseOfElement;observerText;observerSelect;infoButton;infoPanel;infoAppLink;editLink;readingFindingsElement;readingSensible=!1;readingCheck;bestCases;readingScene=!1;readingEntry;static VERDICT_COLOURS={incompatible:"#e04848",unsettled:"#e08a2c",compatible:"#2e9d5b"};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>${WT}</style>${VT}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(wf),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.caseOfElement=this.shadow.getElementById("case-of"),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("labels-button"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=Kt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=n=>({input:this.shadow.getElementById(`share-opt-${n}`),label:this.shadow.getElementById(`share-opt-${n}-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"),As.register(),this.readingFindingsElement=this.shadow.getElementById("reading-findings");const i=this.shadow.getElementById("reading-chip");i.addEventListener("click",()=>{const n=i.getAttribute("aria-expanded")!=="true";i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById("reading-findings-list").hidden=!n}),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($y,n=>this.showConfrontation(n.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",n=>{n.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",n=>this.syncInfoOpen(n.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 n of[this.shareStartOn,this.shareStart,...Object.values(this.shareOptions).map(s=>s.input)])n.addEventListener("input",()=>this.refreshShareLinks());for(const n of[this.shareScope,this.shareOpens])n.addEventListener("change",()=>this.refreshShareLinks());this.isConnected&&(this.ready=this.loadLocaleMessages())}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=Ws.preferencesFor(this);this.preferences=e;const i=vo(e,Mo),[n,s,r,a]=await Promise.all([CT.load(i),FT(i),ME(i),r8.load(i)]);if(t!==this.localeToken)return;const c=i!==this.language||this.messages===void 0;this.language=i,this.messages=n,this.readingCheck=new fn(a),this.bestCases=new ee(a),this.tags=new lM(s),this.said=new Qn(e),this.summaryBuilder=new Vc(this.messages,new kM(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 l=this.entries.find(h=>h.src===this.currentSrc);l&&this.offerInterpretations(l),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(),c&&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 Qn(["en"]);tags=new lM({});connectedCallback(){Ws.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=this.loadLocaleMessages()),this.applyAskedInfo();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}applyAskedInfo(){this.isConnected&&this.hasAttribute(Od)!==this.infoOpen&&this.toggleInfoPanel()}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===b0){const n=this.entries.find(s=>s.src===this.currentSrc);n&&this.offerInterpretations(n)}if(t===Bh){const n=this.entries.find(s=>s.src===this.currentSrc);this.setEntries(this.entries,this.caseSource),n&&this.offerInterpretations(n)}if(t===Od&&this.applyAskedInfo(),t==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(t===Pa||t===Na)&&this.forwardPlayerAttributes(),t===Kc&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===Qp&&this.setComparing(this.hasAttribute(Qp))}forwardPlayerAttributes(){for(const t of[Pa,Na]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=Sr.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(Ui.isCase(i)){Ui.check(i);const n=Ui.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=ar.recording(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?Ui.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}set citedMoments(t){this.sceneElement.ufoElement.citedMoments=t}get playedSeconds(){return this.sceneElement.ufoElement.currentTime/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 Sr.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=Ui.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:ar.recording(r.sighting)})),this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1&&!this.hasAttribute(Bh);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(Kc)?.trim();if(!e)return;const i=t.find(r=>this.plain(r).observer?.id===e);if(i)return i;const n=this.caseSource;if(n){const r=t.find(a=>Ui.accountIds(n.json,n.url,a.src,this.plain(a).id).includes(e));if(r)return r}const s=t.find(r=>r.src.split("/").pop()===e.split("/").pop());return s||(/^\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===t0))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===t0}editorUrl(){if(!this.currentSrc)return V1;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${V1}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${V1}?file=${encodeURIComponent(t.href)}`}get editorHref(){return this.editorUrl()}shownTrackUrl(){return this.readingUrlOf(this.interpretationSelect.value)}shareSubject={module:"rr0-sighting",link:()=>this.playUrl(),element:()=>this.replayElement()};replayElement(){const t=this.sharedAddress(),i=[...t.observer?[[Kc,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?[`${Kc}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${w0}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${w0}/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([G1,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Pa,""]),t.milestones.input.checked||e.push([Na,""]),t.compare.input.checked&&e.push([Qp,""]),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&&!this.hasAttribute(x0);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,t0,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=t0,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(e0,this.messages?.account??"",()=>Promise.resolve(r));const a=this.caseSource;a&&Ui.interpretationEvents(a.json,Ui.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,()=>Ui.interpretationOf(u,a.url,m=>Sr.recording(m)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${i0}${u}`,`${this.variantLabel(d)} (${this.messages?.verdicts[d.variant.verdict]??""})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const l=e&&[...this.interpretationSelect.options].some(u=>u.value===i),h=this.askedInterpretation()??(l?i:e0);this.interpretationSelect.value=h,h===e0?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(h),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2||this.hasAttribute(Bh),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(e0,this.messages?.account??"");for(const{index:i,kept:n}of t)e(`${i0}${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(i0)?Number(t.slice(i0.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"?" : ":": "}askedInterpretation(){const t=this.getAttribute(b0)?.trim(),e=this.caseSource;if(!t||!e)return;const i=this.entries.find(r=>r.src===this.currentSrc);if(!i)return;const s=Ui.interpretationEvents(e.json,Ui.accountIds(e.json,e.url,i.src,this.plain(i).id)).findIndex(r=>r.id===t||typeof r.url=="string"&&new URL(r.url,e.url).href===new URL(t,location.href).href);return s>=0?`case-${s}`:void 0}async chooseInterpretation(t){const e=++this.interpretationToken,i=this.interpretationLoaders.get(t),n=i?await i().catch(d=>{console.warn(`<rr0-sighting>: could not read interpretation "${t}":`,d)}):void 0,s=this.readingUrlOf(t),r=s?await Sr.recording(s).catch(()=>{}):void 0;if(e!==this.interpretationToken)return;const a=this.entries.find(d=>d.src===this.currentSrc),c=a&&r&&"timeline"in r?this.bestCases?.bestSceneOf(a.sighting,r):void 0,l=c??r,h=c?.interpretation&&n?{...n,bodies:[...n.bodies.map(d=>{const f=c.interpretation.bodies.find(p=>p.id===d.id);return f?{...d,track:f.track}:d}),...c.interpretation.bodies.filter(d=>!n.bodies.some(f=>f.id===d.id))]}:n,u=a&&l&&"timeline"in l&&qc.changesTheScene(a.sighting,l)?{...l,timeline:l.timeline.keyframes?.length?l.timeline:a.sighting.timeline}:void 0;u&&s?this.showScene(u,s):this.readingScene&&a&&this.showScene(a.sighting,a.src,!0),this.readingScene=u!==void 0,this.sceneElement.interpretation=h,this.showReadingFindings(a,l),this.editLink.href=this.editorUrl(),this.dispatchEvent(new CustomEvent("interpretationchange",{detail:{track:this.shownTrackUrl()}})),this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation),this.showVariantMoved()}readingUrlOf(t){const e=this.caseSource,i=this.entries.find(r=>r.src===this.currentSrc),n=/^case-(\d+)$/.exec(t);if(!e||!i||!n)return;const s=Ui.interpretationEvents(e.json,Ui.accountIds(e.json,e.url,i.src,this.plain(i).id))[Number(n[1])];return s?.url?new URL(s.url,e.url).href:void 0}static SCENE_FIELDS=["time","utcOffsetHours","place","observerTrack","weatherTrack","decor","instrument","lens","film","exposureSeconds","iso","references","lighting","lightPollution","vehicle"];static changesTheScene(t,e){const i=n=>JSON.stringify(qc.SCENE_FIELDS.map(s=>n[s]));return i(t)!==i(e)}showScene(t,e,i=!1){const n=this.sceneElement.ufoElement.currentTime;this.sceneElement.documentUrl=e?new URL(e,location.href).href:void 0;const s=!this.sceneElement.ufoElement.playRequested,r=e?new URL(e,location.href).href:void 0;t.image?this.sceneElement.showPoster(t.image,r,s):i?this.sceneElement.showPoster(this.caseSource?.json.image,this.caseSource?.url,s):this.sceneElement.showPoster(void 0,void 0,s),this.sceneElement.sightingData=t,this.sceneElement.ufoElement.currentTime=n}showReadingFindings(t,e){const i=this.readingFindingsElement,n=this.messages,s=e?.interpretation?.findings??[],r=t&&e&&this.readingCheck?this.readingCheck.findingsOf(t.sighting,e):[],a=[...s,...r],c=a8.of(a);this.readingEntry=n&&c?{group:"summary",field:"reading",label:n.readingLabel,unit:"",fromSource:!1,value:(a.length===1?n.readingChipOne:n.readingChip).replace("{verdict}",n.readingVerdict[c]).replace("{n}",String(a.length)),color:qc.VERDICT_COLOURS[c],full:a.map(u=>`${{holds:"✓",fails:"✗",untested:"?"}[u.outcome]} ${this.said.read(u.text)??""}`+(u.outcome==="fails"?` (${n.findingAgainst[u.against??"established"]})`:"")).join(`
|
|
9884
|
+
`)}:void 0,this.summarySignature="\0",this.refreshParamSummary();const l=i.querySelector("#reading-sensitivity");if(this.readingSensible=t&&e?As.resultOf(t.sighting,e)!==void 0:!1,l.show(t?.sighting,e),this.showReadingBox(),!n||!c){i.querySelector("#reading-findings-list").hidden=!0,delete i.dataset.verdict;return}i.dataset.verdict=c,i.querySelector("#reading-verdict").textContent=(a.length===1?n.readingChipOne:n.readingChip).replace("{verdict}",n.readingVerdict[c]).replace("{n}",String(a.length));const h=i.querySelector("#reading-findings-list");i.querySelector("#reading-chip").setAttribute("aria-expanded","false"),h.hidden=!0,h.replaceChildren(...a.map(u=>{const d=document.createElement("li");d.dataset.outcome=u.outcome;const f=document.createElement("span");f.className="finding-mark",f.textContent={holds:"✓",fails:"✗",untested:"?"}[u.outcome],f.title=n.findingOutcome[u.outcome],f.setAttribute("aria-label",n.findingOutcome[u.outcome]);const p=document.createElement("span");if(p.textContent=this.said.read(u.text)??"",d.append(f,p),u.outcome==="fails"){const m=document.createElement("span");m.className="finding-against",m.textContent=`(${n.findingAgainst[u.against??"established"]})`,d.append(m)}return d}))}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=Zn.clock(this.getAttribute(KS)),i=this.plain(t).time;return(e?Zn.elapsedSince(i===void 0?void 0:Xs(i),e):void 0)??Zn.delta(this.getAttribute(G1))}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.readingScene=!1,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(FM,{detail:{src:t}}))}async runAssessments(){if(!this.messages)return;const t=++this.assessmentToken,e=await new Oy(this.messages).read(this.sceneElement.ufoElement.sighting);t===this.assessmentToken&&(this.assessmentEntries=e.entries,this.refreshParamSummary())}updateAccountLine(){const t=this.entries.find(a=>a.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??"";const s=!this.hasAttribute(x0)&&this.caseSource&&(this.said.read(this.caseSource.json.title)??this.caseSource.json.id);this.caseOfElement.hidden=!s,this.caseOfElement.textContent=s?`${this.messages?.case??""} ${s}`:"";const r=e!==void 0?`${this.messages?.accountBy??""} ${e}`.trim():void 0;this.sceneElement.filmName=[s||void 0,r].filter(Boolean).join(" - ")||void 0,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=Ze.strip(t.sighting),this.plainRecordings.set(t.sighting,e)),e}basisOf(t,e){const i=this.stripped(t).provenance,n={established:-2,measured:-1,stated:0,derived:1,assumed:2,fitted:3},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=>this.said.read(c.rationale)??"").filter(c=>c!=="");return{basis:r,rationales:a}}formatDate(t){const e=t.place?.locations?.[0],i=so((t.time?Xs(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(){const t=this.labelsShown?this.messages?.hideLabels??"":this.messages?.showLabels??"";this.labelsToggle.title=t,this.labelsToggle.setAttribute("aria-label",t),this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}showReadingBox(){const t=this.readingFindingsElement,e=this.readingEntry!==void 0&&!this.labelsShown;t.hidden=!e&&!this.readingSensible,t.querySelector("#reading-chip").hidden=!e,e||(t.querySelector("#reading-findings-list").hidden=!0)}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,this.showReadingBox(),!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})??[],i=e.map(l=>l.group).lastIndexOf("summary"),n=this.readingEntry?[this.readingEntry]:[],s=[...e.slice(0,i+1),...n,...e.slice(i+1),...this.assessmentEntries],r=s.map(l=>`${l.field}=${l.label}=${l.value}${l.unit}${l.full??""}${l.fromSource?"*":""}`).join("|");if(r===this.summarySignature)return;this.summarySignature=r;const a=[];let c;for(const l of s){c&&c.group!==l.group&&(c=void 0);const h=l.group==="summary"?this.messages?.summaryGroup??"":l.group==="observer"?this.messages?.observerGroup??"":this.messages&&l.group in this.messages.summaryGroups?this.messages.summaryGroups[l.group]:l.group==="assessment"?this.messages?.assessmentGroup??"":void 0;if(h!==void 0&&!c){const d=document.createElement("span");d.className="param-nest";const f=document.createElement("span");f.className="param-nest-label",f.textContent=h,d.append(f),c={group:l.group,element:d},a.push(d)}const u=this.paramItem(l);c?c.element.append(u):a.push(u)}this.paramSummary.replaceChildren(...a),this.syncDescription(s)}openDescription;openDescriptionTitle;syncDescription(t){this.openDescription!==void 0&&!t.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),yE.sync(this.paramSummary,this.openDescription,this.openDescriptionTitle??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.openDescriptionTitle=t.label,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,qc.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages?.location??"",r,this.basisOf(t,qc.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=w0,this.infoAppLink.textContent="UFO@home v0.179.0",Yn.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(`
|
|
9874
9885
|
`)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const jo="rr0-sighting",FM="observerchange";function z3(){Yy(),fl.register(),customElements.get(jo)||customElements.define(jo,qc)}class Qo extends HTMLElement{static TAG="rr0-readings-comparison";static CSS=`
|
|
9875
9886
|
:host { display: block; font-size: 13px; line-height: 1.4; }
|
|
9876
9887
|
:host([hidden]) { display: none; }
|
|
@@ -9901,10 +9912,7 @@ button.open { display: inline-flex; align-items: center; gap: 6px; cursor: point
|
|
|
9901
9912
|
.option input { margin: 2px 0 0; }
|
|
9902
9913
|
${Ia.css(".menu")}
|
|
9903
9914
|
.menu:popover-open { position-area: bottom span-left; margin: .35em 0 0; }
|
|
9904
|
-
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(Zc.TAG)||customElements.define(Zc.TAG,Zc)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=Ws.preferencesFor(this),this.language=vo([...this.preferences],Mo),this.messages=await BT.load(this.language),this.draw()}draw(){const t=this.messages,e=document.createElement("style");e.textContent=Zc.CSS;const i=document.createElement("button");i.type="button",i.className="open",i.setAttribute("part","button"),i.title=t.hint,i.setAttribute("aria-label",t.hint),i.setAttribute("aria-haspopup","menu"),i.innerHTML=Zc.ICON,this.getAttribute("variant")==="pill"&&i.append(Object.assign(document.createElement("span"),{textContent:t.button}));const n=document.createElement("div");n.className="menu",n.setAttribute("role","menu"),Ia.attach(i,n);const s=[["html",t.html,t.htmlHint],["print",t.print,t.printHint],["json",t.json,t.jsonHint],["csv",t.csv,t.csvHint]];n.append(...s.map(([c,l,h])=>{const u=document.createElement("button");return u.type="button",u.setAttribute("role","menuitem"),u.append(Object.assign(document.createElement("strong"),{textContent:l}),Object.assign(document.createElement("small"),{textContent:h})),u.addEventListener("click",()=>void this.export(c,n)),u}));const r=document.createElement("label");r.className="option",this.withPictures=Object.assign(document.createElement("input"),{type:"checkbox"});const a=document.createElement("span");a.append(Object.assign(document.createElement("strong"),{textContent:t.pictures}),Object.assign(document.createElement("small"),{textContent:t.picturesHint})),r.append(this.withPictures,a),n.append(r),this.status=Object.assign(document.createElement("p"),{className:"status",hidden:!0}),this.status.setAttribute("role","status"),n.append(this.status),i.addEventListener("click",()=>Ia.show(n,n.hidden)),this.shadowRoot.replaceChildren(e,i,n)}async export(t,e){const i=this.messages;if(this.source){this.status.textContent=i.working,this.status.hidden=!1;try{const[{CaseReportExport:n},s]=await Promise.all([at(()=>import("./CaseReportExport-
|
|
9905
|
-
.icon { display: block; flex: none; }
|
|
9906
|
-
button:has(> .icon:only-child) { display: inline-flex; align-items: center; justify-content: center; }
|
|
9907
|
-
`}const Y7="interviewseek",K7=`
|
|
9915
|
+
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(Zc.TAG)||customElements.define(Zc.TAG,Zc)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=Ws.preferencesFor(this),this.language=vo([...this.preferences],Mo),this.messages=await BT.load(this.language),this.draw()}draw(){const t=this.messages,e=document.createElement("style");e.textContent=Zc.CSS;const i=document.createElement("button");i.type="button",i.className="open",i.setAttribute("part","button"),i.title=t.hint,i.setAttribute("aria-label",t.hint),i.setAttribute("aria-haspopup","menu"),i.innerHTML=Zc.ICON,this.getAttribute("variant")==="pill"&&i.append(Object.assign(document.createElement("span"),{textContent:t.button}));const n=document.createElement("div");n.className="menu",n.setAttribute("role","menu"),Ia.attach(i,n);const s=[["html",t.html,t.htmlHint],["print",t.print,t.printHint],["json",t.json,t.jsonHint],["csv",t.csv,t.csvHint]];n.append(...s.map(([c,l,h])=>{const u=document.createElement("button");return u.type="button",u.setAttribute("role","menuitem"),u.append(Object.assign(document.createElement("strong"),{textContent:l}),Object.assign(document.createElement("small"),{textContent:h})),u.addEventListener("click",()=>void this.export(c,n)),u}));const r=document.createElement("label");r.className="option",this.withPictures=Object.assign(document.createElement("input"),{type:"checkbox"});const a=document.createElement("span");a.append(Object.assign(document.createElement("strong"),{textContent:t.pictures}),Object.assign(document.createElement("small"),{textContent:t.picturesHint})),r.append(this.withPictures,a),n.append(r),this.status=Object.assign(document.createElement("p"),{className:"status",hidden:!0}),this.status.setAttribute("role","status"),n.append(this.status),i.addEventListener("click",()=>Ia.show(n,n.hidden)),this.shadowRoot.replaceChildren(e,i,n)}async export(t,e){const i=this.messages;if(this.source){this.status.textContent=i.working,this.status.hidden=!1;try{const[{CaseReportExport:n},s]=await Promise.all([at(()=>import("./CaseReportExport-C30Foqx0.js"),[],import.meta.url),this.source()]);await n.make(t,s,this.language,this.preferences,this.withPictures?.checked??!1,(r,a)=>{this.status.textContent=i.drawing.replace("{done}",String(r)).replace("{total}",String(a))}),this.status.hidden=!0,Ia.show(e,!1)}catch{this.status.textContent=i.failed}}}}const Y7="interviewseek",K7=`
|
|
9908
9916
|
<header class="case-head">
|
|
9909
9917
|
<div class="case-bar">
|
|
9910
9918
|
<p id="case-kind" class="case-kind"></p>
|
|
@@ -10011,4 +10019,4 @@ button:has(> .icon:only-child) { display: inline-flex; align-items: center; just
|
|
|
10011
10019
|
.event-body { grid-template-columns: minmax(0, 1fr); grid-template-areas: "pill" "open" "meta" "links"; }
|
|
10012
10020
|
.event-meta { justify-self: start; }
|
|
10013
10021
|
}
|
|
10014
|
-
`,Hh="rr0-case",W1="show-timeline",X1="open-events";class mm extends HTMLElement{static get observedAttributes(){return["src","show-labels",Od,W1,X1,Kc]}static PASSED_ON=["show-labels"];shadow;openEvents;eventList;shown=new Map;messages;said=new Qn(["en"]);json;url;entries=[];constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=q7;const e=document.createElement("div");e.innerHTML=K7,this.shadow.append(t,e),z3(),this.eventList=this.byId("case-events"),Qo.register(),Zc.register(),this.byId("export").source=async()=>{const r=this.json,a=new Map;return await Promise.all(this.entries.filter(c=>c.kind!=="interview"&&c.url).map(async c=>{try{a.set(c.url,await Sr.recording(c.url))}catch{}})),{caseJson:r,caseUrl:this.url,recordings:a}},this.openEvents=this.byId("open-events"),this.openEvents.addEventListener(Y7,r=>{const{at:a,sighting:c}=r.detail;this.seekObservation(a,c)}),this.openEvents.addEventListener(i3,r=>{const a=r.target?.closest?.(".open-event");this.followReplay(a??void 0)}),fl.register();const i=this.byId("share");i.innerHTML=Kt.SHARE;const n=this.byId("share-dialog");n.subject=this.shareSubject,i.addEventListener("click",()=>{this.url&&n.open()}),this.byId("edit").addEventListener("click",()=>{const r=this.editorUrl();r&&window.open(r,"_blank","noopener")}),this.byId("info").addEventListener("click",()=>this.showSummary(this.byId("case-summary").hidden)),this.byId("timeline-button").addEventListener("click",()=>{this.showTimeline(this.byId("case-events").parentElement.hidden)})}shareSubject={module:"rr0-sighting",link:()=>`${wu.home()}/play/?file=${encodeURIComponent(this.url??"")}`,element:()=>`<${Hh} src="${this.url??""}"></${Hh}>`};byId(t){return this.shadow.getElementById(t)}showSummary(t){this.byId("case-summary").hidden=!t,this.byId("info").setAttribute("aria-expanded",String(t))}showTimeline(t){this.byId("case-events").parentElement.hidden=!t,this.byId("timeline-button").setAttribute("aria-pressed",String(t));for(const e of this.players())e.toggleAttribute(Bh,t)}connectedCallback(){this.loadMessages(),this.showTimeline(this.getAttribute(W1)!=="false"),this.showSummary(this.hasAttribute(Od));const t=this.getAttribute("src");t&&this.load(t).catch(e=>console.warn(`<${Hh}> could not read ${t}:`,e))}attributeChangedCallback(t,e,i){if(!(!this.isConnected||i===e))if(t==="src"&&i)this.load(i);else if(t===W1)this.showTimeline(i!=="false");else if(t===X1){if(i==="all")for(let n=0;n<this.entries.length;n++)this.open(n)}else for(const n of this.players())i===null?n.removeAttribute(t):n.setAttribute(t,i)}async loadMessages(){const t=vo(Ws.preferencesFor(this),Mo);this.said=new Qn([t,"en"]),this.messages=await NT(t),await this.byId("share-dialog").useLanguage(t),this.draw()}async load(t){this.url=new URL(t,location.href).href;const e=await Sr.recording(this.url);if(!Ui.isCase(e))throw new Error(`${t} is not a case: <${Hh}> reads a case.json`);if(this.json=e,this.entries=mm.inTime((e.events??[]).map(n=>this.entryOf(n)).filter(n=>n!==void 0)),this.shown.clear(),this.openEvents.replaceChildren(),this.draw(),this.compareReadings(),this.getAttribute(X1)==="all"){for(let n=0;n<this.entries.length;n++)await this.open(n);return}const i=this.entries.findIndex(n=>n.kind!=="interview");i>=0&&this.open(i)}static inTime(t){const e=new Map(t.filter(s=>s.event.id!==void 0).map(s=>[s.event.id,s])),i=s=>s.when!==""||s.kind!=="reading"?s.when:[s.event.interpretationOf].flat().map(a=>a===void 0?void 0:e.get(a)).find(a=>a!==void 0&&a.when!=="")?.when??"",n=s=>s.kind==="reading"?1:0;return t.map((s,r)=>({entry:s,index:r})).sort((s,r)=>i(s.entry).localeCompare(i(r.entry))||n(s.entry)-n(r.entry)||s.index-r.index).map(({entry:s})=>s)}entryOf(t){if(typeof t.url!="string"||t.url==="")return;const e=t.eventType===Ui.INTERVIEW_EVENT?"interview":t.eventType===Ui.SIGHTING_EVENT?t.interpretationOf===void 0?"observation":"reading":void 0;if(e)return{event:t,kind:e,url:new URL(t.url,this.url??location.href).href,title:this.said.read(t.title)??t.id??"",when:String(t.time??"")}}compareReadings(){const t=this.byId("readings-comparison"),e=new Map,i=s=>{let r=e.get(s);return r||(r=Sr.recording(s).then(a=>a,()=>{}),e.set(s,r)),r},n=async s=>Promise.all(this.entries.flatMap((r,a)=>{if(r.kind!=="reading")return[];const c=this.accountOf(r);return[(async()=>({title:r.title,witness:c?.title??"",...s&&c?.url&&r.url?{account:await i(c.url),reading:await i(r.url)}:{},open:()=>void this.open(a).then(()=>this.shown.get(a)?.scrollIntoView({block:"start",behavior:"smooth"}))}))()]}));n(!1).then(s=>t.show(s,()=>n(!0)))}accountOf(t){const e=[t.event.interpretationOf].flat().filter(i=>i!==void 0);return this.entries.find(i=>i.kind==="observation"&&e.includes(i.event.id??""))}editorUrl(){if(!this.url)return;const t=new URL("/edit/",location.href);return t.searchParams.set("file",this.url),t.href}async toggle(t){this.shown.has(t)?this.shut(t):await this.open(t)}async open(t){const e=this.entries[t];if(!e||!e.url||this.shown.has(t))return;const i=document.createElement("section");if(i.className="open-event",i.dataset.at=String(t),e.kind==="interview"){const n=document.createElement("p");n.className="open-title",n.textContent=e.title,i.append(n)}if(e.kind==="interview"){const{register:n}=await at(async()=>{const{register:r}=await import("./InterviewElement-Byb_sxbO.js");return{register:r}},[],import.meta.url);n();const s=document.createElement("rr0-interview");s.setAttribute("src",e.url),i.append(s),window.setTimeout(()=>{this.followReplay(),this.markCitedMoments()},300)}else{const n=document.createElement(jo);n.setAttribute(x0,""),n.toggleAttribute(Bh,!this.byId("case-events").parentElement.hidden),n.setAttribute("src",this.url??"");const s=e.kind==="reading"?this.accountOf(e):void 0;n.setAttribute(Kc,(s??e).url??""),e.kind==="reading"&&n.setAttribute(b0,e.url),queueMicrotask(()=>{for(const r of mm.PASSED_ON){const a=this.getAttribute(r);a!==null&&n.setAttribute(r,a)}}),n.addEventListener(FM,r=>{this.dispatchEvent(new CustomEvent(FM,{detail:r.detail}))}),i.append(n)}this.shown.set(t,i),this.order(),this.draw(),e.kind!=="interview"&&window.setTimeout(()=>this.markCitedMoments(),300)}followReplay(t){const e=t??[...this.shown.values()].find(r=>r.querySelector(jo)),i=e?Number(e.dataset.at):NaN,n=Number.isNaN(i)?void 0:this.entries[i],s=e?.querySelector(jo);if(!(!n||!s)){for(const[r,a]of this.shown){if(this.entries[r]?.kind!=="interview")continue;a.querySelector("rr0-interview")?.revealAt?.(s.playedSeconds,n.event.id)}return e}}markCitedMoments(){for(const[t,e]of this.shown){const i=this.entries[t],n=e.querySelector(jo);if(!i||!n)continue;const s=[];for(const[r,a]of this.shown){if(this.entries[r]?.kind!=="interview")continue;const c=a.querySelector("rr0-interview");s.push(...c?.momentsCited?.(i.event.id)??[])}n.citedMoments=s.sort((r,a)=>r.at-a.at)}}shut(t){this.shown.get(t)?.remove(),this.shown.delete(t),this.markCitedMoments(),this.draw()}order(){const t=[...this.shown.entries()].sort(([e],[i])=>e-i).map(([,e])=>e);this.openEvents.replaceChildren(...t)}async seekObservation(t,e){const i=this.entries.findIndex(r=>r.kind!=="interview"&&(r.event.id===e||e!==void 0&&r.url?.endsWith(`/${e}.json`))),n=i>=0?i:this.entries.findIndex(r=>r.kind!=="interview");if(n<0)return;this.shown.has(n)||await this.open(n),this.shown.get(n)?.querySelector(jo)?.seekTo(t,e),this.shown.get(n)?.scrollIntoView({block:"nearest",behavior:"smooth"})}authors(t){const e=this.messages,i=(t??[]).map(n=>"people"in n?n.people:"org"in n?n.org:this.said.read(n.title)??"").filter(n=>n!=="");return i.length<2||!e?i.join(", "):`${i.slice(0,-1).join(", ")} ${e.linkAnd} ${i[i.length-1]}`}linkedTo(t){const e=this.messages;if(e){if(t.kind==="reading"){const i=[t.event.interpretationOf].flat().filter(s=>s!==void 0),n=this.entries.map((s,r)=>i.includes(s.event.id??"")?r:-1).filter(s=>s>=0);return n.length>0?{heading:e.interpretationOf,to:n}:void 0}if(t.kind==="observation"){const i=this.entries.map((n,s)=>n.kind==="interview"&&[n.event.interviewOf].flat().includes(t.event.id)?s:-1).filter(n=>n>=0);return i.length>0?{heading:e.passagesHeading,to:i}:void 0}}}draw(){const t=this.messages,e=this.json;if(!t||!e)return;this.byId("case-kind").textContent=t.caseHeading,this.byId("case-title").textContent=this.said.read(e.title)??e.id??"";const i=this.said.read(e.summary)??"",n=this.byId("case-summary");n.textContent=i;const s=this.byId("info");s.hidden=i==="",s.title=t.caseSummary,s.setAttribute("aria-label",t.caseSummary),i===""&&this.showSummary(!1),this.byId("events-heading").textContent=t.eventsHeading,this.byId("events-icon").innerHTML=xe.CLOCK;const r=this.byId("share");r.title=t.shareCase,r.setAttribute("aria-label",t.shareCase);const a=this.byId("edit");a.title=t.editCase,a.setAttribute("aria-label",t.editCase),this.eventList.replaceChildren(...this.entries.map((c,l)=>this.card(c,l,t)))}card(t,e,i){const n=document.createElement("li");n.className="event",n.dataset.kind=t.kind,n.dataset.at=String(e),this.shown.has(e)&&(n.dataset.open="");const s=document.createElement("span");s.className="event-mark",s.innerHTML={observation:xe.WITNESS,reading:xe.SUMMARY,interview:xe.INTERVIEW}[t.kind],s.setAttribute("aria-hidden","true");const r=document.createElement("span");r.className="kind-pill",r.dataset.kind=t.kind,r.textContent={observation:i.kindObservation,reading:i.kindReading,interview:i.kindInterview}[t.kind];const a=document.createElement("button");a.type="button",a.className="event-open",a.textContent=t.title,a.title=i.openEvent,a.addEventListener("click",()=>void this.toggle(e));const c=document.createElement("span");c.className="event-meta",c.textContent=t.when.replace("T"," ");const l=document.createElement("span");l.className="event-links";const h=this.linkedTo(t);h&&l.append(`${h.heading} `,...h.to.flatMap((f,p)=>{const m=document.createElement("button");m.type="button",m.className="event-ref",m.textContent=this.entries[f].title,m.title=i.openEvent,m.addEventListener("click",()=>void this.open(f));const g=v=>this.eventList.querySelector(`.event[data-at="${f}"]`)?.classList.toggle("aimed",v);for(const[v,M]of[["mouseenter",!0],["mouseleave",!1],["focus",!0],["blur",!1]])m.addEventListener(v,()=>g(M));return p===0?[m]:[document.createTextNode(` ${i.linkAnd} `),m]}));const u=t.kind==="observation"?"":this.authors(t.event.by);u!==""&&l.append(`${h?" ":""}${i.byAuthor} ${u}`);const d=document.createElement("div");return d.className="event-body",d.append(r,a,c,l),n.append(s,d),n}async loadFromSrc(t){await this.load(t)}get scene(){return this.players()[0]?.scene}players(){return[...this.shown.entries()].sort(([t],[e])=>t-e).map(([,t])=>t.querySelector(jo)).filter(t=>t!==null)}get sightingData(){return this.players()[0]?.sightingData}get player(){return this.players()[0]}}function Z7(){customElements.get(Hh)||customElements.define(Hh,mm)}z3();Z7();export{ok as $,lr as A,Nt as B,rt as C,T0 as D,be as E,ar as F,Ke as G,Ws as H,J7 as I,pe as J,ec as K,cM as L,Re as M,ye as N,Jn as O,Kt as P,Rr as Q,Ct as R,Qn as S,Li as T,Mo as U,Pr as V,gc as W,dk as X,pk as Y,$0 as Z,at as _,Sr as a,cr as a$,Je as a0,Tr as a1,T as a2,De as a3,fa as a4,EI as a5,bt as a6,Ie as a7,Eo as a8,Gt as a9,Bi as aA,U7 as aB,Xy as aC,z7 as aD,Oe as aE,u0 as aF,Z0 as aG,ph as aH,xr as aI,C0 as aJ,xe as aK,Es as aL,Oa as aM,j7 as aN,tk as aO,Q7 as aP,Rf as aQ,uk as aR,ck as aS,G0 as aT,CA as aU,q0 as aV,nk as aW,Yw as aX,lk as aY,fk as aZ,uA as a_,ek as aa,k8 as ab,Qv as ac,ir as ad,c0 as ae,Tc as af,Uu as ag,Is as ah,Tn as ai,hk as aj,ml as ak,Cn as al,jn as am,Ni as an,Qe as ao,si as ap,tn as aq,ts as ar,es as as,ak as at,Bn as au,Me as av,Wn as aw,zi as ax,hn as ay,vs as az,Y7 as b,zf as b0,cg as b1,F4 as b2,bc as b3,wv as b4,Qi as b5,Ga as b6,VR as b7,fi as b8,ik as b9,Vt as bA,Ch as bB,Py as bC,Bt as bD,Ay as bE,Mc as bF,Yr as bG,Ds as bH,gs as bI,bu as bJ,en as bK,mk as bL,sk as ba,pA as bb,rk as bc,ur as bd,fA as be,fx as bf,FR as bg,E3 as bh,z0 as bi,Jv as bj,IA as bk,_y as bl,Ty as bm,He as bn,Ba as bo,Tf as bp,Dt as bq,_n as br,la as bs,La as bt,Ei as bu,xc as bv,rf as bw,mt as bx,v5 as by,iu as bz,Un as c,qA as d,Xn as e,ZA as f,gf as g,vh as h,Ze as i,Mn as j,YM as k,$s as l,re as m,r8 as n,fn as o,fE as p,so as q,Xr as r,vo as s,Sh as t,Cd as u,Bs as v,TI as w,yt as x,tt as y,vd as z};
|
|
10022
|
+
`,Hh="rr0-case",W1="show-timeline",X1="open-events";class mm extends HTMLElement{static get observedAttributes(){return["src","show-labels",Od,W1,X1,Kc]}static PASSED_ON=["show-labels"];shadow;openEvents;eventList;shown=new Map;messages;said=new Qn(["en"]);json;url;entries=[];constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=q7;const e=document.createElement("div");e.innerHTML=K7,this.shadow.append(t,e),z3(),this.eventList=this.byId("case-events"),Qo.register(),Zc.register(),this.byId("export").source=async()=>{const r=this.json,a=new Map;return await Promise.all(this.entries.filter(c=>c.kind!=="interview"&&c.url).map(async c=>{try{a.set(c.url,await Sr.recording(c.url))}catch{}})),{caseJson:r,caseUrl:this.url,recordings:a}},this.openEvents=this.byId("open-events"),this.openEvents.addEventListener(Y7,r=>{const{at:a,sighting:c}=r.detail;this.seekObservation(a,c)}),this.openEvents.addEventListener(i3,r=>{const a=r.target?.closest?.(".open-event");this.followReplay(a??void 0)}),fl.register();const i=this.byId("share");i.innerHTML=Kt.SHARE;const n=this.byId("share-dialog");n.subject=this.shareSubject,i.addEventListener("click",()=>{this.url&&n.open()}),this.byId("edit").addEventListener("click",()=>{const r=this.editorUrl();r&&window.open(r,"_blank","noopener")}),this.byId("info").addEventListener("click",()=>this.showSummary(this.byId("case-summary").hidden)),this.byId("timeline-button").addEventListener("click",()=>{this.showTimeline(this.byId("case-events").parentElement.hidden)})}shareSubject={module:"rr0-sighting",link:()=>`${wu.home()}/play/?file=${encodeURIComponent(this.url??"")}`,element:()=>`<${Hh} src="${this.url??""}"></${Hh}>`};byId(t){return this.shadow.getElementById(t)}showSummary(t){this.byId("case-summary").hidden=!t,this.byId("info").setAttribute("aria-expanded",String(t))}showTimeline(t){this.byId("case-events").parentElement.hidden=!t,this.byId("timeline-button").setAttribute("aria-pressed",String(t));for(const e of this.players())e.toggleAttribute(Bh,t)}connectedCallback(){this.loadMessages(),this.showTimeline(this.getAttribute(W1)!=="false"),this.showSummary(this.hasAttribute(Od));const t=this.getAttribute("src");t&&this.load(t).catch(e=>console.warn(`<${Hh}> could not read ${t}:`,e))}attributeChangedCallback(t,e,i){if(!(!this.isConnected||i===e))if(t==="src"&&i)this.load(i);else if(t===W1)this.showTimeline(i!=="false");else if(t===X1){if(i==="all")for(let n=0;n<this.entries.length;n++)this.open(n)}else for(const n of this.players())i===null?n.removeAttribute(t):n.setAttribute(t,i)}async loadMessages(){const t=vo(Ws.preferencesFor(this),Mo);this.said=new Qn([t,"en"]),this.messages=await NT(t),await this.byId("share-dialog").useLanguage(t),this.draw()}async load(t){this.url=new URL(t,location.href).href;const e=await Sr.recording(this.url);if(!Ui.isCase(e))throw new Error(`${t} is not a case: <${Hh}> reads a case.json`);if(this.json=e,this.entries=mm.inTime((e.events??[]).map(n=>this.entryOf(n)).filter(n=>n!==void 0)),this.shown.clear(),this.openEvents.replaceChildren(),this.draw(),this.compareReadings(),this.getAttribute(X1)==="all"){for(let n=0;n<this.entries.length;n++)await this.open(n);return}const i=this.entries.findIndex(n=>n.kind!=="interview");i>=0&&this.open(i)}static inTime(t){const e=new Map(t.filter(s=>s.event.id!==void 0).map(s=>[s.event.id,s])),i=s=>s.when!==""||s.kind!=="reading"?s.when:[s.event.interpretationOf].flat().map(a=>a===void 0?void 0:e.get(a)).find(a=>a!==void 0&&a.when!=="")?.when??"",n=s=>s.kind==="reading"?1:0;return t.map((s,r)=>({entry:s,index:r})).sort((s,r)=>i(s.entry).localeCompare(i(r.entry))||n(s.entry)-n(r.entry)||s.index-r.index).map(({entry:s})=>s)}entryOf(t){if(typeof t.url!="string"||t.url==="")return;const e=t.eventType===Ui.INTERVIEW_EVENT?"interview":t.eventType===Ui.SIGHTING_EVENT?t.interpretationOf===void 0?"observation":"reading":void 0;if(e)return{event:t,kind:e,url:new URL(t.url,this.url??location.href).href,title:this.said.read(t.title)??t.id??"",when:String(t.time??"")}}compareReadings(){const t=this.byId("readings-comparison"),e=new Map,i=s=>{let r=e.get(s);return r||(r=Sr.recording(s).then(a=>a,()=>{}),e.set(s,r)),r},n=async s=>Promise.all(this.entries.flatMap((r,a)=>{if(r.kind!=="reading")return[];const c=this.accountOf(r);return[(async()=>({title:r.title,witness:c?.title??"",...s&&c?.url&&r.url?{account:await i(c.url),reading:await i(r.url)}:{},open:()=>void this.open(a).then(()=>this.shown.get(a)?.scrollIntoView({block:"start",behavior:"smooth"}))}))()]}));n(!1).then(s=>t.show(s,()=>n(!0)))}accountOf(t){const e=[t.event.interpretationOf].flat().filter(i=>i!==void 0);return this.entries.find(i=>i.kind==="observation"&&e.includes(i.event.id??""))}editorUrl(){if(!this.url)return;const t=new URL("/edit/",location.href);return t.searchParams.set("file",this.url),t.href}async toggle(t){this.shown.has(t)?this.shut(t):await this.open(t)}async open(t){const e=this.entries[t];if(!e||!e.url||this.shown.has(t))return;const i=document.createElement("section");if(i.className="open-event",i.dataset.at=String(t),e.kind==="interview"){const n=document.createElement("p");n.className="open-title",n.textContent=e.title,i.append(n)}if(e.kind==="interview"){const{register:n}=await at(async()=>{const{register:r}=await import("./InterviewElement-BduwyUn5.js");return{register:r}},[],import.meta.url);n();const s=document.createElement("rr0-interview");s.setAttribute("src",e.url),i.append(s),window.setTimeout(()=>{this.followReplay(),this.markCitedMoments()},300)}else{const n=document.createElement(jo);n.setAttribute(x0,""),n.toggleAttribute(Bh,!this.byId("case-events").parentElement.hidden),n.setAttribute("src",this.url??"");const s=e.kind==="reading"?this.accountOf(e):void 0;n.setAttribute(Kc,(s??e).url??""),e.kind==="reading"&&n.setAttribute(b0,e.url),queueMicrotask(()=>{for(const r of mm.PASSED_ON){const a=this.getAttribute(r);a!==null&&n.setAttribute(r,a)}}),n.addEventListener(FM,r=>{this.dispatchEvent(new CustomEvent(FM,{detail:r.detail}))}),i.append(n)}this.shown.set(t,i),this.order(),this.draw(),e.kind!=="interview"&&window.setTimeout(()=>this.markCitedMoments(),300)}followReplay(t){const e=t??[...this.shown.values()].find(r=>r.querySelector(jo)),i=e?Number(e.dataset.at):NaN,n=Number.isNaN(i)?void 0:this.entries[i],s=e?.querySelector(jo);if(!(!n||!s)){for(const[r,a]of this.shown){if(this.entries[r]?.kind!=="interview")continue;a.querySelector("rr0-interview")?.revealAt?.(s.playedSeconds,n.event.id)}return e}}markCitedMoments(){for(const[t,e]of this.shown){const i=this.entries[t],n=e.querySelector(jo);if(!i||!n)continue;const s=[];for(const[r,a]of this.shown){if(this.entries[r]?.kind!=="interview")continue;const c=a.querySelector("rr0-interview");s.push(...c?.momentsCited?.(i.event.id)??[])}n.citedMoments=s.sort((r,a)=>r.at-a.at)}}shut(t){this.shown.get(t)?.remove(),this.shown.delete(t),this.markCitedMoments(),this.draw()}order(){const t=[...this.shown.entries()].sort(([e],[i])=>e-i).map(([,e])=>e);this.openEvents.replaceChildren(...t)}async seekObservation(t,e){const i=this.entries.findIndex(r=>r.kind!=="interview"&&(r.event.id===e||e!==void 0&&r.url?.endsWith(`/${e}.json`))),n=i>=0?i:this.entries.findIndex(r=>r.kind!=="interview");if(n<0)return;this.shown.has(n)||await this.open(n),this.shown.get(n)?.querySelector(jo)?.seekTo(t,e),this.shown.get(n)?.scrollIntoView({block:"nearest",behavior:"smooth"})}authors(t){const e=this.messages,i=(t??[]).map(n=>"people"in n?n.people:"org"in n?n.org:this.said.read(n.title)??"").filter(n=>n!=="");return i.length<2||!e?i.join(", "):`${i.slice(0,-1).join(", ")} ${e.linkAnd} ${i[i.length-1]}`}linkedTo(t){const e=this.messages;if(e){if(t.kind==="reading"){const i=[t.event.interpretationOf].flat().filter(s=>s!==void 0),n=this.entries.map((s,r)=>i.includes(s.event.id??"")?r:-1).filter(s=>s>=0);return n.length>0?{heading:e.interpretationOf,to:n}:void 0}if(t.kind==="observation"){const i=this.entries.map((n,s)=>n.kind==="interview"&&[n.event.interviewOf].flat().includes(t.event.id)?s:-1).filter(n=>n>=0);return i.length>0?{heading:e.passagesHeading,to:i}:void 0}}}draw(){const t=this.messages,e=this.json;if(!t||!e)return;this.byId("case-kind").textContent=t.caseHeading,this.byId("case-title").textContent=this.said.read(e.title)??e.id??"";const i=this.said.read(e.summary)??"",n=this.byId("case-summary");n.textContent=i;const s=this.byId("info");s.hidden=i==="",s.title=t.caseSummary,s.setAttribute("aria-label",t.caseSummary),i===""&&this.showSummary(!1),this.byId("events-heading").textContent=t.eventsHeading,this.byId("events-icon").innerHTML=ye.CLOCK;const r=this.byId("share");r.title=t.shareCase,r.setAttribute("aria-label",t.shareCase);const a=this.byId("edit");a.title=t.editCase,a.setAttribute("aria-label",t.editCase),this.eventList.replaceChildren(...this.entries.map((c,l)=>this.card(c,l,t)))}card(t,e,i){const n=document.createElement("li");n.className="event",n.dataset.kind=t.kind,n.dataset.at=String(e),this.shown.has(e)&&(n.dataset.open="");const s=document.createElement("span");s.className="event-mark",s.innerHTML={observation:ye.WITNESS,reading:ye.SUMMARY,interview:ye.INTERVIEW}[t.kind],s.setAttribute("aria-hidden","true");const r=document.createElement("span");r.className="kind-pill",r.dataset.kind=t.kind,r.textContent={observation:i.kindObservation,reading:i.kindReading,interview:i.kindInterview}[t.kind];const a=document.createElement("button");a.type="button",a.className="event-open",a.textContent=t.title,a.title=i.openEvent,a.addEventListener("click",()=>void this.toggle(e));const c=document.createElement("span");c.className="event-meta",c.textContent=t.when.replace("T"," ");const l=document.createElement("span");l.className="event-links";const h=this.linkedTo(t);h&&l.append(`${h.heading} `,...h.to.flatMap((f,p)=>{const m=document.createElement("button");m.type="button",m.className="event-ref",m.textContent=this.entries[f].title,m.title=i.openEvent,m.addEventListener("click",()=>void this.open(f));const g=v=>this.eventList.querySelector(`.event[data-at="${f}"]`)?.classList.toggle("aimed",v);for(const[v,M]of[["mouseenter",!0],["mouseleave",!1],["focus",!0],["blur",!1]])m.addEventListener(v,()=>g(M));return p===0?[m]:[document.createTextNode(` ${i.linkAnd} `),m]}));const u=t.kind==="observation"?"":this.authors(t.event.by);u!==""&&l.append(`${h?" ":""}${i.byAuthor} ${u}`);const d=document.createElement("div");return d.className="event-body",d.append(r,a,c,l),n.append(s,d),n}async loadFromSrc(t){await this.load(t)}get scene(){return this.players()[0]?.scene}players(){return[...this.shown.entries()].sort(([t],[e])=>t-e).map(([,t])=>t.querySelector(jo)).filter(t=>t!==null)}get sightingData(){return this.players()[0]?.sightingData}get player(){return this.players()[0]}}function Z7(){customElements.get(Hh)||customElements.define(Hh,mm)}z3();Z7();export{ok as $,lr as A,Nt as B,rt as C,T0 as D,be as E,ar as F,Ke as G,Ws as H,J7 as I,pe as J,ec as K,cM as L,Re as M,we as N,Jn as O,Kt as P,Rr as Q,Ct as R,Qn as S,Li as T,Mo as U,Pr as V,gc as W,dk as X,pk as Y,$0 as Z,at as _,Sr as a,cr as a$,Je as a0,Tr as a1,T as a2,De as a3,fa as a4,EI as a5,bt as a6,Ie as a7,Eo as a8,Gt as a9,Bi as aA,U7 as aB,Xy as aC,z7 as aD,Oe as aE,u0 as aF,Z0 as aG,ph as aH,xr as aI,C0 as aJ,ye as aK,Es as aL,Oa as aM,j7 as aN,tk as aO,Q7 as aP,Rf as aQ,uk as aR,ck as aS,G0 as aT,CA as aU,q0 as aV,nk as aW,Yw as aX,lk as aY,fk as aZ,uA as a_,ek as aa,k8 as ab,Qv as ac,ir as ad,c0 as ae,Tc as af,Uu as ag,Is as ah,Tn as ai,hk as aj,ml as ak,Cn as al,jn as am,Ni as an,Qe as ao,si as ap,tn as aq,ts as ar,es as as,ak as at,Bn as au,Me as av,Wn as aw,zi as ax,hn as ay,vs as az,Y7 as b,zf as b0,cg as b1,F4 as b2,bc as b3,wv as b4,Qi as b5,Ga as b6,VR as b7,fi as b8,ik as b9,Vt as bA,Ch as bB,Py as bC,Bt as bD,Ay as bE,Mc as bF,Yr as bG,Ds as bH,gs as bI,bu as bJ,en as bK,mk as bL,sk as ba,pA as bb,rk as bc,ur as bd,fA as be,fx as bf,FR as bg,E3 as bh,z0 as bi,Jv as bj,IA as bk,_y as bl,Ty as bm,He as bn,Ba as bo,Tf as bp,Dt as bq,_n as br,la as bs,La as bt,Ei as bu,xc as bv,rf as bw,mt as bx,v5 as by,iu as bz,Un as c,qA as d,Xn as e,ZA as f,gf as g,vh as h,Ze as i,Mn as j,YM as k,$s as l,re as m,r8 as n,fn as o,fE as p,so as q,Xr as r,vo as s,Sh as t,Cd as u,Bs as v,TI as w,yt as x,tt as y,vd as z};
|