softbox 4.4.0 → 4.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/dist/{ThreePathTracingService-BCGY9F7h.cjs → ThreePathTracingService-CVTgPYSp.cjs} +1 -1
- package/dist/{ThreePathTracingService-CZRttruH.js → ThreePathTracingService-DTWmDzs1.js} +1 -1
- package/dist/{index-Bgui8z4D.cjs → index-BiSXFVUP.cjs} +2 -2
- package/dist/{index-BS5O0Opu.js → index-uh2exMyt.js} +20 -12
- package/dist/index.d.cts +95 -0
- package/dist/index.d.ts +95 -0
- package/dist/simple-viewer.cjs +1 -1
- package/dist/simple-viewer.es.js +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var jo=Object.create;var zi=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var Zo=Object.getOwnPropertyNames;var Ko=Object.getPrototypeOf,Xo=Object.prototype.hasOwnProperty;var Yo=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zo(e))!Xo.call(i,s)&&s!==t&&zi(i,s,{get:()=>e[s],enumerable:!(n=Wo(e,s))||n.enumerable});return i};var Rs=(i,e,t)=>(t=i!=null?jo(Ko(i)):{},Yo(e||!i||!i.__esModule?zi(t,"default",{value:i,enumerable:!0}):t,i));const me=require("react/jsx-runtime"),se=require("react"),p=require("three");function qo(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const E=qo(p);class K extends Error{constructor(e,t,n){super(e),this.code=t,this.context=n,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,K)}static fromError(e,t,n){if(e instanceof K)return e;const s=e instanceof Error?e.message:String(e),r={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new K(s,t,r)}}var Y=(i=>(i.SCENE_INIT_FAILED="SCENE_INIT_FAILED",i.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",i.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",i.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",i.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",i.INITIALIZATION_FAILED="INITIALIZATION_FAILED",i.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",i.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",i.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",i.INVALID_CONFIGURATION="INVALID_CONFIGURATION",i.RENDER_ERROR="RENDER_ERROR",i.RENDER_FAILED="RENDER_FAILED",i.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",i.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",i.INVALID_STATE="INVALID_STATE",i.INVALID_PARAMETER="INVALID_PARAMETER",i.OPERATION_FAILED="OPERATION_FAILED",i.UNKNOWN="UNKNOWN",i))(Y||{});const F={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return F.ok(i())}catch(e){return F.err(e instanceof K?e:new K(String(e),Y.UNKNOWN,{originalError:e}))}}};class Es{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);return n&&n.add(t),()=>{var s;(s=this.listeners.get(e))==null||s.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(s=>{try{s(t)}catch(r){console.error(`Error in event listener for ${String(e)}:`,r)}})}once(e,t){const n=this.on(e,s=>{n(),t(s)});return n}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t;return((t=this.listeners.get(e))==null?void 0:t.size)||0}off(e,t){var n;(n=this.listeners.get(e))==null||n.delete(t)}removeListener(e,t){this.off(e,t)}}const $s=300,vs={meters:1,centimeters:.01,millimeters:.001,feet:.3048,inches:.0254},$o="softbox-units-scale";function Mr(i){const e=i??"meters";if(!Object.prototype.hasOwnProperty.call(vs,e))throw new K(`Unknown units '${String(e)}'. Valid values: ${Object.keys(vs).join(", ")}`,Y.INVALID_PARAMETER);return vs[e]}const Ui="#1a1a1f";class Qo{configureScene(e,t,n){var a,c,u;if(n.helpers){const d={grid:n.helpers.grid,axes:n.helpers.axes,gridColor:"#AAAAAA"},h=t.addHelpers(e,d);h.ok||console.warn("Failed to add helpers:",h.error)}const s=n.lighting;if(s){const d={ambient:s.ambientLight?{color:String(s.ambientLight.color),intensity:s.ambientLight.intensity}:void 0,hemisphere:s.hemisphereLight?{skyColor:String(s.hemisphereLight.skyColor),groundColor:String(s.hemisphereLight.groundColor),intensity:s.hemisphereLight.intensity}:void 0,directional:s.directionalLight?{color:String(s.directionalLight.color),intensity:s.directionalLight.intensity,position:Array.isArray(s.directionalLight.position)?s.directionalLight.position:void 0,castShadow:s.directionalLight.castShadow,shadow:s.directionalLight.shadow}:void 0},h=t.addLighting(e,d);h.ok||console.warn("Failed to add lighting:",h.error)}const r=(a=n.environment)==null?void 0:a.url,o=(((c=n.helpers)==null?void 0:c.studioEnvironment)??!1)&&(((u=n.helpers)==null?void 0:u.darkStudioMode)??!1);if(n.backgroundColor&&!r&&!o){const d=String(n.backgroundColor),h=t.createGradientBackground(e,{topColor:d,bottomColor:d});h.ok||console.warn("Failed to set background:",h.error)}}async configureEnvironment(e,t,n,s,r,o){var d,h,f,m,w,b;const a=await t.initialize({renderer:s,autoDispose:!0});if(o())return;a.ok||console.warn("Failed to initialize environment service:",a.error);const c={backgroundBlurriness:(d=r.environment)==null?void 0:d.backgroundBlurriness,backgroundIntensity:(h=r.environment)==null?void 0:h.backgroundIntensity,environmentIntensity:(f=r.environment)==null?void 0:f.environmentIntensity},u=(m=r.environment)==null?void 0:m.url;if(u){const _=await t.loadEnvironmentMap(u);if(o())return;_.ok?t.applyToScene(e,_.value,c):console.warn("Failed to load environment map:",_.error)}else if((w=r.helpers)!=null&&w.studioEnvironment){const _=t.createStudioEnvironment();if(_.ok){if(t.applyToScene(e,_.value,{...c,setBackground:!1}),(b=r.helpers)!=null&&b.darkStudioMode&&n){const A=n.createGradientBackground(e,{topColor:Ui,bottomColor:Ui});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",_.error)}}}class Jo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,this.continuousReasons=new Set,this.alwaysRender=!1,this.enableIdleDetection=e.enableIdleDetection??!0,this.idleDelay=e.idleDelay??1e3,this.targetFPS=e.targetFPS??60,this.frameInterval=1e3/this.targetFPS,this.enableFrameRateLimiting=e.enableFrameRateLimiting??!0,this.alwaysRender=e.alwaysRender??!1,this.lastRenderTime=performance.now()}requestRender(){this.needsRender=!0,this.wakeUp()}requireContinuous(e){this.continuousReasons.add(e),this.continuousRenderingEnabled=!0,this.wakeUp()}releaseContinuous(e){this.continuousReasons.delete(e),this.continuousRenderingEnabled=this.continuousReasons.size>0}hasContinuousDemand(){return this.continuousReasons.size>0}setAlwaysRender(e){this.alwaysRender=e,e&&this.wakeUp()}wakeUp(){this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1}start(e){if(this.animationFrameId!==null)return;const t=n=>{if(this.animationFrameId===null)return;const s=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&s<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(s),this.lastRenderTime=n,this.needsRender=!1),this.enableIdleDetection&&!this.alwaysRender&&(this.continuousRenderingEnabled||this.needsRender?this.wakeUp():this.idleTimeout===null&&!this.isIdle&&(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0},this.idleDelay))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):this.animationFrameId=null};this.animationFrameId=requestAnimationFrame(t)}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1,this.needsRender=!1,this.continuousRenderingEnabled=!1,this.continuousReasons.clear(),this.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}function Vn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ps(i,e){if(!Vn(i)||!Vn(e))return e===void 0?i:e;const t=e,n={...i};for(const s of Object.keys(t)){const r=t[s];if(r===void 0)continue;const o=n[s];n[s]=Vn(o)&&Vn(r)?ps(o,r):r}return n}class Rr{static serialize(e,t,n,s){const r=t.position,o=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:r.x,y:r.y,z:r.z},cameraTarget:{x:o.x,y:o.y,z:o.z},controlsTarget:{x:o.x,y:o.y,z:o.z},rendererSize:{width:s.clientWidth,height:s.clientHeight}}}static async restore(e,t,n,s){t.position.set(e.cameraPosition.x,e.cameraPosition.y,e.cameraPosition.z),t.lookAt({x:e.cameraTarget.x,y:e.cameraTarget.y,z:e.cameraTarget.z,set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),n.target&&n.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),n.update&&n.update(),e.modelUrl&&s&&await s(e.modelUrl)}}function Qs(i,e){i.type==="perspective"&&"aspect"in i&&(i.aspect=e),i.updateProjectionMatrix()}class gt{constructor(e={}){this.data=Object.freeze({status:"idle",currentModel:null,error:null,isInitialized:!1,loadProgress:0,renderInfo:{frameCount:0,fps:0,lastRenderTime:0,averageRenderTime:0},...e})}get status(){return this.data.status}get currentModel(){return this.data.currentModel}get error(){return this.data.error}get isInitialized(){return this.data.isInitialized}get loadProgress(){return this.data.loadProgress}get renderInfo(){return this.data.renderInfo}setInitialized(){return new gt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new gt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new gt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new gt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new gt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new gt({...this.data,status:"rendering"})}updateRenderInfo(e){return new gt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new gt({...this.data,status:"disposed",currentModel:null})}canLoad(){return this.data.isInitialized&&(this.data.status==="idle"||this.data.status==="loaded"||this.data.status==="error"||this.data.status==="rendering")}canRender(){return this.data.isInitialized&&this.data.status==="loaded"&&this.data.currentModel!==null}isLoading(){return this.data.status==="loading"}hasError(){return this.data.status==="error"&&this.data.error!==null}toJSON(){return{...this.data}}}class ea{constructor(){this.state=new gt,this.stateChangeCallbacks=new Set}getState(){return this.state}setInitialized(){this.updateState(this.state.setInitialized())}startLoading(){this.updateState(this.state.startLoading())}setLoaded(e){this.updateState(this.state.setLoaded(e))}setError(e){this.updateState(this.state.setError(e))}startRendering(){this.updateState(this.state.startRendering())}updateRenderInfo(e){this.updateState(this.state.updateRenderInfo(e))}setDisposed(){this.updateState(this.state.dispose())}canLoad(){return this.state.canLoad()}isInitialized(){return this.state.isInitialized}getStatus(){return this.state.status}getCurrentModel(){return this.state.currentModel}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>{this.stateChangeCallbacks.delete(e)}}clearCallbacks(){this.stateChangeCallbacks.clear()}updateState(e){this.state=e,this.stateChangeCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("Error in state change callback:",n)}})}}function vr(i){const e=i.toDataURL("image/png");return!e||e==="data:,"?null:e}class ta{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,s){if(this.isShowingScreenshot)return;const r=this.renderer.getDomElement(),o=vr(r);if(!o){console.warn("[ScreenshotManager] Screenshot capture produced no image, keeping live scene");return}const a=document.createElement("img");a.src=o,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="auto",a.style.cursor="grab";const c=r.parentElement;if(c){this.serializedSceneState=Rr.serialize(n,e,t,r),r.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const u=()=>{this.restore()};a.addEventListener("mousedown",u),a.addEventListener("touchstart",u);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,s==null||s()}}async restore(){if(!this.isShowingScreenshot||!this.screenshotElement)return;const e=this.renderer.getDomElement(),t=this.screenshotElement.parentElement;t&&(this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),t.removeChild(this.screenshotElement),e.style.display="",this.screenshotElement=null,this.isShowingScreenshot=!1,this.onRestore&&await this.onRestore())}getSerializedState(){return this.serializedSceneState}dispose(){this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),this.screenshotElement&&this.screenshotElement.parentElement&&this.screenshotElement.parentElement.removeChild(this.screenshotElement),this.isShowingScreenshot&&(this.renderer.getDomElement().style.display=""),this.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class na{constructor(e){this.currentModel=null,this.modelLoader=e.modelLoader,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.floorAlignmentService=e.floorAlignmentService,this.sceneSetupService=e.sceneSetupService,this.renderer=e.renderer,this.autoFitToObject=e.autoFitToObject??!1,this.unitsScaleToMeters=e.unitsScaleToMeters??1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const n=performance.now();try{let s;if(typeof e=="string"){this.lastModelUrl=e,t.emit("model:loading",{url:e});const a=await this.modelLoader.load(e,(c,u)=>{t.emit("model:progress",{url:e,loaded:c,total:u})});if(!a.ok)throw a.error;s=a.value.scene}else s=e;if(this.unitsScaleToMeters!==1){if(!this.sceneSetupService)throw new K("A units conversion is configured but no scene setup service is available to apply it",Y.INVALID_PARAMETER);const a=this.sceneSetupService.wrapInUnitsScaleGroup(s,this.unitsScaleToMeters);if(!a.ok)throw a.error;s=a.value}this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const r=this.scene.add(s);if(!r.ok)throw r.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(s);a.ok||console.warn("Failed to align model to floor:",a.error)}if(s.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=s,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,s,2);a.ok||console.warn("Failed to add dynamic grid:",a.error);const c=this.sceneSetupService.snapObjectToFloor(this.scene,s);c.ok||console.warn("Failed to snap object to floor:",c.error);const u=this.sceneSetupService.fitShadowCameraToObject(this.scene,s);if(u.ok||console.warn("Failed to fit shadow camera to object:",u.error),this.renderer){const d=this.sceneSetupService.bakeContactShadow(this.scene,s,this.renderer);d.ok||console.warn("Failed to bake contact shadow:",d.error)}}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(s,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const o=performance.now()-n;return t.emit("model:loaded",{model:s,loadTime:o}),F.ok(s)}catch(s){const r=s instanceof K?s:new K("Failed to load model",Y.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:r,url:typeof e=="string"?e:void 0}),F.err(r)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.dispose()}dispose(){var e,t;this.disposeCurrentModel(),(t=(e=this.modelLoader).dispose)==null||t.call(e),this.lastModelUrl=void 0}}class sa{constructor(e){this.scene=e.scene,this.pathTracingService=e.pathTracingService,this.environmentService=e.environmentService}updateServices(e){e.pathTracingService&&(this.pathTracingService=e.pathTracingService),e.environmentService&&(this.environmentService=e.environmentService)}disposeSceneResources(e=!1){this.scene.disposeContents({keepBackgrounds:!0}),this.triggerGarbageCollection()}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.disposeContents(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}function Cr(i){return typeof i=="object"&&i!==null&&"getInternalRenderer"in i&&typeof i.getInternalRenderer=="function"}class ia{constructor(e){this.completeHandled=!1,this.selfPauseListeners=new Set,this.deps=e}isEnabled(){var e;return!!(this.deps.service&&(((e=this.deps.getOptions().pathTracing)==null?void 0:e.enabled)??!1))}getMaxSamples(){var e;return((e=this.deps.getOptions().pathTracing)==null?void 0:e.maxSamples)??$s}isCompleteHandled(){return this.completeHandled}isAccumulating(){var e;return!!((e=this.deps.service)!=null&&e.isEnabled())}onSelfPause(e){return this.selfPauseListeners.add(e),()=>this.selfPauseListeners.delete(e)}async initialize(){var u;const{service:e,getOptions:t,isDisposed:n,renderer:s,renderLoopManager:r,schedule:o}=this.deps;if(!e||!(((u=t().pathTracing)==null?void 0:u.enabled)??!1))return;const a=await e.initialize({enabled:!0,renderer:s});if(n())return;if(!a.ok){console.warn("Failed to initialize path tracing:",a.error);return}const c=t().pathTracing;c&&e.updateSettings({samples:c.maxSamples??$s,bounces:c.bounces,transmissiveBounces:c.transmissiveBounces,renderScale:c.renderScale,lowResScale:c.lowResScale,dynamicLowRes:c.dynamicLowRes,enablePathTracing:c.enabled??!0}),e.events.on("pathtracing:paused",({reason:d})=>{r.releaseContinuous("path-tracing"),t().staticScene||r.setAlwaysRender(!1),o(()=>{r.hasContinuousDemand()||r.stop()},100),d==="gave-up"&&this.selfPauseListeners.forEach(h=>h())})}resetAccumulation(e=!1){this.deps.service&&this.isEnabled()&&(this.deps.service.reset(e),this.completeHandled=!1)}getSampleCount(){var e;return((e=this.deps.service)==null?void 0:e.getSampleCount())||0}beforeFrame(){var e;return{wasActive:((e=this.deps.service)==null?void 0:e.isEnabled())||!1,samples:this.getSampleCount()}}render(e,t){const n=this.deps.service;if(!n||n.isPathTracerDisposed())return null;const s=n.getSampleCount(),r=s>=this.getMaxSamples()&&s>0;return!n.isEnabled()&&!r?null:(s===0&&(this.startTime=performance.now()),n.render(e,t))}detectCompletion(e,t){const n=this.deps.service;if(!n)return;(n.getSampleCount()||0)>=this.getMaxSamples()&&!this.completeHandled&&e.wasActive&&this.handleComplete(e.samples,t)}handleComplete(e,t){const{events:n,renderLoopManager:s,getOptions:r,schedule:o,replaceWithScreenshot:a,renderer:c}=this.deps;this.completeHandled=!0,s.releaseContinuous("path-tracing"),r().staticScene||s.setAlwaysRender(!1),n.emit("pathtracing:complete",{samples:e,totalTime:t-(this.startTime||0)});const u=()=>{s.hasContinuousDemand()||s.stop()};if(r().replaceWithScreenshotOnComplete){o(()=>{a(),o(u,200)},100);return}if(s.requestRender(),o(u,100),Cr(c)){const d=c.getInternalRenderer();d&&(d.autoClear=!1)}}onResizeStart(){var t;const e=((t=this.deps.service)==null?void 0:t.isEnabled())??!1;return this.deps.service&&this.completeHandled&&(this.deps.service.reset(),this.completeHandled=!1),e}onResizeEnd(e){e&&this.deps.service&&this.deps.service.setEnabled(!0)}}function Ir(){const i="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?i[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}const ra=i=>[i,"video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].filter(t=>!!t).find(t=>MediaRecorder.isTypeSupported(t));class oa{constructor(e){this.pendingSettlers=new Set,this.pathTracedWaitSettlers=new Set,this.deps=e}async captureStill(e={}){return this.deps.isDisposed()?F.err(new K("Cannot capture a still from a disposed viewer",Y.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?F.err(new K("Viewer was disposed while a model load finished",Y.INVALID_STATE)):this.deps.isScreenshotActive()?F.err(new K("Cannot capture a still while a screenshot is replacing the canvas",Y.INVALID_STATE)):this.deps.pathTracing.isEnabled()?this.capturePathTracedStill(e):this.captureRasterStill(e))}settleOnDispose(){[...this.pendingSettlers].forEach(e=>e("disposed"))}notifyTurntableEnabled(){[...this.pathTracedWaitSettlers].forEach(e=>e("turntable"))}async captureVideo(e={}){var d;if(this.deps.isDisposed())return F.err(new K("Cannot capture video from a disposed viewer",Y.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return F.err(new K("Viewer was disposed while a model load finished",Y.INVALID_STATE));if(this.deps.isScreenshotActive())return F.err(new K("Cannot capture video while a screenshot is replacing the canvas",Y.INVALID_STATE));const t=e.duration??3;if(!(t>0))return F.err(new K("Video duration must be a positive number of seconds",Y.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return F.err(new K("Video capture needs MediaRecorder and canvas.captureStream support",Y.UNSUPPORTED_FORMAT));const s=n.captureStream(e.fps??30);let r;try{r=new MediaRecorder(s,{mimeType:ra(e.mimeType),videoBitsPerSecond:e.videoBitsPerSecond})}catch(h){return s.getTracks().forEach(f=>f.stop()),F.err(new K("Failed to start the video recorder",Y.OPERATION_FAILED,{originalError:h}))}const o=s.getVideoTracks()[0],a=(d=o==null?void 0:o.requestFrame)==null?void 0:d.bind(o),c=a?this.deps.events.on("render:complete",()=>a()):()=>{},u=`video-capture:${Ir()}`;return this.deps.renderLoopManager.requireContinuous(u),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(h=>{const f=[];let m=null,w=!1;const b=A=>{w||(w=!0,this.pendingSettlers.delete(_),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(u),s.getTracks().forEach(T=>T.stop()),h(A))},_=()=>{b(F.err(new K("Viewer was disposed during video capture",Y.INVALID_STATE)));try{r.stop()}catch{}};this.pendingSettlers.add(_),r.ondataavailable=A=>{A.data.size>0&&f.push(A.data)},r.onstop=()=>{b(F.ok(new Blob(f,{type:r.mimeType||"video/webm"})))},r.onerror=()=>{b(F.err(new K("Video recording failed",Y.OPERATION_FAILED)))},r.start(250),m=setTimeout(()=>{r.state!=="inactive"&&r.stop()},t*1e3)})}async capturePathTracedStill(e){if(e.width!==void 0||e.height!==void 0)return F.err(new K("Path-traced stills are captured at the canvas resolution; omit width/height",Y.INVALID_PARAMETER));if(this.deps.isAutoRotating())return F.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",Y.INVALID_STATE));const t=this.deps.pathTracing.isAccumulating()&&this.deps.getStatus()!=="error";if(!this.deps.pathTracing.isCompleteHandled()&&t){const n=await this.waitForPathTracingOutcome();if(n==="disposed")return F.err(new K("Viewer was disposed while waiting for the path tracer",Y.INVALID_STATE));if(n==="error")return F.err(new K("Model failed while waiting for the path tracer",Y.RENDER_FAILED));if(n==="turntable")return F.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",Y.INVALID_STATE))}return this.readCanvasPng()}waitForPathTracingOutcome(){return new Promise(e=>{let t=()=>{},n=()=>{},s=()=>{},r=()=>{};const o=a=>{this.pendingSettlers.delete(o),this.pathTracedWaitSettlers.delete(o),t(),n(),s(),r(),e(a)};this.pendingSettlers.add(o),this.pathTracedWaitSettlers.add(o),t=this.deps.events.once("pathtracing:complete",()=>o("complete")),n=this.deps.events.once("model:error",()=>o("error")),s=this.deps.pathTracing.onSelfPause(()=>o("complete")),r=this.deps.events.on("controls:change",()=>{this.deps.isAutoRotating()&&o("turntable")})})}captureRasterStill(e){const{renderer:t,scene:n,camera:s,renderLoopManager:r}=this.deps,o=t.getDomElement(),a=t.getPixelRatio(),c=o.clientWidth>0&&o.clientHeight>0,u=c?o.clientWidth:Math.round(o.width/a),d=c?o.clientHeight:Math.round(o.height/a);if(u<=0||d<=0)return F.err(new K("Cannot capture: the canvas has no size",Y.INVALID_STATE));const h=u/d,f=Math.round(e.width??(e.height!==void 0?e.height*h:u*a)),m=Math.round(e.height??(e.width!==void 0?e.width/h:d*a)),w=t.capabilities.maxTextureSize;if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0||f>w||m>w)return F.err(new K(`Requested still size ${f}x${m} is outside 1..${w}`,Y.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),Qs(s,f/m);const b=t.render(n,s),_=b.ok?this.readCanvasPng():F.err(b.error);return t.setSize(u,d),t.setPixelRatio(a),Qs(s,h),t.render(n,s),r.requestRender(),_}readCanvasPng(){const e=vr(this.deps.renderer.getDomElement());return e?F.ok(e):F.err(new K("Canvas produced an empty image",Y.RENDER_FAILED))}}class aa{constructor(e){var r;this.frameCount=0,this.disposed=!1,this.pendingTimers=new Set,this.modelLoadChain=Promise.resolve(),this.renderer=e.renderer,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.options=e.options,this.rendererOptions=e.rendererOptions,this.sceneSetupService=e.sceneSetupService,this.environmentService=e.environmentService,this.selectionService=e.selectionService,this.anchorProjectionService=e.anchorProjectionService,this.animationService=e.animationService,this.stateManager=new ea,this.screenshotManager=new ta({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}});const t=Mr(this.options.units);this.modelManager=new na({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,renderer:this.renderer,autoFitToObject:(r=this.options.camera)==null?void 0:r.autoFitToObject,unitsScaleToMeters:t}),this.resourceManager=new sa({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new Qo,this.events=new Es;const n=this.options.rendering||{},s=this.options.staticScene!==!1;this.renderLoopManager=new Jo({enableIdleDetection:n.enableIdleDetection??s,idleDelay:n.idleDelay,targetFPS:n.targetFPS,enableFrameRateLimiting:n.enableFrameRateLimiting,alwaysRender:!1}),this.pathTracing=new ia({service:e.pathTracingService,events:this.events,renderLoopManager:this.renderLoopManager,renderer:this.renderer,getOptions:()=>this.options,isDisposed:()=>this.disposed,schedule:(o,a)=>this.schedule(o,a),replaceWithScreenshot:()=>this.replaceWithScreenshot()}),this.capture=new oa({renderer:this.renderer,scene:this.scene,camera:this.camera,events:this.events,renderLoopManager:this.renderLoopManager,pathTracing:this.pathTracing,getStatus:()=>this.stateManager.getStatus(),isDisposed:()=>this.disposed,awaitModelLoads:()=>this.modelLoadChain,reviveRenderLoop:()=>this.reviveRenderLoop(),isAutoRotating:()=>this.controls.autoRotate,isScreenshotActive:()=>this.screenshotManager.isActive()})}async initialize(){var e,t;try{const n=this.renderer.initialize(this.rendererOptions||{});return n.ok?(this.sceneSetupService&&this.sceneConfigurator.configureScene(this.scene,this.sceneSetupService,this.options),this.environmentService&&(await this.sceneConfigurator.configureEnvironment(this.scene,this.environmentService,this.sceneSetupService,this.renderer,this.options,()=>this.disposed),this.disposed)||(await this.pathTracing.initialize(),this.disposed)||(this.selectionService&&this.selectionService.initialize({canvas:this.renderer.getDomElement(),camera:this.camera,getPickRoot:()=>this.modelManager.getCurrentModel(),bvh:(e=this.options.selection)==null?void 0:e.bvh,onPick:s=>{s&&!this.disposed&&this.events.emit("object:selected",s)}}),this.stateManager.setInitialized(),this.startRenderLoop(),this.options.staticScene?this.pathTracing.isEnabled()&&this.renderLoopManager.requireContinuous("path-tracing"):this.renderLoopManager.setAlwaysRender(!0),(t=this.options.controls)!=null&&t.autoRotate&&this.renderLoopManager.requireContinuous("turntable"),this.renderLoopManager.requestRender()),F.ok(void 0)):n}catch(n){const s=new K("Failed to initialize viewer",Y.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),F.err(s)}}loadModel(e){const t=this.modelLoadChain.then(()=>this.runLoadModel(e));return this.modelLoadChain=t.then(()=>{},()=>{}),t}async runLoadModel(e){if(this.disposed)return F.err(new K("Cannot load model after dispose",Y.INVALID_STATE));if(!this.stateManager.canLoad())return F.err(new K("Cannot load model in current state",Y.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const t=await this.modelManager.loadModel(e,this.events);return this.disposed?(t.ok&&this.modelManager.disposeCurrentModel(),F.err(new K("Viewer was disposed while the model was loading",Y.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(!0),F.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof K?t:new K("Failed to load model",Y.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),F.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var o;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.isDisposed()){this.renderLoopManager.stop();return}const t=performance.now(),n=e>0?1e3/e:0;this.controls.update()&&(this.events.emit("controls:change",{controls:this.controls}),this.pathTracing.resetAccumulation(),this.renderLoopManager.requestRender()),(o=this.animationService)!=null&&o.isPlaying()&&this.animationService.update(e/1e3);const r=this.pathTracing.beforeFrame();this.renderFrame().catch(a=>{console.error("[ViewerCore] Render frame error:",a)}),this.pathTracing.detectCompletion(r,t),this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t})})}stopRenderLoop(){this.renderLoopManager.stop()}schedule(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),!this.disposed&&e()},t);this.pendingTimers.add(n)}async renderFrame(){const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.screenshotManager.isActive())return;this.stateManager.startRendering();const t=await(this.pathTracing.render(this.scene,this.camera)??Promise.resolve(this.renderer.render(this.scene,this.camera)));if(!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}this.events.emit("render:complete",{frame:this.frameCount,renderTime:performance.now()-e,samples:this.pathTracing.getSampleCount()})}updateOptions(e){var h,f,m,w,b,_,A,T,x;if(this.disposed)return;const t=(h=this.options.animations)==null?void 0:h.autoplay,n=(f=this.options.controls)==null?void 0:f.autoRotate;this.options=ps(this.options,e);let s=!1;e.backgroundColor!==void 0&&this.applyBackgroundColor(e.backgroundColor);const r=(m=e.renderer)==null?void 0:m.toneMappingExposure;r!==void 0&&(this.renderer.setToneMappingExposure(r),s=!0);const o=(w=e.environment)==null?void 0:w.environmentIntensity;o!==void 0&&(this.scene.setEnvironmentIntensity(o),s=!0);const a=(b=e.controls)==null?void 0:b.autoRotate;a!==void 0&&a!==n&&(this.controls.autoRotate=a,a?(this.renderLoopManager.requireContinuous("turntable"),this.capture.notifyTurntableEnabled()):this.renderLoopManager.releaseContinuous("turntable"),s=!0);const c=(_=e.controls)==null?void 0:_.autoRotateSpeed;c!==void 0&&(this.controls.autoRotateSpeed=c,s=!0);const u=(A=e.animations)==null?void 0:A.autoplay;u!==void 0&&u!==t&&(u?this.modelManager.getCurrentModel()&&this.autoplayFromOptions(u):this.pauseAnimations(),s=!0);const d=(T=e.animations)==null?void 0:T.speed;d!==void 0&&((x=this.animationService)==null||x.setSpeed(d),s=!0),s&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}applyBackgroundColor(e){var n;if((n=this.options.environment)!=null&&n.url||!this.sceneSetupService)return;const t=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(e),bottomColor:String(e)});if(!t.ok){console.warn("Failed to update background color:",t.error);return}this.renderLoopManager.requestRender()}resize(e,t){if(this.disposed)return;const n=this.renderer.getDomElement();if(n.width===e&&n.height===t)return;const s=this.pathTracing.onResizeStart();Qs(this.camera,e/t),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}this.pathTracing.onResizeEnd(s),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}getRenderer(){return this.renderer}getScene(){return this.scene}getCamera(){return this.camera}getControls(){return this.controls}getModel(){return this.modelManager.getCurrentModel()}requestRender(){this.renderLoopManager.requestRender()}reviveRenderLoop(){this.stateManager.isInitialized()&&!this.renderLoopManager.isRunning()&&this.startRenderLoop()}getAnimationNames(){var e;return((e=this.animationService)==null?void 0:e.getClipNames())??[]}playAnimations(e){var n;if(!this.animationService)return e!==void 0?F.err(new K(`Cannot play animation clip '${e}': the viewer was assembled without an animation service`,Y.INVALID_STATE)):F.ok(void 0);const t=this.animationService.play(e);return t.ok?(this.animationService.isPlaying()&&((n=this.sceneSetupService)==null||n.setContactShadowMode(this.scene,"live"),this.renderLoopManager.requireContinuous("animations"),this.reviveRenderLoop(),this.renderLoopManager.requestRender()),F.ok(void 0)):t}autoplayFromOptions(e){const t=this.playAnimations(typeof e=="string"?e:void 0);t.ok||console.error("animations.autoplay failed:",t.error.message)}pauseAnimations(){var e;(e=this.animationService)==null||e.pause(),this.renderLoopManager.releaseContinuous("animations"),this.rebakeContactShadowForCurrentPose(),this.renderLoopManager.requestRender()}rebakeContactShadowForCurrentPose(){const e=this.modelManager.getCurrentModel();if(!e||!this.sceneSetupService)return;const t=this.sceneSetupService.bakeContactShadow(this.scene,e,this.renderer);t.ok||console.warn("Failed to re-bake contact shadow after pausing animations:",t.error)}attachAnimations(e){if(!this.animationService)return;this.renderLoopManager.releaseContinuous("animations"),this.animationService.attach(e);const t=this.options.animations;(t==null?void 0:t.speed)!==void 0&&this.animationService.setSpeed(t.speed);const n=t==null?void 0:t.autoplay;n&&this.autoplayFromOptions(n)}createAnchorProjector(){return this.anchorProjectionService?this.anchorProjectionService.createProjector({camera:this.camera,getCanvas:()=>this.renderer.getDomElement(),getModel:()=>this.getModel()}):null}captureStill(e={}){return this.capture.captureStill(e)}captureVideo(e={}){return this.capture.captureVideo(e)}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){const e=this.screenshotManager.getSerializedState();e&&await Rr.restore(e,this.camera,this.controls,async t=>{const n=await this.loadModel(t);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){var e,t;this.disposed=!0,this.pendingTimers.forEach(n=>clearTimeout(n)),this.pendingTimers.clear(),this.stopRenderLoop(),(e=this.selectionService)==null||e.dispose(),(t=this.animationService)==null||t.detach(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.capture.settleOnDispose(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class Pt{constructor(e){this.vector=e}get x(){return this.vector.x}set x(e){this.vector.x=e}get y(){return this.vector.y}set y(e){this.vector.y=e}get z(){return this.vector.z}set z(e){this.vector.z=e}set(e,t,n){this.vector.set(e,t,n)}copy(e){this.vector.set(e.x,e.y,e.z)}add(e){this.vector.x+=e.x,this.vector.y+=e.y,this.vector.z+=e.z}multiply(e){this.vector.x*=e.x,this.vector.y*=e.y,this.vector.z*=e.z}normalize(){this.vector.normalize()}length(){return this.vector.length()}getThreeVector(){return this.vector}static fromThreeVector(e){return new Pt(e)}static create(e=0,t=0,n=0){return new Pt(new E.Vector3(e,t,n))}}const Lr=0,ca=1,Pr=2,Vi=2,Cs=1.25,Hi=1,He=32,Ne=He/4,wi=65535,la=wi<<16,us=Math.pow(2,-24),Ei=Symbol("SKIP_GENERATION"),Or={strategy:Lr,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Ei]:!1};function Ae(i,e,t){return t.min.x=e[i],t.min.y=e[i+1],t.min.z=e[i+2],t.max.x=e[i+3],t.max.y=e[i+4],t.max.z=e[i+5],t}function Gi(i){let e=-1,t=-1/0;for(let n=0;n<3;n++){const s=i[n+3]-i[n];s>t&&(t=s,e=n)}return e}function ji(i,e){e.set(i)}function Wi(i,e,t){let n,s;for(let r=0;r<3;r++){const o=r+3;n=i[r],s=e[r],t[r]=n<s?n:s,n=i[o],s=e[o],t[o]=n>s?n:s}}function Hn(i,e,t){for(let n=0;n<3;n++){const s=e[i+2*n],r=e[i+2*n+1],o=s-r,a=s+r;o<t[n]&&(t[n]=o),a>t[n+3]&&(t[n+3]=a)}}function un(i){const e=i[3]-i[0],t=i[4]-i[1],n=i[5]-i[2];return 2*(e*t+t*n+n*e)}function Ie(i,e){return e[i+15]===wi}function Ge(i,e){return e[i+6]}function Xe(i,e){return e[i+14]}function Be(i){return i+Ne}function ze(i,e){const t=e[i+6];return i+t*Ne}function Ts(i,e){return e[i+7]}function ha(i){return i}function Is(i,e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0,h=1/0,f=1/0,m=1/0,w=-1/0,b=-1/0,_=-1/0;const A=i.offset||0;for(let T=(e-A)*6,x=(e+t-A)*6;T<x;T+=6){const S=i[T+0],M=i[T+1],P=S-M,I=S+M;P<r&&(r=P),I>c&&(c=I),S<h&&(h=S),S>w&&(w=S);const C=i[T+2],D=i[T+3],L=C-D,k=C+D;L<o&&(o=L),k>u&&(u=k),C<f&&(f=C),C>b&&(b=C);const N=i[T+4],H=i[T+5],j=N-H,$=N+H;j<a&&(a=j),$>d&&(d=$),N<m&&(m=N),N>_&&(_=N)}n[0]=r,n[1]=o,n[2]=a,n[3]=c,n[4]=u,n[5]=d,s[0]=h,s[1]=f,s[2]=m,s[3]=w,s[4]=b,s[5]=_}const Et=32,ua=(i,e)=>i.candidate-e.candidate,Mt=new Array(Et).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Gn=new Float32Array(6);function da(i,e,t,n,s,r){let o=-1,a=0;if(r===Lr)o=Gi(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ca)o=Gi(i),o!==-1&&(a=fa(t,n,s,o));else if(r===Pr){const c=un(i);let u=Cs*s;const d=t.offset||0,h=(n-d)*6,f=(n+s-d)*6;for(let m=0;m<3;m++){const w=e[m],A=(e[m+3]-w)/Et;if(s<Et/4){const T=[...Mt];T.length=s;let x=0;for(let M=h;M<f;M+=6,x++){const P=T[x];P.candidate=t[M+2*m],P.count=0;const{bounds:I,leftCacheBounds:C,rightCacheBounds:D}=P;for(let L=0;L<3;L++)D[L]=1/0,D[L+3]=-1/0,C[L]=1/0,C[L+3]=-1/0,I[L]=1/0,I[L+3]=-1/0;Hn(M,t,I)}T.sort(ua);let S=s;for(let M=0;M<S;M++){const P=T[M];for(;M+1<S&&T[M+1].candidate===P.candidate;)T.splice(M+1,1),S--}for(let M=h;M<f;M+=6){const P=t[M+2*m];for(let I=0;I<S;I++){const C=T[I];P>=C.candidate?Hn(M,t,C.rightCacheBounds):(Hn(M,t,C.leftCacheBounds),C.count++)}}for(let M=0;M<S;M++){const P=T[M],I=P.count,C=s-P.count,D=P.leftCacheBounds,L=P.rightCacheBounds;let k=0;I!==0&&(k=un(D)/c);let N=0;C!==0&&(N=un(L)/c);const H=Hi+Cs*(k*I+N*C);H<u&&(o=m,u=H,a=P.candidate)}}else{for(let S=0;S<Et;S++){const M=Mt[S];M.count=0,M.candidate=w+A+S*A;const P=M.bounds;for(let I=0;I<3;I++)P[I]=1/0,P[I+3]=-1/0}for(let S=h;S<f;S+=6){let I=~~((t[S+2*m]-w)/A);I>=Et&&(I=Et-1);const C=Mt[I];C.count++,Hn(S,t,C.bounds)}const T=Mt[Et-1];ji(T.bounds,T.rightCacheBounds);for(let S=Et-2;S>=0;S--){const M=Mt[S],P=Mt[S+1];Wi(M.bounds,P.rightCacheBounds,M.rightCacheBounds)}let x=0;for(let S=0;S<Et-1;S++){const M=Mt[S],P=M.count,I=M.bounds,D=Mt[S+1].rightCacheBounds;P!==0&&(x===0?ji(I,Gn):Wi(I,Gn,Gn)),x+=P;let L=0,k=0;x!==0&&(L=un(Gn)/c);const N=s-x;N!==0&&(k=un(D)/c);const H=Hi+Cs*(L*x+k*N);H<u&&(o=m,u=H,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function fa(i,e,t,n){let s=0;const r=i.offset;for(let o=e,a=e+t;o<a;o++)s+=i[(o-r)*6+n*2];return s/t}class Ls{constructor(){this.boundingData=new Float32Array(6)}}function pa(i,e,t,n,s,r){let o=n,a=n+s-1;const c=r.pos,u=r.axis*2,d=t.offset||0;for(;;){for(;o<=a&&t[(o-d)*6+u]<c;)o++;for(;o<=a&&t[(a-d)*6+u]>=c;)a--;if(o<a){for(let h=0;h<e;h++){let f=i[o*e+h];i[o*e+h]=i[a*e+h],i[a*e+h]=f}for(let h=0;h<6;h++){const f=o-d,m=a-d,w=t[f*6+h];t[f*6+h]=t[m*6+h],t[m*6+h]=w}o++,a--}else return o}}let Dr,ds,Js,Nr;const ma=Math.pow(2,32);function ei(i){return"count"in i?1:1+ei(i.left)+ei(i.right)}function ga(i,e,t){return Dr=new Float32Array(t),ds=new Uint32Array(t),Js=new Uint16Array(t),Nr=new Uint8Array(t),ti(i,e)}function ti(i,e){const t=i/4,n=i/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Dr[t+o]=r[o];if(s)return e.buffer?(Nr.set(new Uint8Array(e.buffer),i),i+e.buffer.byteLength):(ds[t+6]=e.offset,Js[n+14]=e.count,Js[n+15]=wi,i+He);{const{left:o,right:a,splitAxis:c}=e,u=i+He;let d=ti(u,o);const h=i/He,m=d/He-h;if(m>ma)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ds[t+6]=m,ds[t+7]=c,ti(d,a)}}function ya(i,e,t,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:c,strategy:u,onProgress:d}=s,h=i.primitiveBuffer,f=i.primitiveBufferStride,m=new Float32Array(6);let w=!1;const b=new Ls;return Is(e,t,n,b.boundingData,m),A(b,t,n,m),b;function _(T){d&&d((T-r.offset)/r.count)}function A(T,x,S,M=null,P=0){if(!w&&P>=o&&(w=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`)),S<=c||P>=o)return _(x+S),T.offset=x,T.count=S,T;const I=da(T.boundingData,M,e,x,S,u);if(I.axis===-1)return _(x+S),T.offset=x,T.count=S,T;const C=pa(h,f,e,x,S,I);if(C===x||C===x+S)_(x+S),T.offset=x,T.count=S;else{T.splitAxis=I.axis;const D=new Ls,L=x,k=C-x;T.left=D,Is(e,L,k,D.boundingData,m),A(D,L,k,m,P+1);const N=new Ls,H=C,j=S-k;T.right=N,Is(e,H,j,N.boundingData,m),A(N,H,j,m,P+1)}return T}}function wa(i,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=i.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,i.computePrimitiveBounds(o.offset,o.count,a),i._roots=n.map(c=>{const u=ya(i,a,c.offset,c.count,e,o),d=ei(u),h=new t(He*d);return ga(0,u,h),h})}class Ti{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Ea{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=n=>{t&&e.push(t),t=n,this.float32Array=new Float32Array(n),this.uint16Array=new Uint16Array(n),this.uint32Array=new Uint32Array(n)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const be=new Ea;let Lt,nn;const jt=[],jn=new Ti(()=>new p.Box3);function Ta(i,e,t,n,s,r){Lt=jn.getPrimitive(),nn=jn.getPrimitive(),jt.push(Lt,nn),be.setBuffer(i._roots[e]);const o=ni(0,i.geometry,t,n,s,r);be.clearBuffer(),jn.releasePrimitive(Lt),jn.releasePrimitive(nn),jt.pop(),jt.pop();const a=jt.length;return a>0&&(nn=jt[a-1],Lt=jt[a-2]),o}function ni(i,e,t,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:c,uint32Array:u}=be;let d=i*2;if(Ie(d,c)){const f=Ge(i,u),m=Xe(d,c);return Ae(i,a,Lt),n(f,m,!1,o,r+i/Ne,Lt)}else{let L=function(N){const{uint16Array:H,uint32Array:j}=be;let $=N*2;for(;!Ie($,H);)N=Be(N),$=N*2;return Ge(N,j)},k=function(N){const{uint16Array:H,uint32Array:j}=be;let $=N*2;for(;!Ie($,H);)N=ze(N,j),$=N*2;return Ge(N,j)+Xe($,H)};const f=Be(i),m=ze(i,u);let w=f,b=m,_,A,T,x;if(s&&(T=Lt,x=nn,Ae(w,a,T),Ae(b,a,x),_=s(T),A=s(x),A<_)){w=m,b=f;const N=_;_=A,A=N,T=x}T||(T=Lt,Ae(w,a,T));const S=Ie(w*2,c),M=t(T,S,_,o+1,r+w/Ne);let P;if(M===Vi){const N=L(w),j=k(w)-N;P=n(N,j,!0,o+1,r+w/Ne,T)}else P=M&&ni(w,e,t,n,s,r,o+1);if(P)return!0;x=nn,Ae(b,a,x);const I=Ie(b*2,c),C=t(x,I,A,o+1,r+b/Ne);let D;if(C===Vi){const N=L(b),j=k(b)-N;D=n(N,j,!0,o+1,r+b/Ne,x)}else D=C&&ni(b,e,t,n,s,r,o+1);return!!D}}const Sn=new be.constructor,ms=new be.constructor,Ct=new Ti(()=>new p.Box3),Wt=new p.Box3,Zt=new p.Box3,Ps=new p.Box3,Os=new p.Box3;let Ds=!1;function Sa(i,e,t,n){if(Ds)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ds=!0;const s=i._roots,r=e._roots;let o,a=0,c=0;const u=new p.Matrix4().copy(t).invert();for(let d=0,h=s.length;d<h;d++){Sn.setBuffer(s[d]),c=0;const f=Ct.getPrimitive();Ae(0,Sn.float32Array,f),f.applyMatrix4(u);for(let m=0,w=r.length;m<w&&(ms.setBuffer(r[m]),o=ht(0,0,t,u,n,a,c,0,0,f),ms.clearBuffer(),c+=r[m].byteLength/He,!o);m++);if(Ct.releasePrimitive(f),Sn.clearBuffer(),a+=s[d].byteLength/He,o)break}return Ds=!1,o}function ht(i,e,t,n,s,r=0,o=0,a=0,c=0,u=null,d=!1){let h,f;d?(h=ms,f=Sn):(h=Sn,f=ms);const m=h.float32Array,w=h.uint32Array,b=h.uint16Array,_=f.float32Array,A=f.uint32Array,T=f.uint16Array,x=i*2,S=e*2,M=Ie(x,b),P=Ie(S,T);let I=!1;if(P&&M)d?I=s(Ge(e,A),Xe(e*2,T),Ge(i,w),Xe(i*2,b),c,o+e/Ne,a,r+i/Ne):I=s(Ge(i,w),Xe(i*2,b),Ge(e,A),Xe(e*2,T),a,r+i/Ne,c,o+e/Ne);else if(P){const C=Ct.getPrimitive();Ae(e,_,C),C.applyMatrix4(t);const D=Be(i),L=ze(i,w);Ae(D,m,Wt),Ae(L,m,Zt);const k=C.intersectsBox(Wt),N=C.intersectsBox(Zt);I=k&&ht(e,D,n,t,s,o,r,c,a+1,C,!d)||N&&ht(e,L,n,t,s,o,r,c,a+1,C,!d),Ct.releasePrimitive(C)}else{const C=Be(e),D=ze(e,A);Ae(C,_,Ps),Ae(D,_,Os);const L=u.intersectsBox(Ps),k=u.intersectsBox(Os);if(L&&k)I=ht(i,C,t,n,s,r,o,a,c+1,u,d)||ht(i,D,t,n,s,r,o,a,c+1,u,d);else if(L)if(M)I=ht(i,C,t,n,s,r,o,a,c+1,u,d);else{const N=Ct.getPrimitive();N.copy(Ps).applyMatrix4(t);const H=Be(i),j=ze(i,w);Ae(H,m,Wt),Ae(j,m,Zt);const $=N.intersectsBox(Wt),re=N.intersectsBox(Zt);I=$&&ht(C,H,n,t,s,o,r,c,a+1,N,!d)||re&&ht(C,j,n,t,s,o,r,c,a+1,N,!d),Ct.releasePrimitive(N)}else if(k)if(M)I=ht(i,D,t,n,s,r,o,a,c+1,u,d);else{const N=Ct.getPrimitive();N.copy(Os).applyMatrix4(t);const H=Be(i),j=ze(i,w);Ae(H,m,Wt),Ae(j,m,Zt);const $=N.intersectsBox(Wt),re=N.intersectsBox(Zt);I=$&&ht(D,H,n,t,s,o,r,c,a+1,N,!d)||re&&ht(D,j,n,t,s,o,r,c,a+1,N,!d),Ct.releasePrimitive(N)}}return I}const Zi=new p.Box3,Kt=new Float32Array(6);class _a{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Or,...e},wa(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0;for(let h=e,f=e+t;h<f;h++){this.writePrimitiveBounds(h,Kt,0);const[m,w,b,_,A,T]=Kt;m<r&&(r=m),_>c&&(c=_),w<o&&(o=w),A>u&&(u=A),b<a&&(a=b),T>d&&(d=T)}return n[s+0]=r,n[s+1]=o,n[s+2]=a,n[s+3]=c,n[s+4]=u,n[s+5]=d,n}computePrimitiveBounds(e,t,n){const s=n.offset||0;for(let r=e,o=e+t;r<o;r++){this.writePrimitiveBounds(r,Kt,0);const[a,c,u,d,h,f]=Kt,m=(a+d)/2,w=(c+h)/2,b=(u+f)/2,_=(d-a)/2,A=(h-c)/2,T=(f-u)/2,x=(r-s)*6;n[x+0]=m,n[x+1]=_+(Math.abs(m)+_)*us,n[x+2]=w,n[x+3]=A+(Math.abs(w)+A)*us,n[x+4]=b,n[x+5]=T+(Math.abs(b)+T)*us}return n}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,s=t.length;n<s;n++)t[n]+=e;else{const n=this._roots;for(let s=0;s<n.length;s++){const r=n[s],o=new Uint32Array(r),a=new Uint16Array(r),c=r.byteLength/He;for(let u=0;u<c;u++){const d=Ne*u,h=2*d;Ie(h,a)&&(o[d+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],s=new Uint32Array(n),r=new Uint16Array(n);o(0);function o(a,c=0){const u=a*2,d=Ie(u,r);if(d){const h=s[a+6],f=r[u+14];e(c,d,new Float32Array(n,a*4,6),h,f)}else{const h=Be(a),f=ze(a,s),m=Ts(a,s);e(c,d,new Float32Array(n,a*4,6),m)||(o(h,c+1),o(f,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const s=e[t],r=new Uint32Array(s),o=new Uint16Array(s),a=new Float32Array(s),c=s.byteLength/He;for(let u=c-1;u>=0;u--){const d=u*Ne,h=d*2;if(Ie(h,o)){const m=Ge(d,r),w=Xe(h,o);this.writePrimitiveRangeBounds(m,w,Kt,0),a.set(Kt,d)}else{const m=Be(d),w=ze(d,r);for(let b=0;b<3;b++){const _=a[m+b],A=a[m+b+3],T=a[w+b],x=a[w+b+3];a[d+b]=_<T?_:T,a[d+b+3]=A>x?A:x}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{Ae(0,new Float32Array(n),Zi),e.union(Zi)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:s,intersectsPrimitive:r,scratchPrimitive:o,iterate:a}=e;if(s&&r){const h=s;s=(f,m,w,b,_)=>h(f,m,w,b,_)?!0:a(f,m,this,r,w,b,o)}else s||(r?s=(h,f,m,w)=>a(h,f,this,r,m,w,o):s=(h,f,m)=>m);let c=!1,u=0;const d=this._roots;for(let h=0,f=d.length;h<f;h++){const m=d[h];if(c=Ta(this,h,n,s,t,u),c)break;u+=m.byteLength/He}return c}bvhcast(e,t,n){let{intersectsRanges:s}=n;return Sa(this,e,t,s)}}function ba(){return typeof SharedArrayBuffer<"u"}function Ss(i){return i.index?i.index.count:i.attributes.position.count}function _s(i){return Ss(i)/3}function kr(i,e=ArrayBuffer){return i>65535?new Uint32Array(new e(4*i)):new Uint16Array(new e(2*i))}function xa(i,e){if(!i.index){const t=i.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=kr(t,n);i.setIndex(new p.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function Aa(i,e,t){const n=Ss(i)/t,s=e||i.drawRange,r=s.start/t,o=(s.start+s.count)/t,a=Math.max(0,r),c=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function Ma(i,e){return i.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Ki(i,e,t){const n=Aa(i,e,t),s=Ma(i,t);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,c=Ss(i)/t,u=[];for(const f of s){const{offset:m,count:w}=f,b=m,_=isFinite(w)?w:c-m,A=m+_;b<a&&A>o&&(u.push({pos:Math.max(o,b),isStart:!0}),u.push({pos:Math.min(a,A),isStart:!1}))}u.sort((f,m)=>f.pos!==m.pos?f.pos-m.pos:f.type==="end"?-1:1);let d=0,h=null;for(const f of u){const m=f.pos;d!==0&&m!==h&&r.push({offset:h,count:m-h}),d+=f.isStart?1:-1,h=m}return r}function Ra(i,e){const t=i[i.length-1],n=t.offset+t.count>2**16,s=i.reduce((u,d)=>u+d.count,0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let c=0;for(let u=0;u<i.length;u++){const{offset:d,count:h}=i[u];for(let f=0;f<h;f++)a[c+f]=d+f;c+=h}return a}class va extends _a{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(t.useSharedArrayBuffer&&!ba())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?n=>this._indirectBuffer[n]:n=>n,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,t={...Or,...t},t[Ei]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=Ki(t,e.range,n),r=Ra(s,e.useSharedArrayBuffer);this._indirectBuffer=r}else xa(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new p.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Ki(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class bt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const c=e[r][t];n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}setFromPoints(e,t){let n=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],c=e.dot(a);n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}bt.prototype.setFromBox=(function(){const i=new p.Vector3;return function(t,n){const s=n.min,r=n.max;let o=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)for(let d=0;d<=1;d++){i.x=s.x*c+r.x*(1-c),i.y=s.y*u+r.y*(1-u),i.z=s.z*d+r.z*(1-d);const h=t.dot(i);o=Math.min(h,o),a=Math.max(h,a)}this.min=o,this.max=a}})();const Ca=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Vector3;return function(s,r,o){const a=s.start,c=i,u=r.start,d=e;t.subVectors(a,u),i.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const h=t.dot(d),f=d.dot(c),m=d.dot(d),w=t.dot(c),_=c.dot(c)*m-f*f;let A,T;_!==0?A=(h*f-w*m)/_:A=0,T=(h+A*f)/m,o.x=A,o.y=T}})(),Si=(function(){const i=new p.Vector2,e=new p.Vector3,t=new p.Vector3;return function(s,r,o,a){Ca(s,r,i);let c=i.x,u=i.y;if(c>=0&&c<=1&&u>=0&&u<=1){s.at(c,o),r.at(u,a);return}else if(c>=0&&c<=1){u<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(u>=0&&u<=1){c<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let d;c<0?d=s.start:d=s.end;let h;u<0?h=r.start:h=r.end;const f=e,m=t;if(s.closestPointToPoint(h,!0,e),r.closestPointToPoint(d,!0,t),f.distanceToSquared(h)<=m.distanceToSquared(d)){o.copy(f),a.copy(h);return}else{o.copy(d),a.copy(m);return}}}})(),Ia=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Plane,n=new p.Line3;return function(r,o){const{radius:a,center:c}=r,{a:u,b:d,c:h}=o;if(n.start=u,n.end=d,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a||(n.start=u,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a)||(n.start=d,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a))return!0;const b=o.getPlane(t);if(Math.abs(b.distanceToPoint(c))<=a){const A=b.projectPoint(c,e);if(o.containsPoint(A))return!0}return!1}})(),La=["x","y","z"],Tt=1e-15,Xi=Tt*Tt;function nt(i){return Math.abs(i)<Tt}class dt extends p.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new p.Vector3),this.satBounds=new Array(4).fill().map(()=>new bt),this.points=[this.a,this.b,this.c],this.plane=new p.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new p.Line3,this.needsUpdate=!0}intersectsSphere(e){return Ia(e,this)}update(){const e=this.a,t=this.b,n=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],c=o[0];this.getNormal(a),c.setFromPoints(a,s);const u=r[1],d=o[1];u.subVectors(e,t),d.setFromPoints(u,s);const h=r[2],f=o[2];h.subVectors(t,n),f.setFromPoints(h,s);const m=r[3],w=o[3];m.subVectors(n,e),w.setFromPoints(m,s);const b=u.length(),_=h.length(),A=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,b<Tt?_<Tt||A<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):_<Tt?A<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<Tt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}dt.prototype.closestPointToSegment=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Line3;return function(s,r=null,o=null){const{start:a,end:c}=s,u=this.points;let d,h=1/0;for(let f=0;f<3;f++){const m=(f+1)%3;t.start.copy(u[f]),t.end.copy(u[m]),Si(t,s,i,e),d=i.distanceToSquared(e),d<h&&(h=d,r&&r.copy(i),o&&o.copy(e))}return this.closestPointToPoint(a,i),d=a.distanceToSquared(i),d<h&&(h=d,r&&r.copy(i),o&&o.copy(a)),this.closestPointToPoint(c,i),d=c.distanceToSquared(i),d<h&&(h=d,r&&r.copy(i),o&&o.copy(c)),Math.sqrt(h)}})();dt.prototype.intersectsTriangle=(function(){const i=new dt,e=new bt,t=new bt,n=new p.Vector3,s=new p.Vector3,r=new p.Vector3,o=new p.Vector3,a=new p.Line3,c=new p.Line3,u=new p.Vector3,d=new p.Vector2,h=new p.Vector2;function f(x,S,M,P){const I=n;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?I.copy(x.plane.normal):I.copy(S.plane.normal);const C=x.satBounds,D=x.satAxes;for(let N=1;N<4;N++){const H=C[N],j=D[N];if(e.setFromPoints(j,S.points),H.isSeparated(e)||(o.copy(I).cross(j),e.setFromPoints(o,x.points),t.setFromPoints(o,S.points),e.isSeparated(t)))return!1}const L=S.satBounds,k=S.satAxes;for(let N=1;N<4;N++){const H=L[N],j=k[N];if(e.setFromPoints(j,x.points),H.isSeparated(e)||(o.crossVectors(I,j),e.setFromPoints(o,x.points),t.setFromPoints(o,S.points),e.isSeparated(t)))return!1}return M&&(P||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),M.start.set(0,0,0),M.end.set(0,0,0)),!0}function m(x,S,M,P,I,C,D,L,k,N,H){let j=D/(D-L);N.x=P+(I-P)*j,H.start.subVectors(S,x).multiplyScalar(j).add(x),j=D/(D-k),N.y=P+(C-P)*j,H.end.subVectors(M,x).multiplyScalar(j).add(x)}function w(x,S,M,P,I,C,D,L,k,N,H){if(I>0)m(x.c,x.a,x.b,P,S,M,k,D,L,N,H);else if(C>0)m(x.b,x.a,x.c,M,S,P,L,D,k,N,H);else if(L*k>0||D!=0)m(x.a,x.b,x.c,S,M,P,D,L,k,N,H);else if(L!=0)m(x.b,x.a,x.c,M,S,P,L,D,k,N,H);else if(k!=0)m(x.c,x.a,x.b,P,S,M,k,D,L,N,H);else return!0;return!1}function b(x,S,M,P){const I=S.degenerateSegment,C=x.plane.distanceToPoint(I.start),D=x.plane.distanceToPoint(I.end);return nt(C)?nt(D)?f(x,S,M,P):(M&&(M.start.copy(I.start),M.end.copy(I.start)),x.containsPoint(I.start)):nt(D)?(M&&(M.start.copy(I.end),M.end.copy(I.end)),x.containsPoint(I.end)):x.plane.intersectLine(I,n)!=null?(M&&(M.start.copy(n),M.end.copy(n)),x.containsPoint(n)):!1}function _(x,S,M){const P=S.a;return nt(x.plane.distanceToPoint(P))&&x.containsPoint(P)?(M&&(M.start.copy(P),M.end.copy(P)),!0):!1}function A(x,S,M){const P=x.degenerateSegment,I=S.a;return P.closestPointToPoint(I,!0,n),I.distanceToSquared(n)<Xi?(M&&(M.start.copy(I),M.end.copy(I)),!0):!1}function T(x,S,M,P){if(x.isDegenerateIntoSegment)if(S.isDegenerateIntoSegment){const I=x.degenerateSegment,C=S.degenerateSegment,D=s,L=r;I.delta(D),C.delta(L);const k=n.subVectors(C.start,I.start),N=D.x*L.y-D.y*L.x;if(nt(N))return!1;const H=(k.x*L.y-k.y*L.x)/N,j=-(D.x*k.y-D.y*k.x)/N;if(H<0||H>1||j<0||j>1)return!1;const $=I.start.z+D.z*H,re=C.start.z+L.z*j;return nt($-re)?(M&&(M.start.copy(I.start).addScaledVector(D,H),M.end.copy(I.start).addScaledVector(D,H)),!0):!1}else return S.isDegenerateIntoPoint?A(x,S,M):b(S,x,M,P);else{if(x.isDegenerateIntoPoint)return S.isDegenerateIntoPoint?S.a.distanceToSquared(x.a)<Xi?(M&&(M.start.copy(x.a),M.end.copy(x.a)),!0):!1:S.isDegenerateIntoSegment?A(S,x,M):_(S,x,M);if(S.isDegenerateIntoPoint)return _(x,S,M);if(S.isDegenerateIntoSegment)return b(x,S,M,P)}}return function(S,M=null,P=!1){this.needsUpdate&&this.update(),S.isExtendedTriangle?S.needsUpdate&&S.update():(i.copy(S),i.update(),S=i);const I=T(this,S,M,P);if(I!==void 0)return I;const C=this.plane,D=S.plane;let L=D.distanceToPoint(this.a),k=D.distanceToPoint(this.b),N=D.distanceToPoint(this.c);nt(L)&&(L=0),nt(k)&&(k=0),nt(N)&&(N=0);const H=L*k,j=L*N;if(H>0&&j>0)return!1;let $=C.distanceToPoint(S.a),re=C.distanceToPoint(S.b),ke=C.distanceToPoint(S.c);nt($)&&($=0),nt(re)&&(re=0),nt(ke)&&(ke=0);const ot=$*re,ve=$*ke;if(ot>0&&ve>0)return!1;s.copy(C.normal),r.copy(D.normal);const Ue=s.cross(r);let je=0,Me=Math.abs(Ue.x);const ye=Math.abs(Ue.y);ye>Me&&(Me=ye,je=1),Math.abs(Ue.z)>Me&&(je=2);const We=La[je],xt=this.a[We],ge=this.b[We],at=this.c[We],ct=S.a[We],an=S.b[We],Vt=S.c[We];if(w(this,xt,ge,at,H,j,L,k,N,d,a))return f(this,S,M,P);if(w(S,ct,an,Vt,ot,ve,$,re,ke,h,c))return f(this,S,M,P);if(d.y<d.x){const wt=d.y;d.y=d.x,d.x=wt,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(h.y<h.x){const wt=h.y;h.y=h.x,h.x=wt,u.copy(c.start),c.start.copy(c.end),c.end.copy(u)}return d.y<h.x||h.y<d.x?!1:(M&&(h.x>d.x?M.start.copy(c.start):M.start.copy(a.start),h.y<d.y?M.end.copy(c.end):M.end.copy(a.end)),!0)}})();dt.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();dt.prototype.distanceToTriangle=(function(){const i=new p.Vector3,e=new p.Vector3,t=["a","b","c"],n=new p.Line3,s=new p.Line3;return function(o,a=null,c=null){const u=a||c?n:null;if(this.intersectsTriangle(o,u,!0))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let d=1/0;for(let h=0;h<3;h++){let f;const m=t[h],w=o[m];this.closestPointToPoint(w,i),f=w.distanceToSquared(i),f<d&&(d=f,a&&a.copy(i),c&&c.copy(w));const b=this[m];o.closestPointToPoint(b,i),f=b.distanceToSquared(i),f<d&&(d=f,a&&a.copy(b),c&&c.copy(i))}for(let h=0;h<3;h++){const f=t[h],m=t[(h+1)%3];n.set(this[f],this[m]);for(let w=0;w<3;w++){const b=t[w],_=t[(w+1)%3];s.set(o[b],o[_]),Si(n,s,i,e);const A=i.distanceToSquared(e);A<d&&(d=A,a&&a.copy(i),c&&c.copy(e))}}return Math.sqrt(d)}})();class Ye{constructor(e,t,n){this.isOrientedBox=!0,this.min=new p.Vector3,this.max=new p.Vector3,this.matrix=new p.Matrix4,this.invMatrix=new p.Matrix4,this.points=new Array(8).fill().map(()=>new p.Vector3),this.satAxes=new Array(3).fill().map(()=>new p.Vector3),this.satBounds=new Array(3).fill().map(()=>new bt),this.alignedSatBounds=new Array(3).fill().map(()=>new bt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ye.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,s=this.points;for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)for(let h=0;h<=1;h++){const f=1*u|2*d|4*h,m=s[f];m.x=u?n.x:t.x,m.y=d?n.y:t.y,m.z=h?n.z:t.z,m.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let u=0;u<3;u++){const d=o[u],h=r[u],f=1<<u,m=s[f];d.subVectors(a,m),h.setFromPoints(d,s)}const c=this.alignedSatBounds;c[0].setFromPointsField(s,"x"),c[1].setFromPointsField(s,"y"),c[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();Ye.prototype.intersectsBox=(function(){const i=new bt;return function(t){this.needsUpdate&&this.update();const n=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(i.min=n.x,i.max=s.x,a[0].isSeparated(i)||(i.min=n.y,i.max=s.y,a[1].isSeparated(i))||(i.min=n.z,i.max=s.z,a[2].isSeparated(i)))return!1;for(let c=0;c<3;c++){const u=o[c],d=r[c];if(i.setFromBox(u,t),d.isSeparated(i))return!1}return!0}})();Ye.prototype.intersectsTriangle=(function(){const i=new dt,e=new Array(3),t=new bt,n=new bt,s=new p.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(i.copy(o),i.update(),o=i);const a=this.satBounds,c=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const m=a[f],w=c[f];if(t.setFromPoints(w,e),m.isSeparated(t))return!1}const u=o.satBounds,d=o.satAxes,h=this.points;for(let f=0;f<3;f++){const m=u[f],w=d[f];if(t.setFromPoints(w,h),m.isSeparated(t))return!1}for(let f=0;f<3;f++){const m=c[f];for(let w=0;w<4;w++){const b=d[w];if(s.crossVectors(m,b),t.setFromPoints(s,e),n.setFromPoints(s,h),t.isSeparated(n))return!1}}return!0}})();Ye.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();Ye.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();Ye.prototype.distanceToBox=(function(){const i=["x","y","z"],e=new Array(12).fill().map(()=>new p.Line3),t=new Array(12).fill().map(()=>new p.Line3),n=new p.Vector3,s=new p.Vector3;return function(o,a=0,c=null,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(c||u)&&(o.getCenter(s),this.closestPointToPoint(s,n),o.closestPointToPoint(n,s),c&&c.copy(n),u&&u.copy(s)),0;const d=a*a,h=o.min,f=o.max,m=this.points;let w=1/0;for(let _=0;_<8;_++){const A=m[_];s.copy(A).clamp(h,f);const T=A.distanceToSquared(s);if(T<w&&(w=T,c&&c.copy(A),u&&u.copy(s),T<d))return Math.sqrt(T)}let b=0;for(let _=0;_<3;_++)for(let A=0;A<=1;A++)for(let T=0;T<=1;T++){const x=(_+1)%3,S=(_+2)%3,M=A<<x|T<<S,P=1<<_|A<<x|T<<S,I=m[M],C=m[P];e[b].set(I,C);const L=i[_],k=i[x],N=i[S],H=t[b],j=H.start,$=H.end;j[L]=h[L],j[k]=A?h[k]:f[k],j[N]=T?h[N]:f[k],$[L]=f[L],$[k]=A?h[k]:f[k],$[N]=T?h[N]:f[k],b++}for(let _=0;_<=1;_++)for(let A=0;A<=1;A++)for(let T=0;T<=1;T++){s.x=_?f.x:h.x,s.y=A?f.y:h.y,s.z=T?f.z:h.z,this.closestPointToPoint(s,n);const x=s.distanceToSquared(n);if(x<w&&(w=x,c&&c.copy(n),u&&u.copy(s),x<d))return Math.sqrt(x)}for(let _=0;_<12;_++){const A=e[_];for(let T=0;T<12;T++){const x=t[T];Si(A,x,n,s);const S=n.distanceToSquared(s);if(S<w&&(w=S,c&&c.copy(n),u&&u.copy(s),S<d))return Math.sqrt(S)}}return Math.sqrt(w)}})();class Pa extends Ti{constructor(){super(()=>new dt)}}const rt=new Pa,dn=new p.Vector3,Ns=new p.Vector3;function Oa(i,e,t={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,c=null;if(i.shapecast({boundsTraverseOrder:d=>(dn.copy(e).clamp(d.min,d.max),dn.distanceToSquared(e)),intersectsBounds:(d,h,f)=>f<a&&f<o,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,dn);const f=e.distanceToSquared(dn);return f<a&&(Ns.copy(dn),a=f,c=h),f<r}}),a===1/0)return null;const u=Math.sqrt(a);return t.point?t.point.copy(Ns):t.point=Ns.clone(),t.distance=u,t.faceIndex=c,t}const Wn=parseInt(p.REVISION)>=169,Da=parseInt(p.REVISION)<=161,Nt=new p.Vector3,kt=new p.Vector3,Ft=new p.Vector3,Zn=new p.Vector2,Kn=new p.Vector2,Xn=new p.Vector2,Yi=new p.Vector3,qi=new p.Vector3,$i=new p.Vector3,fn=new p.Vector3;function Na(i,e,t,n,s,r,o,a){let c;if(r===p.BackSide?c=i.intersectTriangle(n,t,e,!0,s):c=i.intersectTriangle(e,t,n,r!==p.DoubleSide,s),c===null)return null;const u=i.origin.distanceTo(s);return u<o||u>a?null:{distance:u,point:s.clone()}}function Qi(i,e,t,n,s,r,o,a,c,u,d){Nt.fromBufferAttribute(e,r),kt.fromBufferAttribute(e,o),Ft.fromBufferAttribute(e,a);const h=Na(i,Nt,kt,Ft,fn,c,u,d);if(h){if(n){Zn.fromBufferAttribute(n,r),Kn.fromBufferAttribute(n,o),Xn.fromBufferAttribute(n,a),h.uv=new p.Vector2;const m=p.Triangle.getInterpolation(fn,Nt,kt,Ft,Zn,Kn,Xn,h.uv);Wn||(h.uv=m)}if(s){Zn.fromBufferAttribute(s,r),Kn.fromBufferAttribute(s,o),Xn.fromBufferAttribute(s,a),h.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(fn,Nt,kt,Ft,Zn,Kn,Xn,h.uv1);Wn||(h.uv1=m),Da&&(h.uv2=h.uv1)}if(t){Yi.fromBufferAttribute(t,r),qi.fromBufferAttribute(t,o),$i.fromBufferAttribute(t,a),h.normal=new p.Vector3;const m=p.Triangle.getInterpolation(fn,Nt,kt,Ft,Yi,qi,$i,h.normal);h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1),Wn||(h.normal=m)}const f={a:r,b:o,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(Nt,kt,Ft,f.normal),h.face=f,h.faceIndex=r,Wn){const m=new p.Vector3;p.Triangle.getBarycoord(fn,Nt,kt,Ft,m),h.barycoord=m}}return h}function Ji(i){return i&&i.isMaterial?i.side:i}function bs(i,e,t,n,s,r,o){const a=n*3;let c=a+0,u=a+1,d=a+2;const{index:h,groups:f}=i;i.index&&(c=h.getX(c),u=h.getX(u),d=h.getX(d));const{position:m,normal:w,uv:b,uv1:_}=i.attributes;if(Array.isArray(e)){const A=n*3;for(let T=0,x=f.length;T<x;T++){const{start:S,count:M,materialIndex:P}=f[T];if(A>=S&&A<S+M){const I=Ji(e[P]),C=Qi(t,m,w,b,_,c,u,d,I,r,o);if(C)if(C.faceIndex=n,C.face.materialIndex=P,s)s.push(C);else return C}}}else{const A=Ji(e),T=Qi(t,m,w,b,_,c,u,d,A,r,o);if(T)if(T.faceIndex=n,T.face.materialIndex=0,s)s.push(T);else return T}return null}function Le(i,e,t,n){const s=i.a,r=i.b,o=i.c;let a=e,c=e+1,u=e+2;t&&(a=t.getX(a),c=t.getX(c),u=t.getX(u)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(c),r.y=n.getY(c),r.z=n.getZ(c),o.x=n.getX(u),o.y=n.getY(u),o.z=n.getZ(u)}function ka(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++)bs(c,e,t,d,r,o,a)}function Fa(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let u=1/0,d=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,h,null,r,o),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ba(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=i,h=e+i;d<h;d++){let f;if(f=d,Le(o,f*3,c,u),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function za(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)r=d[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,u),u+=r.byteLength;function h(f,m,w=!1){const b=f*2;if(Ie(b,a)){const _=Ge(f,o),A=Xe(b,a);let T=1/0,x=1/0,S=1/0,M=-1/0,P=-1/0,I=-1/0;for(let C=3*_,D=3*(_+A);C<D;C++){let L=n[C];const k=s.getX(L),N=s.getY(L),H=s.getZ(L);k<T&&(T=k),k>M&&(M=k),N<x&&(x=N),N>P&&(P=N),H<S&&(S=H),H>I&&(I=H)}return c[f+0]!==T||c[f+1]!==x||c[f+2]!==S||c[f+3]!==M||c[f+4]!==P||c[f+5]!==I?(c[f+0]=T,c[f+1]=x,c[f+2]=S,c[f+3]=M,c[f+4]=P,c[f+5]=I,!0):!1}else{const _=Be(f),A=ze(f,o);let T=w,x=!1,S=!1;if(e){if(!T){const L=_/Ne+m/He,k=A/Ne+m/He;x=e.has(L),S=e.has(k),T=!x&&!S}}else x=!0,S=!0;const M=T||x,P=T||S;let I=!1;M&&(I=h(_,m,T));let C=!1;P&&(C=h(A,m,T));const D=I||C;if(D)for(let L=0;L<3;L++){const k=_+L,N=A+L,H=c[k],j=c[k+3],$=c[N],re=c[N+3];c[f+L]=H<$?H:$,c[f+L+3]=j>re?j:re}return D}}}function Ot(i,e,t,n,s){let r,o,a,c,u,d;const h=1/t.direction.x,f=1/t.direction.y,m=1/t.direction.z,w=t.origin.x,b=t.origin.y,_=t.origin.z;let A=e[i],T=e[i+3],x=e[i+1],S=e[i+3+1],M=e[i+2],P=e[i+3+2];return h>=0?(r=(A-w)*h,o=(T-w)*h):(r=(T-w)*h,o=(A-w)*h),f>=0?(a=(x-b)*f,c=(S-b)*f):(a=(S-b)*f,c=(x-b)*f),r>c||a>o||((a>r||isNaN(r))&&(r=a),(c<o||isNaN(o))&&(o=c),m>=0?(u=(M-_)*m,d=(P-_)*m):(u=(P-_)*m,d=(M-_)*m),r>d||u>o)?!1:((u>r||r!==r)&&(r=u),(d<o||o!==o)&&(o=d),r<=s&&o>=n)}function Ua(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++){let f=u?u[d]:d;bs(c,e,t,f,r,o,a)}}function Va(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let u=1/0,d=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,c?c[h]:h,null,r,o),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ha(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=i,h=e+i;d<h;d++){let f;if(f=t.resolveTriangleIndex(d),Le(o,f*3,c,u),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function Ga(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),si(0,i,t,n,s,r,o),be.clearBuffer()}function si(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ie(d,c)){const f=Ge(i,u),m=Xe(d,c);ka(e,t,n,f,m,s,r,o)}else{const f=Be(i);Ot(f,a,n,r,o)&&si(f,e,t,n,s,r,o);const m=ze(i,u);Ot(m,a,n,r,o)&&si(m,e,t,n,s,r,o)}}const ja=["x","y","z"];function Wa(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=ii(0,i,t,n,s,r);return be.clearBuffer(),o}function ii(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ie(u,a)){const h=Ge(i,c),f=Xe(u,a);return Fa(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=ja[h],w=n.direction[f]>=0;let b,_;w?(b=Be(i),_=ze(i,c)):(b=ze(i,c),_=Be(i));const T=Ot(b,o,n,s,r)?ii(b,e,t,n,s,r):null;if(T){const M=T.point[f];if(w?M<=o[_+h]:M>=o[_+h+3])return T}const S=Ot(_,o,n,s,r)?ii(_,e,t,n,s,r):null;return T&&S?T.distance<=S.distance?T:S:T||S||null}}const Yn=new p.Box3,Xt=new dt,Yt=new dt,pn=new p.Matrix4,er=new Ye,qn=new Ye;function Za(i,e,t,n){be.setBuffer(i._roots[e]);const s=ri(0,i,t,n);return be.clearBuffer(),s}function ri(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),er.set(t.boundingBox.min,t.boundingBox.max,n),s=er),Ie(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,b=Ge(i,a),_=Xe(c,o);if(pn.copy(n).invert(),t.boundsTree)return Ae(i,r,qn),qn.matrix.copy(pn),qn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>qn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let x=b*3,S=(_+b)*3;x<S;x+=3)if(Le(Yt,x,h,f),Yt.needsUpdate=!0,T.intersectsTriangle(Yt))return!0;return!1}});{const A=_s(t);for(let T=b*3,x=(_+b)*3;T<x;T+=3){Le(Xt,T,h,f),Xt.a.applyMatrix4(pn),Xt.b.applyMatrix4(pn),Xt.c.applyMatrix4(pn),Xt.needsUpdate=!0;for(let S=0,M=A*3;S<M;S+=3)if(Le(Yt,S,m,w),Yt.needsUpdate=!0,Xt.intersectsTriangle(Yt))return!0}}}else{const d=Be(i),h=ze(i,a);return Ae(d,r,Yn),!!(s.intersectsBox(Yn)&&ri(d,e,t,n,s)||(Ae(h,r,Yn),s.intersectsBox(Yn)&&ri(h,e,t,n,s)))}}const $n=new p.Matrix4,ks=new Ye,mn=new Ye,Ka=new p.Vector3,Xa=new p.Vector3,Ya=new p.Vector3,qa=new p.Vector3;function $a(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),ks.set(e.boundingBox.min,e.boundingBox.max,t),ks.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let w=Ka,b=Xa,_=null,A=null;s&&(_=Ya,A=qa);let T=1/0,x=null,S=null;return $n.copy(t).invert(),mn.matrix.copy($n),i.shapecast({boundsTraverseOrder:M=>ks.distanceToBox(M),intersectsBounds:(M,P,I)=>I<T&&I<o?(P&&(mn.min.copy(M.min),mn.max.copy(M.max),mn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>mn.distanceToBox(C),intersectsBounds:(C,D,L)=>L<T&&L<o,intersectsRange:(C,D)=>{for(let L=C,k=C+D;L<k;L++){Le(m,3*L,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let N=M,H=M+P;N<H;N++){Le(f,3*N,u,c),f.needsUpdate=!0;const j=f.distanceToTriangle(m,w,_);if(j<T&&(b.copy(w),A&&A.copy(_),T=j,x=N,S=L),j<r)return!0}}}});{const I=_s(e);for(let C=0,D=I;C<D;C++){Le(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let L=M,k=M+P;L<k;L++){Le(f,3*L,u,c),f.needsUpdate=!0;const N=f.distanceToTriangle(m,w,_);if(N<T&&(b.copy(w),A&&A.copy(_),T=N,x=L,S=C),N<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=T,n.faceIndex=x,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4($n),b.applyMatrix4($n),s.distance=b.sub(s.point).length(),s.faceIndex=S),n)}function Qa(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)r=d[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,u),u+=r.byteLength;function h(f,m,w=!1){const b=f*2;if(Ie(b,a)){const _=Ge(f,o),A=Xe(b,a);let T=1/0,x=1/0,S=1/0,M=-1/0,P=-1/0,I=-1/0;for(let C=_,D=_+A;C<D;C++){const L=3*i.resolveTriangleIndex(C);for(let k=0;k<3;k++){let N=L+k;N=n?n[N]:N;const H=s.getX(N),j=s.getY(N),$=s.getZ(N);H<T&&(T=H),H>M&&(M=H),j<x&&(x=j),j>P&&(P=j),$<S&&(S=$),$>I&&(I=$)}}return c[f+0]!==T||c[f+1]!==x||c[f+2]!==S||c[f+3]!==M||c[f+4]!==P||c[f+5]!==I?(c[f+0]=T,c[f+1]=x,c[f+2]=S,c[f+3]=M,c[f+4]=P,c[f+5]=I,!0):!1}else{const _=Be(f),A=ze(f,o);let T=w,x=!1,S=!1;if(e){if(!T){const L=_/Ne+m/He,k=A/Ne+m/He;x=e.has(L),S=e.has(k),T=!x&&!S}}else x=!0,S=!0;const M=T||x,P=T||S;let I=!1;M&&(I=h(_,m,T));let C=!1;P&&(C=h(A,m,T));const D=I||C;if(D)for(let L=0;L<3;L++){const k=_+L,N=A+L,H=c[k],j=c[k+3],$=c[N],re=c[N+3];c[f+L]=H<$?H:$,c[f+L+3]=j>re?j:re}return D}}}function Ja(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),oi(0,i,t,n,s,r,o),be.clearBuffer()}function oi(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ie(d,c)){const f=Ge(i,u),m=Xe(d,c);Ua(e,t,n,f,m,s,r,o)}else{const f=Be(i);Ot(f,a,n,r,o)&&oi(f,e,t,n,s,r,o);const m=ze(i,u);Ot(m,a,n,r,o)&&oi(m,e,t,n,s,r,o)}}const ec=["x","y","z"];function tc(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=ai(0,i,t,n,s,r);return be.clearBuffer(),o}function ai(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ie(u,a)){const h=Ge(i,c),f=Xe(u,a);return Va(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=ec[h],w=n.direction[f]>=0;let b,_;w?(b=Be(i),_=ze(i,c)):(b=ze(i,c),_=Be(i));const T=Ot(b,o,n,s,r)?ai(b,e,t,n,s,r):null;if(T){const M=T.point[f];if(w?M<=o[_+h]:M>=o[_+h+3])return T}const S=Ot(_,o,n,s,r)?ai(_,e,t,n,s,r):null;return T&&S?T.distance<=S.distance?T:S:T||S||null}}const Qn=new p.Box3,qt=new dt,$t=new dt,gn=new p.Matrix4,tr=new Ye,Jn=new Ye;function nc(i,e,t,n){be.setBuffer(i._roots[e]);const s=ci(0,i,t,n);return be.clearBuffer(),s}function ci(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),tr.set(t.boundingBox.min,t.boundingBox.max,n),s=tr),Ie(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,b=Ge(i,a),_=Xe(c,o);if(gn.copy(n).invert(),t.boundsTree)return Ae(i,r,Jn),Jn.matrix.copy(gn),Jn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>Jn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let x=b,S=_+b;x<S;x++)if(Le($t,3*e.resolveTriangleIndex(x),h,f),$t.needsUpdate=!0,T.intersectsTriangle($t))return!0;return!1}});{const A=_s(t);for(let T=b,x=_+b;T<x;T++){const S=e.resolveTriangleIndex(T);Le(qt,3*S,h,f),qt.a.applyMatrix4(gn),qt.b.applyMatrix4(gn),qt.c.applyMatrix4(gn),qt.needsUpdate=!0;for(let M=0,P=A*3;M<P;M+=3)if(Le($t,M,m,w),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const d=Be(i),h=ze(i,a);return Ae(d,r,Qn),!!(s.intersectsBox(Qn)&&ci(d,e,t,n,s)||(Ae(h,r,Qn),s.intersectsBox(Qn)&&ci(h,e,t,n,s)))}}const es=new p.Matrix4,Fs=new Ye,yn=new Ye,sc=new p.Vector3,ic=new p.Vector3,rc=new p.Vector3,oc=new p.Vector3;function ac(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Fs.set(e.boundingBox.min,e.boundingBox.max,t),Fs.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let w=sc,b=ic,_=null,A=null;s&&(_=rc,A=oc);let T=1/0,x=null,S=null;return es.copy(t).invert(),yn.matrix.copy(es),i.shapecast({boundsTraverseOrder:M=>Fs.distanceToBox(M),intersectsBounds:(M,P,I)=>I<T&&I<o?(P&&(yn.min.copy(M.min),yn.max.copy(M.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:C=>yn.distanceToBox(C),intersectsBounds:(C,D,L)=>L<T&&L<o,intersectsRange:(C,D)=>{for(let L=C,k=C+D;L<k;L++){const N=I.resolveTriangleIndex(L);Le(m,3*N,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let H=M,j=M+P;H<j;H++){const $=i.resolveTriangleIndex(H);Le(f,3*$,u,c),f.needsUpdate=!0;const re=f.distanceToTriangle(m,w,_);if(re<T&&(b.copy(w),A&&A.copy(_),T=re,x=H,S=L),re<r)return!0}}}})}else{const I=_s(e);for(let C=0,D=I;C<D;C++){Le(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let L=M,k=M+P;L<k;L++){const N=i.resolveTriangleIndex(L);Le(f,3*N,u,c),f.needsUpdate=!0;const H=f.distanceToTriangle(m,w,_);if(H<T&&(b.copy(w),A&&A.copy(_),T=H,x=L,S=C),H<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=T,n.faceIndex=x,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(es),b.applyMatrix4(es),s.distance=b.sub(s.point).length(),s.faceIndex=S),n)}function nr(i,e,t){return i===null?null:(i.point.applyMatrix4(e.matrixWorld),i.distance=i.point.distanceTo(t.ray.origin),i.object=e,i)}const ts=new Ye,ns=new p.Ray,sr=new p.Vector3,ir=new p.Matrix4,rr=new p.Vector3,Bs=["getX","getY","getZ"];class xn extends va{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,s=e._roots,r=e._indirectBuffer,o=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(c=>c.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:s,roots:r,indirectBuffer:o}=e;e.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(r));const a=new xn(t,{...n,[Ei]:!0});if(a._roots=r,a._indirectBuffer=o||null,n.setIndex){const u=t.getIndex();if(u===null){const d=new p.BufferAttribute(e.index,1,!1);t.setIndex(d)}else u.array!==s&&(u.array.set(s),u.needsUpdate=!0)}return a;function c(u){for(let d=0;d<u.length;d++){const h=u[d],f=new Uint32Array(h),m=new Uint16Array(h);for(let w=0,b=h.byteLength/He;w<b;w++){const _=Ne*w,A=2*_;Ie(A,m)||(f[_+6]=f[_+6]/Ne-w)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,u=(r?r[e]:e)*3;let d=u+0,h=u+1,f=u+2;a&&(d=a[d],h=a[h],f=a[f]);for(let m=0;m<3;m++){const w=o[Bs[m]](d),b=o[Bs[m]](h),_=o[Bs[m]](f);let A=w;b<A&&(A=b),_<A&&(A=_);let T=w;b>T&&(T=b),_>T&&(T=_),t[n+m]=A,t[n+m+3]=T}return t}computePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,c=o.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const u=o.array,d=o.offset||0;let h=3;o.isInterleavedBufferAttribute&&(h=o.data.stride);const f=["getX","getY","getZ"],m=n.offset;for(let w=e,b=e+t;w<b;w++){const A=(r?r[w]:w)*3,T=(w-m)*6;let x=A+0,S=A+1,M=A+2;a&&(x=a[x],S=a[S],M=a[M]),c||(x=x*h+d,S=S*h+d,M=M*h+d);for(let P=0;P<3;P++){let I,C,D;c?(I=o[f[P]](x),C=o[f[P]](S),D=o[f[P]](M)):(I=u[x+P],C=u[S+P],D=u[M+P]);let L=I;C<L&&(L=C),D<L&&(L=D);let k=I;C>k&&(k=C),D>k&&(k=D);const N=(k-L)/2,H=P*2;n[T+H+0]=L+N,n[T+H+1]=N+(Math.abs(L)+N)*us}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;ir.copy(e.matrixWorld).invert(),ns.copy(t.ray).applyMatrix4(ir),rr.setFromMatrixScale(e.matrixWorld),sr.copy(ns.direction).multiply(rr);const r=sr.length(),o=t.near/r,a=t.far/r;if(t.firstHitOnly===!0){let c=this.raycastFirst(ns,s,o,a);c=nr(c,e,t),c&&n.push(c)}else{const c=this.raycast(ns,s,o,a);for(let u=0,d=c.length;u<d;u++){const h=nr(c[u],e,t);h&&n.push(h)}}return n}refit(e=null){return(this.indirect?Qa:za)(this,e)}raycast(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots,o=[],a=this.indirect?Ja:Ga;for(let c=0,u=r.length;c<u;c++)a(this,c,t,e,o,n,s);return o}raycastFirst(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?tc:Wa;for(let c=0,u=r.length;c<u;c++){const d=a(this,c,t,e,n,s);d!=null&&(o==null||d.distance<o.distance)&&(o=d)}return o}intersectsGeometry(e,t){let n=!1;const s=this._roots,r=this.indirect?nc:Za;for(let o=0,a=s.length;o<a&&(n=r(this,o,e,t),!n);o++);return n}shapecast(e){const t=rt.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Ha:Ba});return rt.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:s,intersectsTriangles:r}=n;const o=rt.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?w=>{const b=this.resolveTriangleIndex(w);Le(o,b*3,a,c)}:w=>{Le(o,w*3,a,c)},d=rt.getPrimitive(),h=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?w=>{const b=e.resolveTriangleIndex(w);Le(d,b*3,h,f)}:w=>{Le(d,w*3,h,f)};if(r){if(!(e instanceof xn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const w=(b,_,A,T,x,S,M,P)=>{for(let I=A,C=A+T;I<C;I++){m(I),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let D=b,L=b+_;D<L;D++)if(u(D),o.needsUpdate=!0,r(o,d,D,I,x,S,M,P))return!0}return!1};if(s){const b=s;s=function(_,A,T,x,S,M,P,I){return b(_,A,T,x,S,M,P,I)?!0:w(_,A,T,x,S,M,P,I)}}else s=w}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return ts.set(e.min,e.max,t),ts.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ts.intersectsBox(n),intersectsTriangle:n=>ts.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},s={},r=0,o=1/0){return(this.indirect?ac:$a)(this,e,t,n,s,r,o)}closestPointToPoint(e,t={},n=0,s=1/0){return Oa(this,e,t,n,s)}}const tn={Mesh:p.Mesh.prototype.raycast,Line:p.Line.prototype.raycast,LineSegments:p.LineSegments.prototype.raycast,LineLoop:p.LineLoop.prototype.raycast,Points:p.Points.prototype.raycast,BatchedMesh:p.BatchedMesh.prototype.raycast},Ve=new p.Mesh,ss=[];function cc(i,e){if(this.isBatchedMesh)lc.call(this,i,e);else{const{geometry:t}=this;if(t.boundsTree)t.boundsTree.raycastObject3D(this,i,e);else{let n;if(this instanceof p.Mesh)n=tn.Mesh;else if(this instanceof p.LineSegments)n=tn.LineSegments;else if(this instanceof p.LineLoop)n=tn.LineLoop;else if(this instanceof p.Line)n=tn.Line;else if(this instanceof p.Points)n=tn.Points;else throw new Error("BVH: Fallback raycast function not found.");n.call(this,i,e)}}}function lc(i,e){if(this.boundsTrees){const t=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ve.material=this.material,Ve.geometry=this.geometry;const o=Ve.geometry.boundsTree,a=Ve.geometry.drawRange;Ve.geometry.boundingSphere===null&&(Ve.geometry.boundingSphere=new p.Sphere);for(let c=0,u=n.length;c<u;c++){if(!this.getVisibleAt(c))continue;const d=n[c].geometryIndex;if(Ve.geometry.boundsTree=t[d],this.getMatrixAt(c,Ve.matrixWorld).premultiply(r),!Ve.geometry.boundsTree){this.getBoundingBoxAt(d,Ve.geometry.boundingBox),this.getBoundingSphereAt(d,Ve.geometry.boundingSphere);const h=s[d];Ve.geometry.setDrawRange(h.start,h.count)}Ve.raycast(i,ss);for(let h=0,f=ss.length;h<f;h++){const m=ss[h];m.object=this,m.batchId=c,e.push(m)}ss.length=0}Ve.geometry.boundsTree=o,Ve.geometry.drawRange=a,Ve.material=null,Ve.geometry=null}else tn.BatchedMesh.call(this,i,e)}function Fr(i){i.traverse(e=>{var s,r,o;const t=e;if(!t.isMesh||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh)return;const n=t.geometry;!((s=n==null?void 0:n.attributes)!=null&&s.position)||(o=(r=n.morphAttributes)==null?void 0:r.position)!=null&&o.length||(n.boundsTree||(n.boundsTree=new xn(n)),t.raycast=cc)})}function hc(i){i.boundsTree&&(i.boundsTree=void 0)}function or(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof E.Texture&&s.dispose()}const t=i;if(t.isShaderMaterial&&t.uniforms)for(const n of Object.values(t.uniforms))(n==null?void 0:n.value)instanceof E.Texture&&n.value.dispose();i.dispose()}function xs(i){i.traverse(e=>{var r;const t=e;t.geometry&&typeof t.geometry.dispose=="function"&&(hc(t.geometry),t.geometry.dispose());const n=t.material;Array.isArray(n)?n.forEach(or):n&&or(n);const s=e;s.isLight&&((r=s.shadow)!=null&&r.dispose)&&s.shadow.dispose()})}function uc(i,e){if(!(e!=null&&e.keepBackgrounds)){i.background instanceof E.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof E.Texture&&(i.environment.dispose(),i.environment=null);const t=i;t.__originalEnvironmentTexture&&(t.__originalEnvironmentTexture=void 0)}for(const t of[...i.children])xs(t),i.remove(t)}class De{constructor(e){this.object=e,this.positionAdapter=Pt.fromThreeVector(e.position),this.rotationAdapter=Pt.fromThreeVector(e.rotation),this.scaleAdapter=Pt.fromThreeVector(e.scale)}get id(){return this.object.uuid}get name(){return this.object.name}set name(e){this.object.name=e}get visible(){return this.object.visible}set visible(e){this.object.visible=e}get castShadow(){return this.object.castShadow}set castShadow(e){this.object.castShadow=e}get receiveShadow(){return this.object.receiveShadow}set receiveShadow(e){this.object.receiveShadow=e}get position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof De?(this.object.add(e.getThreeObject()),F.ok(void 0)):F.err(new K("Child must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to add child object",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof De?(this.object.remove(e.getThreeObject()),F.ok(void 0)):F.err(new K("Child must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to remove child object",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new De(t))})}clone(){return new De(this.object.clone())}dispose(){xs(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new De(e)}static create(){return new De(new E.Object3D)}}class St{constructor(e){this.scene=e||new E.Scene}get id(){return this.scene.uuid}get name(){return this.scene.name}set name(e){this.scene.name=e}add(e){try{return e instanceof De?(this.scene.add(e.getThreeObject()),F.ok(void 0)):F.err(new K("Object must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to add object to scene",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof De?(this.scene.remove(e.getThreeObject()),F.ok(void 0)):F.err(new K("Object must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to remove object from scene",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeContents(e){uc(this.scene,e)}traverse(e){this.scene.traverse(t=>{e(new De(t))})}get background(){return this.scene.background instanceof E.Color?new li(this.scene.background):this.scene.background instanceof E.Texture?new is(this.scene.background):null}set background(e){e instanceof li?this.scene.background=e.getThreeColor():e instanceof is?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new ar(this.scene.fog):null}set fog(e){e instanceof ar?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new is(this.scene.environment):null}set environment(e){e instanceof is?this.scene.environment=e.getThreeTexture():this.scene.environment=null}setEnvironmentIntensity(e){this.scene.environmentIntensity=e}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class li{constructor(e){this.color=e}get r(){return this.color.r}set r(e){this.color.r=e}get g(){return this.color.g}set g(e){this.color.g=e}get b(){return this.color.b}set b(e){this.color.b=e}setHex(e){this.color.setHex(e)}setRGB(e,t,n){this.color.setRGB(e,t,n)}getHex(){return this.color.getHex()}getThreeColor(){return this.color}}let is=class{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image||null}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}};class ar{constructor(e){this.fog=e}get color(){return new li(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Br extends De{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Pt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new E.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class _i extends Br{constructor(e){const t=e||new E.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=75,t=1,n=.1,s=1e3){return new _i(new E.PerspectiveCamera(e,t,n,s))}}class dc{constructor(e){this.renderer=null,this._id=Ir(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new E.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:E.BasicShadowMap,pcf:E.PCFShadowMap,pcfsoft:E.PCFSoftShadowMap,vsm:E.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:E.NoToneMapping,linear:E.LinearToneMapping,reinhard:E.ReinhardToneMapping,cineon:E.CineonToneMapping,aces:E.ACESFilmicToneMapping};this.renderer.toneMapping=t[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}if(e.pixelRatio!==void 0?this.renderer.setPixelRatio(e.pixelRatio):this.renderer.setPixelRatio(window.devicePixelRatio),this.canvas){const{clientWidth:t,clientHeight:n}=this.canvas.parentElement||this.canvas;t&&n&&this.renderer.setSize(t,n)}return this.renderer.outputColorSpace=E.SRGBColorSpace,F.ok(void 0)}catch(t){return F.err(new K("Failed to initialize renderer",Y.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return F.err(new K("Renderer not initialized",Y.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof St))return F.err(new K("Scene must be a ThreeSceneAdapter",Y.INVALID_PARAMETER));if(!(t instanceof Br))return F.err(new K("Camera must be a ThreeCameraAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),F.ok(void 0)}catch(n){return F.err(new K("Failed to render frame",Y.RENDER_FAILED,{originalError:n}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const n=this.renderer.domElement;n.style.width="100%",n.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(e)}getPixelRatio(){return this.renderer?this.renderer.getPixelRatio():1}setToneMappingExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}getDomElement(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.domElement}getContext(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.getContext()}get capabilities(){if(!this.renderer)return{maxTextureSize:0,maxCubemapSize:0,maxAttributes:0,maxVertexUniforms:0,maxFragmentUniforms:0,maxSamples:0,isWebGL2:!1};const e=this.renderer.capabilities;return{maxTextureSize:e.maxTextureSize,maxCubemapSize:e.maxCubemapSize,maxAttributes:e.maxAttributes,maxVertexUniforms:e.maxVertexUniforms,maxFragmentUniforms:e.maxFragmentUniforms,maxSamples:e.maxSamples||0,isWebGL2:e.isWebGL2}}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}isDisposed(){return this.renderer===null}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function cr(i,e){if(e===p.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===p.TriangleFanDrawMode||e===p.TriangleStripDrawMode){let t=i.getIndex();if(t===null){const o=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);i.setIndex(o),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===p.TriangleFanDrawMode)for(let o=1;o<=n;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}function fc(i){const e=new Map,t=new Map,n=i.clone();return zr(i,n,function(s,r){e.set(r,s),t.set(s,r)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=e.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(c){return t.get(c)}),r.bind(r.skeleton,r.bindMatrix)}),n}function zr(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)zr(i.children[n],e.children[n],t)}class pc extends p.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Ec(t)}),this.register(function(t){return new Tc(t)}),this.register(function(t){return new Cc(t)}),this.register(function(t){return new Ic(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new _c(t)}),this.register(function(t){return new bc(t)}),this.register(function(t){return new xc(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new wc(t)}),this.register(function(t){return new Mc(t)}),this.register(function(t){return new Sc(t)}),this.register(function(t){return new vc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new gc(t)}),this.register(function(t){return new lr(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new lr(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Pc(t)})}load(e,t,n,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const u=p.LoaderUtils.extractUrlBase(e);o=p.LoaderUtils.resolveURL(u,this.path)}else o=p.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(u){s?s(u):console.error(u),r.manager.itemError(e),r.manager.itemEnd(e)},c=new p.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(u){try{r.parse(u,o,function(d){t(d),r.manager.itemEnd(e)},a)}catch(d){a(d)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const o={},a={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===Ur){try{o[le.KHR_BINARY_GLTF]=new Oc(e)}catch(h){s&&s(h);return}r=JSON.parse(o[le.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const u=new Zc(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](u);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,o[h.name]=!0}if(r.extensionsUsed)for(let d=0;d<r.extensionsUsed.length;++d){const h=r.extensionsUsed[d],f=r.extensionsRequired||[];switch(h){case le.KHR_MATERIALS_UNLIT:o[h]=new yc;break;case le.KHR_DRACO_MESH_COMPRESSION:o[h]=new Dc(r,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:o[h]=new Nc;break;case le.KHR_MESH_QUANTIZATION:o[h]=new kc;break;default:f.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}u.setExtensions(o),u.setPlugins(a),u.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function mc(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function Re(i,e,t){const n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class gc{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let u;const d=new p.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],p.LinearSRGBColorSpace);const h=c.range!==void 0?c.range:0;switch(c.type){case"directional":u=new p.DirectionalLight(d),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new p.PointLight(d),u.distance=h;break;case"spot":u=new p.SpotLight(d),u.distance=h,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,u.angle=c.spot.outerConeAngle,u.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return u.position.set(0,0,0),yt(u,c),c.intensity!==void 0&&(u.intensity=c.intensity),u.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(u),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class yc{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return p.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new p.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),e.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,p.SRGBColorSpace))}return Promise.all(s)}}class wc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class Ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const r=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new p.Vector2(r,r)}return Promise.all(s)}}class Tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class Sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class _c{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(t.sheenColor=new p.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){const r=n.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,p.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class bc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class xc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const r=n.attenuationColor||[1,1,1];return t.attenuationColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),Promise.all(s)}}class Ac{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class Mc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const r=n.specularColorFactor||[1,1,1];return t.specularColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,p.SRGBColorSpace)),Promise.all(s)}}class Rc{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(s)}}class vc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class Cc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class Ic{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,o.source,c)}}class Lc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,o.source,c)}}class lr{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const c=s.byteOffset||0,u=s.byteLength||0,d=s.count,h=s.byteStride,f=new Uint8Array(a,c,u);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(d,h,f,s.mode,s.filter).then(function(m){return m.buffer}):o.ready.then(function(){const m=new ArrayBuffer(d*h);return o.decodeGltfBuffer(new Uint8Array(m),d,h,f,s.mode,s.filter),m})})}else return null}}class Pc{constructor(e){this.name=le.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const u of s.primitives)if(u.mode!==st.TRIANGLES&&u.mode!==st.TRIANGLE_STRIP&&u.mode!==st.TRIANGLE_FAN&&u.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],c={};for(const u in o)a.push(this.parser.getDependency("accessor",o[u]).then(d=>(c[u]=d,c[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(u=>{const d=u.pop(),h=d.isGroup?d.children:[d],f=u[0].count,m=[];for(const w of h){const b=new p.Matrix4,_=new p.Vector3,A=new p.Quaternion,T=new p.Vector3(1,1,1),x=new p.InstancedMesh(w.geometry,w.material,f);for(let S=0;S<f;S++)c.TRANSLATION&&_.fromBufferAttribute(c.TRANSLATION,S),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,S),c.SCALE&&T.fromBufferAttribute(c.SCALE,S),x.setMatrixAt(S,b.compose(_,A,T));for(const S in c)if(S==="_COLOR_0"){const M=c[S];x.instanceColor=new p.InstancedBufferAttribute(M.array,M.itemSize,M.normalized)}else S!=="TRANSLATION"&&S!=="ROTATION"&&S!=="SCALE"&&w.geometry.setAttribute(S,c[S]);p.Object3D.prototype.copy.call(x,w),this.parser.assignFinalMaterial(x),m.push(x)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const Ur="glTF",wn=12,hr={JSON:1313821514,BIN:5130562};class Oc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,wn),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Ur)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-wn,r=new DataView(e,wn);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const c=r.getUint32(o,!0);if(o+=4,c===hr.JSON){const u=new Uint8Array(e,wn+o,a);this.content=n.decode(u)}else if(c===hr.BIN){const u=wn+o;this.body=e.slice(u,u+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Dc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},u={};for(const d in o){const h=hi[d]||d.toLowerCase();a[h]=o[d]}for(const d in e.attributes){const h=hi[d]||d.toLowerCase();if(o[d]!==void 0){const f=n.accessors[e.attributes[d]],m=rn[f.componentType];u[h]=m.name,c[h]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(d){return new Promise(function(h,f){s.decodeDracoFile(d,function(m){for(const w in m.attributes){const b=m.attributes[w],_=c[w];_!==void 0&&(b.normalized=_)}h(m)},a,u,p.LinearSRGBColorSpace,f)})})}}class Nc{constructor(){this.name=le.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class kc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Vr extends p.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let o=0;o!==s;o++)t[o]=n[r+o];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,u=a*3,d=s-t,h=(n-t)/d,f=h*h,m=f*h,w=e*u,b=w-u,_=-2*m+3*f,A=m-f,T=1-_,x=A-f+h;for(let S=0;S!==a;S++){const M=o[b+S+a],P=o[b+S+c]*d,I=o[w+S+a],C=o[w+S]*d;r[S]=T*M+x*P+_*I+A*C}return r}}const Fc=new p.Quaternion;class Bc extends Vr{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return Fc.fromArray(r).normalize().toArray(r),r}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},rn={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},ur={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},dr={33071:p.ClampToEdgeWrapping,33648:p.MirroredRepeatWrapping,10497:p.RepeatWrapping},zs={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},hi={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Rt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},zc={CUBICSPLINE:void 0,LINEAR:p.InterpolateLinear,STEP:p.InterpolateDiscrete},Us={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Uc(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new p.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:p.FrontSide})),i.DefaultMaterial}function Bt(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function yt(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Vc(i,e,t){let n=!1,s=!1,r=!1;for(let u=0,d=e.length;u<d;u++){const h=e[u];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(i);const o=[],a=[],c=[];for(let u=0,d=e.length;u<d;u++){const h=e[u];if(n){const f=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):i.attributes.position;o.push(f)}if(s){const f=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):i.attributes.normal;a.push(f)}if(r){const f=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):i.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(u){const d=u[0],h=u[1],f=u[2];return n&&(i.morphAttributes.position=d),s&&(i.morphAttributes.normal=h),r&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function Hc(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Gc(i){let e;const t=i.extensions&&i.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Vs(t.attributes):e=i.indices+":"+Vs(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Vs(i.targets[n]);return e}function Vs(i){let e="";const t=Object.keys(i).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+i[t[n]]+";";return e}function ui(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function jc(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Wc=new p.Matrix4;class Zc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new mc,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&o<98?this.textureLoader=new p.TextureLoader(this.options.manager):this.textureLoader=new p.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new p.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return Bt(r,a,s),yt(a,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(const c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const o=t[s].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(o,a)=>{const c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(const[u,d]of o.children.entries())r(d,a.children[u])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){n.load(p.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=zs[s.type],a=rn[s.componentType],c=s.normalized===!0,u=new a(s.count*o);return Promise.resolve(new p.BufferAttribute(u,o,c))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],c=zs[s.type],u=rn[s.componentType],d=u.BYTES_PER_ELEMENT,h=d*c,f=s.byteOffset||0,m=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,w=s.normalized===!0;let b,_;if(m&&m!==h){const A=Math.floor(f/m),T="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let x=t.cache.get(T);x||(b=new u(a,A*m,s.count*m/d),x=new p.InterleavedBuffer(b,m/d),t.cache.add(T,x)),_=new p.InterleavedBufferAttribute(x,c,f%m/d,w)}else a===null?b=new u(s.count*c):b=new u(a,f,s.count*c),_=new p.BufferAttribute(b,c,w);if(s.sparse!==void 0){const A=zs.SCALAR,T=rn[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,S=s.sparse.values.byteOffset||0,M=new T(o[1],x,s.sparse.count*A),P=new u(o[2],S,s.sparse.count*c);a!==null&&(_=new p.BufferAttribute(_.array.slice(),_.itemSize,_.normalized)),_.normalized=!1;for(let I=0,C=M.length;I<C;I++){const D=M[I];if(_.setX(D,P[I*c]),c>=2&&_.setY(D,P[I*c+1]),c>=3&&_.setZ(D,P[I*c+2]),c>=4&&_.setW(D,P[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=w}return _})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,o=t.images[r];let a=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){const s=this,r=this.json,o=r.textures[e],a=r.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const u=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=o.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return d.magFilter=ur[f.magFilter]||p.LinearFilter,d.minFilter=ur[f.minFilter]||p.LinearMipmapLinearFilter,d.wrapS=dr[f.wrapS]||p.RepeatWrapping,d.wrapT=dr[f.wrapT]||p.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==p.NearestFilter&&d.minFilter!==p.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=u,u}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const o=s.images[e],a=self.URL||self.webkitURL;let c=o.uri||"",u=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(h){u=!0;const f=new Blob([h],{type:o.mimeType});return c=a.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(h){return new Promise(function(f,m){let w=f;t.isImageBitmapLoader===!0&&(w=function(b){const _=new p.Texture(b);_.needsUpdate=!0,f(_)}),t.load(p.LoaderUtils.resolveURL(h,r.path),w,void 0,m)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),yt(h,o),h.userData.mimeType=o.mimeType||jc(o.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=r.associations.get(o);o=r.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,c)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.PointsMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.LineBasicMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(s||r||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),r&&(c.vertexColors=!0),o&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return p.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let o;const a={},c=r.extensions||{},u=[];if(c[le.KHR_MATERIALS_UNLIT]){const h=s[le.KHR_MATERIALS_UNLIT];o=h.getMaterialType(),u.push(h.extendParams(a,r,t))}else{const h=r.pbrMetallicRoughness||{};if(a.color=new p.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const f=h.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],p.LinearSRGBColorSpace),a.opacity=f[3]}h.baseColorTexture!==void 0&&u.push(t.assignTexture(a,"map",h.baseColorTexture,p.SRGBColorSpace)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),u.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=p.DoubleSide);const d=r.alphaMode||Us.OPAQUE;if(d===Us.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Us.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new p.Vector2(1,1),r.normalTexture.scale!==void 0)){const h=r.normalTexture.scale;a.normalScale.set(h,h)}if(r.occlusionTexture!==void 0&&o!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==p.MeshBasicMaterial){const h=r.emissiveFactor;a.emissive=new p.Color().setRGB(h[0],h[1],h[2],p.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==p.MeshBasicMaterial&&u.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,p.SRGBColorSpace)),Promise.all(u).then(function(){const h=new o(a);return r.name&&(h.name=r.name),yt(h,r),t.associations.set(h,{materials:e}),r.extensions&&Bt(s,h,r),h})}createUniqueName(e){const t=p.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return fr(c,a,t)})}const o=[];for(let a=0,c=e.length;a<c;a++){const u=e[a],d=Gc(u),h=s[d];if(h)o.push(h.promise);else{let f;u.extensions&&u.extensions[le.KHR_DRACO_MESH_COMPRESSION]?f=r(u):f=fr(new p.BufferGeometry,u,t),s[d]={primitive:u,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],o=r.primitives,a=[];for(let c=0,u=o.length;c<u;c++){const d=o[c].material===void 0?Uc(this.cache):this.getDependency("material",o[c].material);a.push(d)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){const u=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let m=0,w=d.length;m<w;m++){const b=d[m],_=o[m];let A;const T=u[m];if(_.mode===st.TRIANGLES||_.mode===st.TRIANGLE_STRIP||_.mode===st.TRIANGLE_FAN||_.mode===void 0)A=r.isSkinnedMesh===!0?new p.SkinnedMesh(b,T):new p.Mesh(b,T),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),_.mode===st.TRIANGLE_STRIP?A.geometry=cr(A.geometry,p.TriangleStripDrawMode):_.mode===st.TRIANGLE_FAN&&(A.geometry=cr(A.geometry,p.TriangleFanDrawMode));else if(_.mode===st.LINES)A=new p.LineSegments(b,T);else if(_.mode===st.LINE_STRIP)A=new p.Line(b,T);else if(_.mode===st.LINE_LOOP)A=new p.LineLoop(b,T);else if(_.mode===st.POINTS)A=new p.Points(b,T);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+_.mode);Object.keys(A.geometry.morphAttributes).length>0&&Hc(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),yt(A,r),_.extensions&&Bt(s,A,_),t.assignFinalMaterial(A),h.push(A)}for(let m=0,w=h.length;m<w;m++)t.associations.set(h[m],{meshes:e,primitives:m});if(h.length===1)return r.extensions&&Bt(s,h[0],r),h[0];const f=new p.Group;r.extensions&&Bt(s,f,r),t.associations.set(f,{meshes:e});for(let m=0,w=h.length;m<w;m++)f.add(h[m]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new p.PerspectiveCamera(p.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new p.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),yt(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),o=s,a=[],c=[];for(let u=0,d=o.length;u<d;u++){const h=o[u];if(h){a.push(h);const f=new p.Matrix4;r!==null&&f.fromArray(r.array,u*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[u])}return new p.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,o=[],a=[],c=[],u=[],d=[];for(let h=0,f=s.channels.length;h<f;h++){const m=s.channels[h],w=s.samplers[m.sampler],b=m.target,_=b.node,A=s.parameters!==void 0?s.parameters[w.input]:w.input,T=s.parameters!==void 0?s.parameters[w.output]:w.output;b.node!==void 0&&(o.push(this.getDependency("node",_)),a.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",T)),u.push(w),d.push(b))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(h){const f=h[0],m=h[1],w=h[2],b=h[3],_=h[4],A=[];for(let x=0,S=f.length;x<S;x++){const M=f[x],P=m[x],I=w[x],C=b[x],D=_[x];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();const L=n._createAnimationTracks(M,P,I,C,D);if(L)for(let k=0;k<L.length;k++)A.push(L[k])}const T=new p.AnimationClip(r,void 0,A);return yt(T,s),T})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const o=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,u=s.weights.length;c<u;c++)a.morphTargetInfluences[c]=s.weights[c]}),o})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),o=[],a=s.children||[];for(let u=0,d=a.length;u<d;u++)o.push(n.getDependency("node",a[u]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),c]).then(function(u){const d=u[0],h=u[1],f=u[2];f!==null&&d.traverse(function(m){m.isSkinnedMesh&&m.bind(f,Wc)});for(let m=0,w=h.length;m<w;m++)d.add(h[m]);if(d.userData.pivot!==void 0&&h.length>0){const m=d.userData.pivot,w=h[0];d.pivot=new p.Vector3().fromArray(m),d.position.x-=m[0],d.position.y-=m[1],d.position.z-=m[2],w.position.set(0,0,0),delete d.userData.pivot}return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],o=r.name?s.createUniqueName(r.name):"",a=[],c=s._invokeOne(function(u){return u.createNodeMesh&&u.createNodeMesh(e)});return c&&a.push(c),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(u){return s._getNodeRef(s.cameraCache,r.camera,u)})),s._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(e)}).forEach(function(u){a.push(u)}),this.nodeCache[e]=Promise.all(a).then(function(u){let d;if(r.isBone===!0?d=new p.Bone:u.length>1?d=new p.Group:u.length===1?d=u[0]:d=new p.Object3D,d!==u[0])for(let h=0,f=u.length;h<f;h++)d.add(u[h]);if(r.name&&(d.userData.name=r.name,d.name=o),yt(d,r),r.extensions&&Bt(n,d,r),r.matrix!==void 0){const h=new p.Matrix4;h.fromArray(r.matrix),d.applyMatrix4(h)}else r.translation!==void 0&&d.position.fromArray(r.translation),r.rotation!==void 0&&d.quaternion.fromArray(r.rotation),r.scale!==void 0&&d.scale.fromArray(r.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const h=s.associations.get(d);s.associations.set(d,{...h})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new p.Group;n.name&&(r.name=s.createUniqueName(n.name)),yt(r,n),n.extensions&&Bt(t,r,n);const o=n.nodes||[],a=[];for(let c=0,u=o.length;c<u;c++)a.push(s.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let d=0,h=c.length;d<h;d++){const f=c[d];f.parent!==null?r.add(fc(f)):r.add(f)}const u=d=>{const h=new Map;for(const[f,m]of s.associations)(f instanceof p.Material||f instanceof p.Texture)&&h.set(f,m);return d.traverse(f=>{const m=s.associations.get(f);m!=null&&h.set(f,m)}),h};return s.associations=u(r),r})}_createAnimationTracks(e,t,n,s,r){const o=[],a=e.name?e.name:e.uuid,c=[];function u(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}Rt[r.path]===Rt.weights?(u(e),e.isGroup&&e.children.forEach(u)):c.push(a);let d;switch(Rt[r.path]){case Rt.weights:d=p.NumberKeyframeTrack;break;case Rt.rotation:d=p.QuaternionKeyframeTrack;break;case Rt.translation:case Rt.scale:d=p.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:d=p.NumberKeyframeTrack;break;case 2:case 3:default:d=p.VectorKeyframeTrack;break}break}const h=s.interpolation!==void 0?zc[s.interpolation]:p.InterpolateLinear,f=this._getArrayFromAccessor(n);for(let m=0,w=c.length;m<w;m++){const b=new d(c[m]+"."+Rt[r.path],t.array,f,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),o.push(b)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=ui(t.constructor),s=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof p.QuaternionKeyframeTrack?Bc:Vr;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Kc(i,e,t){const n=e.attributes,s=new p.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,u=a.max;if(c!==void 0&&u!==void 0){if(s.set(new p.Vector3(c[0],c[1],c[2]),new p.Vector3(u[0],u[1],u[2])),a.normalized){const d=ui(rn[a.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const a=new p.Vector3,c=new p.Vector3;for(let u=0,d=r.length;u<d;u++){const h=r[u];if(h.POSITION!==void 0){const f=t.json.accessors[h.POSITION],m=f.min,w=f.max;if(m!==void 0&&w!==void 0){if(c.setX(Math.max(Math.abs(m[0]),Math.abs(w[0]))),c.setY(Math.max(Math.abs(m[1]),Math.abs(w[1]))),c.setZ(Math.max(Math.abs(m[2]),Math.abs(w[2]))),f.normalized){const b=ui(rn[f.componentType]);c.multiplyScalar(b)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}i.boundingBox=s;const o=new p.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=o}function fr(i,e,t){const n=e.attributes,s=[];function r(o,a){return t.getDependency("accessor",o).then(function(c){i.setAttribute(a,c)})}for(const o in n){const a=hi[o]||o.toLowerCase();a in i.attributes||s.push(r(n[o],a))}if(e.indices!==void 0&&!i.index){const o=t.getDependency("accessor",e.indices).then(function(a){i.setIndex(a)});s.push(o)}return p.ColorManagement.workingColorSpace!==p.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${p.ColorManagement.workingColorSpace}" not supported.`),yt(i,e),Kc(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?Vc(i,e.targets,t):i})}const Xc=E.REVISION.replace(/\D/g,""),Hr=`https://cdn.jsdelivr.net/npm/three@0.${Xc}/examples/jsm/libs`,Yc=`${Hr}/draco/`,qc=`${Hr}/basis/`;class $c{constructor(e={}){this.loadingManager=new E.LoadingManager,this.loader=new pc(this.loadingManager),this.config=e}ensureDecoders(){return this.decodersReady||(this.decodersReady=this.configureDecoders()),this.decodersReady}async configureDecoders(){const e=this.config,t=[];(e.draco??!0)&&t.push(this.configureDraco(e)),(e.ktx2??!0)&&t.push(this.configureKtx2(e)),(e.meshopt??!0)&&t.push(this.configureMeshopt());const n=await Promise.allSettled(t);for(const s of n)s.status==="rejected"&&console.warn("softbox: a compression decoder failed to initialize; compressed assets using it may not load.",s.reason)}async configureDraco(e){const{DRACOLoader:t}=await import("three/examples/jsm/loaders/DRACOLoader.js"),n=new t(this.loadingManager);n.setDecoderPath(e.dracoDecoderPath??Yc),this.dracoLoader=n,this.loader.setDRACOLoader(n)}async configureKtx2(e){const{KTX2Loader:t}=await import("three/examples/jsm/loaders/KTX2Loader.js"),n=new t(this.loadingManager);n.setTranscoderPath(e.ktx2TranscoderPath??qc),e.renderer&&n.detectSupport(e.renderer),this.ktx2Loader=n,this.loader.setKTX2Loader(n)}async configureMeshopt(){const e=await import("three/examples/jsm/libs/meshopt_decoder.module.js");this.loader.setMeshoptDecoder(e.MeshoptDecoder)}async load(e,t){try{return await this.ensureDecoders(),new Promise(n=>{this.loader.load(e,s=>{var o;(this.config.bvh??!0)&&Fr(s.scene),s.scene.animations=s.animations;const r={scene:new De(s.scene),animations:this.convertAnimations(s.animations),cameras:(o=s.cameras)==null?void 0:o.map(a=>{const c=a instanceof E.PerspectiveCamera,u=a instanceof E.OrthographicCamera;return{name:a.name,type:a.type,fov:c?a.fov:void 0,aspect:c?a.aspect:void 0,near:c||u?a.near:.1,far:c||u?a.far:1e3}}),userData:s.userData};n(F.ok(r))},s=>{s.total>0&&(t==null||t(s.loaded,s.total))},s=>{n(F.err(new K("Failed to load GLTF model",Y.MODEL_LOAD_FAILED,{url:e,originalError:s})))})})}catch(n){return F.err(new K("Failed to initiate model loading",Y.MODEL_LOAD_FAILED,{url:e,originalError:n}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}dispose(){var e,t;(e=this.dracoLoader)==null||e.dispose(),(t=this.ktx2Loader)==null||t.dispose()}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(n=>({name:n.name,type:this.getTrackType(n),times:n.times,values:n.values}))}))}getTrackType(e){return e instanceof E.VectorKeyframeTrack?"vector":e instanceof E.QuaternionKeyframeTrack?"quaternion":e instanceof E.NumberKeyframeTrack?"number":e instanceof E.BooleanKeyframeTrack?"boolean":"number"}}class pr{static createLoader(e,t={}){var s;const n=(s=e.split(".").pop())==null?void 0:s.toLowerCase();switch(n){case"gltf":case"glb":return new $c(t);default:throw new K(`Unsupported file format: ${n}`,Y.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const mr={type:"change"},bi={type:"start"},Gr={type:"end"},rs=new p.Ray,gr=new p.Plane,Qc=Math.cos(70*p.MathUtils.DEG2RAD),Pe=new p.Vector3,$e=2*Math.PI,Ee={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Hs=1e-6;class jr extends p.Controls{constructor(e,t=null){super(e,t),this.state=Ee.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=el.bind(this),this._onPointerDown=Jc.bind(this),this._onPointerUp=tl.bind(this),this._onContextMenu=cl.bind(this),this._onMouseWheel=il.bind(this),this._onKeyDown=rl.bind(this),this._onTouchStart=ol.bind(this),this._onTouchMove=al.bind(this),this._onMouseDown=nl.bind(this),this._onMouseMove=sl.bind(this),this._interceptControlDown=ll.bind(this),this._interceptControlUp=hl.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(mr),this.update(),this.state=Ee.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Pe.copy(t).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===Ee.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=$e:n>Math.PI&&(n-=$e),s<-Math.PI?s+=$e:s>Math.PI&&(s-=$e),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Pe.setFromSpherical(this._spherical),Pe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Pe),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Pe.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const u=new p.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).add(a),this.object.updateMatrixWorld(),o=Pe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(rs.origin.copy(this.object.position),rs.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(rs.direction))<Qc?this.object.lookAt(this.target):(gr.setFromNormalAndCoplanarPoint(this.object.up,this.target),rs.intersectPlane(gr,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Hs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Hs||this._lastTargetPosition.distanceToSquared(this.target)>Hs?(this.dispatchEvent(mr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?$e/60*this.autoRotateSpeed*e:$e/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Pe.setFromMatrixColumn(t,0),Pe.multiplyScalar(-e),this._panOffset.add(Pe)}_panUp(e,t){this.screenSpacePanning===!0?Pe.setFromMatrixColumn(t,1):(Pe.setFromMatrixColumn(t,0),Pe.crossVectors(this.object.up,Pe)),Pe.multiplyScalar(e),this._panOffset.add(Pe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Pe.copy(s).sub(this.target);let r=Pe.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function Jc(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function el(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function tl(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Gr),this.state=Ee.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function nl(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Ee.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ee.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ee.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ee.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ee.PAN}break;default:this.state=Ee.NONE}this.state!==Ee.NONE&&this.dispatchEvent(bi)}function sl(i){switch(this.state){case Ee.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Ee.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Ee.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function il(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ee.NONE||(i.preventDefault(),this.dispatchEvent(bi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Gr))}function rl(i){this.enabled!==!1&&this._handleKeyDown(i)}function ol(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Ee.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Ee.TOUCH_PAN;break;default:this.state=Ee.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Ee.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Ee.TOUCH_DOLLY_ROTATE;break;default:this.state=Ee.NONE}break;default:this.state=Ee.NONE}this.state!==Ee.NONE&&this.dispatchEvent(bi)}function al(i){switch(this._trackPointer(i),this.state){case Ee.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Ee.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Ee.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Ee.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Ee.NONE}}function cl(i){this.enabled!==!1&&i.preventDefault()}function ll(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function hl(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Gs=new p.Plane,os=new p.Raycaster,Qt=new p.Vector2,js=new p.Vector3;class ul extends jr{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE},this._panWorldStart=new p.Vector3}_handleMouseDownPan(e){if(super._handleMouseDownPan(e),this._panOffset.set(0,0,0),this.screenSpacePanning===!0)return;Gs.setFromNormalAndCoplanarPoint(this.object.up,this.target);const n=this.domElement.getBoundingClientRect();Qt.x=(e.clientX-n.left)/n.width*2-1,Qt.y=-((e.clientY-n.top)/n.height)*2+1,os.setFromCamera(Qt,this.object),os.ray.intersectPlane(Gs,this._panWorldStart)}_handleMouseMovePan(e){if(this.screenSpacePanning===!0){super._handleMouseMovePan(e);return}const n=this.domElement.getBoundingClientRect();Qt.x=(e.clientX-n.left)/n.width*2-1,Qt.y=-((e.clientY-n.top)/n.height)*2+1,os.setFromCamera(Qt,this.object),os.ray.intersectPlane(Gs,js)&&(js.sub(this._panWorldStart),this._panOffset.copy(js).negate(),this.update())}}class Wr{constructor(e){this.controls=e,this.targetAdapter=Pt.fromThreeVector(e.target)}get enabled(){return this.controls.enabled}set enabled(e){this.controls.enabled=e}get enableDamping(){return this.controls.enableDamping}set enableDamping(e){this.controls.enableDamping=e}get dampingFactor(){return this.controls.dampingFactor}set dampingFactor(e){this.controls.dampingFactor=e}get enableZoom(){return this.controls.enableZoom}set enableZoom(e){this.controls.enableZoom=e}get enableRotate(){return this.controls.enableRotate}set enableRotate(e){this.controls.enableRotate=e}get enablePan(){return this.controls.enablePan}set enablePan(e){this.controls.enablePan=e}get zoomSpeed(){return this.controls.zoomSpeed}set zoomSpeed(e){this.controls.zoomSpeed=e}get minDistance(){return this.controls.minDistance}set minDistance(e){this.controls.minDistance=e}get maxDistance(){return this.controls.maxDistance}set maxDistance(e){this.controls.maxDistance=e}get rotateSpeed(){return this.controls.rotateSpeed}set rotateSpeed(e){this.controls.rotateSpeed=e}get minPolarAngle(){return this.controls.minPolarAngle}set minPolarAngle(e){this.controls.minPolarAngle=e}get maxPolarAngle(){return this.controls.maxPolarAngle}set maxPolarAngle(e){this.controls.maxPolarAngle=e}get minAzimuthAngle(){return this.controls.minAzimuthAngle}set minAzimuthAngle(e){this.controls.minAzimuthAngle=e}get maxAzimuthAngle(){return this.controls.maxAzimuthAngle}set maxAzimuthAngle(e){this.controls.maxAzimuthAngle=e}get panSpeed(){return this.controls.panSpeed}set panSpeed(e){this.controls.panSpeed=e}get screenSpacePanning(){return this.controls.screenSpacePanning}set screenSpacePanning(e){this.controls.screenSpacePanning=e}get target(){return this.targetAdapter}update(){return this.controls.update()}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}get autoRotate(){return this.controls.autoRotate}set autoRotate(e){this.controls.autoRotate=e}get autoRotateSpeed(){return this.controls.autoRotateSpeed}set autoRotateSpeed(e){this.controls.autoRotateSpeed=e}getThreeControls(){return this.controls}}class dl extends Wr{constructor(e,t){super(new jr(e,t))}get type(){return"orbit"}}class fl extends Wr{constructor(e,t){const n=new ul(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Rn=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function zt(i){return Rn(i,"getThreeObject")??(i instanceof E.Object3D?i:null)}function vn(i){return Rn(i,"getThreeCamera")??(i instanceof E.Camera?i:null)}function di(i){return Rn(i,"getThreeScene")??(i instanceof E.Scene?i:null)}function Zr(i){return Rn(i,"getThreeRenderer")??(i instanceof E.WebGLRenderer?i:null)}function xi(i){return Rn(i,"getThreeControls")}const fi="contact-shadow-baked",on="contact-shadow-live",Ai="softboxContactShadowHelper",yr=Math.PI*(3-Math.sqrt(5)),xe=class xe{constructor(e){this.explicitPasses=e==null?void 0:e.passes}bake(e){const{renderer:t,scene:n,object:s,light:r}=e;if(t.getContext().isContextLost()){this.leaveLiveCatcherInCharge(n);return}const o=this.measureBakeRegion(s);if(!o)return;const a=n.getObjectByName(on);(a==null?void 0:a.geometry)instanceof E.CircleGeometry&&(o.halfExtent=Math.min(o.halfExtent,a.geometry.parameters.radius));const c=new E.WebGLRenderTarget(xe.ACCUMULATION_TEXTURE_SIZE,xe.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?E.HalfFloatType:E.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),u=new E.CircleGeometry(o.halfExtent,64);if(this.accumulateShadowPasses(t,s,r,o,c,u),t.getContext().isContextLost()){c.dispose(),u.dispose(),this.leaveLiveCatcherInCharge(n),console.warn("Contact-shadow bake aborted: WebGL context was lost mid-bake");return}this.installBakedMesh(n,o,c,u)}leaveLiveCatcherInCharge(e){this.evictBakedMesh(e);const t=e.getObjectByName(on);t&&(t.visible=!0)}evictBakedMesh(e){const t=e.getObjectByName(fi);t&&(e.remove(t),xs(t))}measureBakeRegion(e){const t=new E.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new E.Vector3),s=t.getCenter(new E.Vector3),o=Math.max(Math.max(n.x,n.z)*1.6+n.y,.05);return{center:s,halfExtent:o,objectHeight:n.y}}accumulateShadowPasses(e,t,n,s,r,o){const a=new E.Scene,c=t.parent;a.add(t);const u=this.disableColorWrite(t),d=this.createBakeLight(n);a.add(d),a.add(d.target);const h=new E.ShadowMaterial({transparent:!0,opacity:0,depthWrite:!1});h.blending=E.CustomBlending,h.blendEquation=E.AddEquation,h.blendSrc=E.OneFactor,h.blendDst=E.OneFactor;const f=new E.Mesh(o,h);f.rotation.x=-Math.PI/2,f.position.set(s.center.x,0,s.center.z),f.receiveShadow=!0,a.add(f);const m=this.createBakeCamera(s);a.add(m);const w=e.getRenderTarget(),b=e.autoClear,_=e.getClearColor(new E.Color),A=e.getClearAlpha(),T=e.shadowMap.autoUpdate;try{e.shadowMap.autoUpdate=!0,e.setRenderTarget(r),e.setClearColor(0,0),e.clear(!0,!1,!1),e.autoClear=!1;const x=this.explicitPasses??this.measureAffordablePasses(e,a,m,n,d,r);h.opacity=1/x;for(const S of this.sampleLightPositions(n,x))d.position.copy(S),e.render(a,m)}finally{e.autoClear=b,e.setClearColor(_,A),e.setRenderTarget(w),e.shadowMap.autoUpdate=T,this.restoreColorWrite(u),c?c.add(t):a.remove(t),d.dispose(),h.dispose()}}measureAffordablePasses(e,t,n,s,r,o){r.position.copy(s.position),e.render(t,n),this.awaitGpuIdle(e,o);const a=performance.now();e.render(t,n),this.awaitGpuIdle(e,o);const c=Math.max(performance.now()-a,.01);return E.MathUtils.clamp(Math.round(xe.BAKE_BUDGET_MS/c),xe.MIN_PASSES,xe.MAX_PASSES)}awaitGpuIdle(e,t){if(!e.capabilities.textureTypeReadable(t.texture.type))return;const n=t.texture.type===E.HalfFloatType?new Uint16Array(4):new Uint8Array(4);e.readRenderTargetPixels(t,0,0,1,1,n)}createBakeLight(e){const t=new E.DirectionalLight(16777215,1);t.castShadow=!0,t.shadow.mapSize.set(xe.BAKE_SHADOW_MAP_SIZE,xe.BAKE_SHADOW_MAP_SIZE),t.shadow.bias=e.shadow.bias,t.shadow.normalBias=e.shadow.normalBias,t.shadow.radius=4;const n=e.shadow.camera,s=t.shadow.camera;return s.left=n.left,s.right=n.right,s.top=n.top,s.bottom=n.bottom,s.near=n.near,s.far=n.far,s.updateProjectionMatrix(),t}createBakeCamera(e){const t=new E.OrthographicCamera(-e.halfExtent,e.halfExtent,e.halfExtent,-e.halfExtent,.1,Math.max(e.objectHeight,1)*4);return t.position.set(e.center.x,Math.max(e.objectHeight,1)*2,e.center.z),t.up.set(0,0,-1),t.lookAt(e.center.x,0,e.center.z),t.updateProjectionMatrix(),t.updateMatrixWorld(!0),t}sampleLightPositions(e,t){const n=e.position.clone(),s=e.target.parent?e.target.getWorldPosition(new E.Vector3):e.target.position.clone(),r=s.clone().sub(n),o=r.length(),a=r.normalize(),c=new E.Vector3().crossVectors(a,new E.Vector3(0,1,0));c.lengthSq()<1e-6&&c.set(1,0,0),c.normalize();const u=new E.Vector3().crossVectors(a,c),d=Math.round(t*xe.AMBIENT_RATIO),h=t-d,f=E.MathUtils.degToRad(xe.LIGHT_APERTURE_DEGREES),m=Math.tan(f/2)*o,w=[];for(let A=0;A<h;A++){const T=m*Math.sqrt((A+.5)/h),x=A*yr;w.push(n.clone().addScaledVector(c,T*Math.cos(x)).addScaledVector(u,T*Math.sin(x)))}const b=Math.sin(E.MathUtils.degToRad(xe.AMBIENT_MIN_ELEVATION_DEGREES)),_=.98;for(let A=0;A<d;A++){const T=Math.sqrt((A+.5)/d),x=b+(_-b)*T,S=Math.sqrt(1-x*x),M=A*yr;w.push(new E.Vector3(S*Math.cos(M),x,S*Math.sin(M)).multiplyScalar(o).add(s))}return w}installBakedMesh(e,t,n,s){this.evictBakedMesh(e);const r=new E.MeshBasicMaterial({map:n.texture,transparent:!0,opacity:xe.SHADOW_STRENGTH,depthWrite:!1,toneMapped:!1});r.onBeforeCompile=u=>{u.fragmentShader=u.fragmentShader.replace("#include <map_fragment>",`#include <map_fragment>
|
|
2
|
-
diffuseColor.a = pow(diffuseColor.a, 0.75);`)},r.customProgramCacheKey=()=>"contact-shadow-alpha-gamma",r.addEventListener("dispose",()=>n.dispose());const o=new E.Mesh(s,r);o.name=fi,o.userData[Ai]=!0,o.rotation.x=-Math.PI/2;const a=E.MathUtils.clamp(t.objectHeight*.0025,2e-4,.01);o.position.set(t.center.x,a,t.center.z),o.userData.renderTarget=n,e.add(o);const c=e.getObjectByName(on);c&&(c.visible=!1)}disableColorWrite(e){const t=new Map;return e.traverse(n=>{const s=n;if(!s.isMesh)return;const r=Array.isArray(s.material)?s.material:[s.material];for(const o of r)o&&!t.has(o)&&(t.set(o,o.colorWrite),o.colorWrite=!1)}),t}restoreColorWrite(e){e.forEach((t,n)=>{n.colorWrite=t})}};xe.AMBIENT_RATIO=.45,xe.LIGHT_APERTURE_DEGREES=9,xe.AMBIENT_MIN_ELEVATION_DEGREES=55,xe.ACCUMULATION_TEXTURE_SIZE=1024,xe.BAKE_SHADOW_MAP_SIZE=1024,xe.SHADOW_STRENGTH=.85,xe.BAKE_BUDGET_MS=100,xe.MIN_PASSES=24,xe.MAX_PASSES=96;let pi=xe;const bn=class bn{static getHeight(e){return e*this.HEIGHT_RATIO}static getBevelSize(e){return e*this.BEVEL_RATIO}static getBevelThickness(e){return this.getBevelSize(e)}static getBaseSize(e){return e+this.getBevelSize(e)+this.getBevelThickness(e)}static getGapFactor(){return this.GAP_FACTOR}static getGridSpacing(e){const t=this.getBaseSize(e),n=this.getGapFactor();return{width:Math.sqrt(3)*t*n,height:2*t*n}}static getYPosition(e){return-this.getBevelSize(e)}};bn.HEIGHT_RATIO=.075,bn.BEVEL_RATIO=.04,bn.GAP_FACTOR=1.05;let Ut=bn;var _t=(i=>(i.SQUARE_WIRE="square_wire",i.HEXAGONAL_WIRE="hexagonal_wire",i.HEXAGONAL_GLASS="hexagonal_glass",i.STONE_TILES="stone_tiles",i.CUSTOM="custom",i))(_t||{});class pl{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new E.Color(e.color||8947848),r=new E.Color(e.centerLineColor||e.color||4473924),o=new E.GridHelper(t,n,r,s);if(e.opacity!==void 0&&e.opacity<1){const a=o.material;a.transparent=!0,a.opacity=e.opacity}return o}dispose(){}}class ml{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new E.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)??Math.floor(e.divisions/2),s=e.size/Math.max(1,n*2),r=new E.Color(e.color||8947848),o=e.opacity||.4,a=new E.LineBasicMaterial({color:r,transparent:!0,opacity:o}),c=s*Math.sqrt(3),u=s*2;for(let h=-n;h<=n;h++){const f=Math.max(-n,-h-n),m=Math.min(n,-h+n);for(let w=f;w<=m;w++){const b=c*(h+w/2),_=u*.75*w,A=[],T=Math.PI*2/6;for(let M=0;M<=6;M++){const P=M*T+Math.PI/6,I=b+s*Math.cos(P),C=_+s*Math.sin(P);A.push(new E.Vector3(I,0,C))}const x=new E.BufferGeometry().setFromPoints(A),S=new E.Line(x,a);t.add(S)}}return t}dispose(){}}class gl{constructor(e,t,n,s={}){this.position=e,this.size=t,this.color=n,this.materialOptions=s,this.height=Ut.getHeight(this.size),this.bevel=Ut.getBevelSize(this.size)}createGeometry(){const e=new E.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let o=0;o<6;o++){const a=t*Math.cos(o*n),c=t*Math.sin(o*n);o===0?e.moveTo(a,c):e.lineTo(a,c)}e.closePath();const s={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:2},r=new E.ExtrudeGeometry(e,s);return r.rotateZ(Math.PI/6),r.rotateX(Math.PI/2),r.translate(this.position.x,this.position.y,this.position.z),r}createMaterial(){const{metalness:e=0,roughness:t=.15,transmission:n=1,thickness:s=.4,ior:r=1.5}=this.materialOptions,o=n>0;return new E.MeshPhysicalMaterial({color:new E.Color(this.color),metalness:e,roughness:t,transparent:o,transmission:n,thickness:s,ior:r,opacity:1,clearcoat:o?1:0,clearcoatRoughness:.05,sheen:o?1:0,sheenColor:new E.Color(16777215),envMapIntensity:1})}}function yl(i,e){var d;const t=i.getIndex()?i.toNonIndexed():i,n=t.getAttribute("position").array,s=t.getAttribute("normal").array,r=(d=t.getAttribute("uv"))==null?void 0:d.array,o=new Float32Array(n.length*e.length),a=new Float32Array(s.length*e.length),c=r?new Float32Array(r.length*e.length):void 0;e.forEach((h,f)=>{const m=f*n.length;o.set(n,m);for(let w=m;w<m+n.length;w+=3)o[w]+=h.x,o[w+1]+=h.y,o[w+2]+=h.z;a.set(s,f*s.length),c&&r&&c.set(r,f*r.length)});const u=new E.BufferGeometry;return u.setAttribute("position",new E.BufferAttribute(o,3)),u.setAttribute("normal",new E.BufferAttribute(a,3)),c&&u.setAttribute("uv",new E.BufferAttribute(c,2)),u}class wl{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var w,b,_,A,T,x,S;const t=new E.Group,n=((w=e.styleOptions)==null?void 0:w.hexRadius)??Math.floor(e.divisions/2),s=((b=e.styleOptions)==null?void 0:b.tileSize)||1,r=String(e.color||"#ffffff"),o=Ut.getGridSpacing(s),a=o.width,c=o.height,u=new gl(new E.Vector3(0,0,0),s,r,{metalness:(_=e.styleOptions)==null?void 0:_.metalness,roughness:(A=e.styleOptions)==null?void 0:A.roughness,transmission:(T=e.styleOptions)==null?void 0:T.transmission,thickness:(x=e.styleOptions)==null?void 0:x.thickness,ior:(S=e.styleOptions)==null?void 0:S.ior}),d=u.createGeometry(),h=Ut.getYPosition(s),f=[];for(let M=-n;M<=n;M++){const P=Math.max(-n,-M-n),I=Math.min(n,-M+n);for(let C=P;C<=I;C++)f.push(new E.Vector3(a*(M+C/2),h,c*.75*C))}const m=new E.Mesh(yl(d,f),u.createMaterial());return m.receiveShadow=!0,t.add(m),d.dispose(),t.add(this.createShadowCatcher(a*(n+.5))),t}createShadowCatcher(e){const t=new E.Mesh(new E.CircleGeometry(Math.max(e,1),64),new E.ShadowMaterial({opacity:.35}));return t.name=on,t.userData[Ai]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class El{constructor(){this.name="Stone Tile Grid",this.textureLoader=new E.TextureLoader}createGrid(e){var m,w,b,_;const t=new E.Group,n=e.size,s=Math.max(1,e.divisions),r=n/s,o=r*.02,a=r-o,c=((m=e.styleOptions)==null?void 0:m.height)||r*.05,u=((w=e.styleOptions)==null?void 0:w.bevelSize)||c*.2,d=((b=e.styleOptions)==null?void 0:b.randomHeight)||!1,h=((_=e.styleOptions)==null?void 0:_.randomRotation)||!1,f=this.createStoneMaterial(e);for(let A=0;A<s;A++)for(let T=0;T<s;T++){const x=(A-s/2)*r+r/2,S=(T-s/2)*r+r/2,M=d?c*(.8+Math.random()*.4):c,P=new E.Shape,I=a/2;P.moveTo(-I,-I),P.lineTo(I,-I),P.lineTo(I,I),P.lineTo(-I,I),P.closePath();const C={depth:M,bevelEnabled:!0,bevelSize:u,bevelThickness:u,bevelSegments:2},D=new E.ExtrudeGeometry(P,C);D.rotateX(-Math.PI/2);const L=new E.Mesh(D,f);L.position.set(x,-M/2,S),L.castShadow=!0,L.receiveShadow=!0,h&&(L.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(L)}return t}createStoneMaterial(e){var o,a,c,u,d;const t=new E.Color(e.color||8421504),n=((o=e.styleOptions)==null?void 0:o.metalness)||0,s=((a=e.styleOptions)==null?void 0:a.roughness)||.8,r={color:t,metalness:n,roughness:s};if((c=e.styleOptions)!=null&&c.texture){const h=this.loadTexture(e.styleOptions.texture);h&&(r.map=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}if((u=e.styleOptions)!=null&&u.normalMap){const h=this.loadTexture(e.styleOptions.normalMap);h&&(r.normalMap=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const h=this.loadTexture(e.styleOptions.roughnessMap);h&&(r.roughnessMap=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}return new E.MeshStandardMaterial(r)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}const vi=class vi{static createGrid(e,t){const n=this.gridStyles.get(e);if(!n){console.warn(`Unknown grid type: ${e}, falling back to square wire grid`);const r=this.gridStyles.get(_t.SQUARE_WIRE);if(!r)throw new Error("Square wire grid style not found");return r.createGrid(t)}const s=n.createGrid(t);return s.name=`Grid_${e}`,s}static registerGridStyle(e,t){this.gridStyles.set(e,t)}static getAvailableTypes(){return Array.from(this.gridStyles.keys())}static disposeGridStyle(e){const t=this.gridStyles.get(e);t&&t.dispose&&t.dispose()}};vi.gridStyles=new Map([[_t.SQUARE_WIRE,new pl],[_t.HEXAGONAL_WIRE,new ml],[_t.HEXAGONAL_GLASS,new wl],[_t.STONE_TILES,new El]]);let gs=vi;const wr=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};class Tl{constructor(){this.contactShadowBaker=new pi}addHelpers(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene();if(t.grid){const s=n.userData,r=typeof t.grid=="object"?t.grid:null,o={enabled:!0,color:(r==null?void 0:r.colorGrid)||t.gridColor||"#AAAAAA",type:r!=null&&r.type?r.type:_t.HEXAGONAL_GLASS,opacity:r==null?void 0:r.opacity,styleOptions:r==null?void 0:r.styleOptions};if(n.userData={...s,gridOptions:o},r!=null&&r.size||r!=null&&r.divisions){const a=o.type||_t.HEXAGONAL_GLASS,c=r.size||10,u=r.divisions||10,d={size:c,divisions:u,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:Math.floor(u/2),tileSize:1,...o.styleOptions}},h=gs.createGrid(a,d);h.userData.isGrid=!0,h.userData.isDefaultGrid=!0,n.add(h)}}if(t.axes){const s=t.axesSize||5,r=new E.AxesHelper(s);n.add(r)}return F.ok(void 0)}catch(n){return F.err(new K("Failed to add helpers to scene",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}addDynamicGrid(e,t,n=1.2){var s;try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const r=e.getThreeScene(),o=r.userData,a=o==null?void 0:o.gridOptions;if(!(a!=null&&a.enabled))return F.ok(void 0);const c=[];r.traverse(C=>{var D,L,k;((D=C.userData)!=null&&D.isGrid||(L=C.userData)!=null&&L.isHexGrid||(k=C.userData)!=null&&k.isDefaultGrid)&&c.push(C)}),c.forEach(C=>{xs(C),r.remove(C)});let u;t instanceof De||"getThreeObject"in t&&typeof t.getThreeObject=="function"?u=t.getThreeObject():u=t;const d=new E.Box3().setFromObject(u),h=d.getSize(new E.Vector3);if(d.isEmpty()||!Number.isFinite(h.x)||!Number.isFinite(h.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),F.ok(void 0);const f=(s=a.styleOptions)==null?void 0:s.tileSize,m=typeof f=="number"?f:1,b=Ut.getGridSpacing(m).width,_=Math.max(h.x,h.z)*n+h.y;let A=_<=b?0:Math.ceil((_/b-1)/2);const T=60;A>T&&(console.warn(`Dynamic grid would need ${A} rings to cover the object; capping at ${T}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),A=T),_<b*.8?A=0:A<3&&_>b*2&&(A=3);const x=a.type||_t.HEXAGONAL_GLASS,M={size:Math.max(h.x,h.z)*n,divisions:A*2+1,color:a.color,opacity:a.opacity,styleOptions:{hexRadius:A,tileSize:m,...a.styleOptions}},P=gs.createGrid(x,M);P.userData.isGrid=!0,P.userData.isHexGrid=!0;const I=P.getObjectByName(on);return I&&(I.position.y=E.MathUtils.clamp(h.y*.0025,2e-4,.002)),r.add(P),F.ok(void 0)}catch(r){return F.err(new K("Failed to add dynamic grid",Y.SCENE_OPERATION_FAILED,{originalError:r}))}}snapObjectToFloor(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));let n;t instanceof De||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=S=>{var P,I,C;let M=S;for(;M;){if((P=M.userData)!=null&&P.isGrid||(I=M.userData)!=null&&I.isHexGrid||(C=M.userData)!=null&&C.isDefaultGrid)return!0;M=M.parent}return!1},r=e.getThreeScene();r.updateMatrixWorld(!0);const o=[];r.traverse(S=>{S.isMesh&&s(S)&&o.push(S)});const a=[];if(n.traverse(S=>{S.isMesh&&a.push(S)}),o.length===0||a.length===0)return F.ok(void 0);let c=-1/0;const u=new E.Box3;for(const S of o)u.setFromObject(S),Number.isFinite(u.max.y)&&(c=Math.max(c,u.max.y));if(!Number.isFinite(c))return F.ok(void 0);const d=new E.Box3().setFromObject(n);if(d.isEmpty()||!Number.isFinite(d.min.x)||!Number.isFinite(d.max.x))return F.ok(void 0);const h=40,f=Math.max(1,d.max.y-d.min.y),m=d.max.y+f,w=d.min.y-f,b=new E.Raycaster,_=new E.Vector3(0,-1,0),A=new E.Vector3(0,1,0);let T=1/0;const x=(S,M,P,I)=>{b.set(new E.Vector3(S,M,P),I);for(const C of b.intersectObjects(a,!1))C.point.y<T&&(T=C.point.y)};for(let S=0;S<=h;S++)for(let M=0;M<=h;M++){const P=d.min.x+(d.max.x-d.min.x)*(S/h),I=d.min.z+(d.max.z-d.min.z)*(M/h);x(P,m,I,_),x(P,w,I,A)}if(Number.isFinite(T)){const S=T-c;Math.abs(S)>1e-4&&(n.position.y-=S)}return F.ok(void 0)}catch(n){return F.err(new K("Failed to snap object to floor",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}fitShadowCameraToObject(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));let n;t instanceof De||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=new E.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return F.ok(void 0);const r=s.getSize(new E.Vector3),o=e.getThreeScene(),a=wr(o);if(!a||!a.castShadow)return F.ok(void 0);const d=Math.max(r.x,r.y,r.z,.1)*2,h=a.shadow.camera;return h.left=-d,h.right=d,h.top=d,h.bottom=-d,h.updateProjectionMatrix(),F.ok(void 0)}catch(n){return F.err(new K("Failed to fit shadow camera to object",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}bakeContactShadow(e,t,n){try{const s=di(e);if(!s)return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const r=zt(t);if(!r)return F.err(new K("Object must expose a Three.js Object3D",Y.INVALID_PARAMETER));const o=Zr(n.getInternalRenderer());if(!o||!o.shadowMap.enabled)return F.ok(void 0);const a=wr(s);return!a||!a.castShadow||this.contactShadowBaker.bake({renderer:o,scene:s,object:r,light:a}),F.ok(void 0)}catch(s){return F.err(new K("Failed to bake contact shadow",Y.SCENE_OPERATION_FAILED,{originalError:s}))}}setContactShadowMode(e,t){try{const n=di(e);if(!n)return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const s=n.getObjectByName(fi),r=n.getObjectByName(on);return t==="baked"&&!s||(s&&(s.visible=t==="baked"),r&&(r.visible=t==="live")),F.ok(void 0)}catch(n){return F.err(new K("Failed to switch contact shadow mode",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}wrapInUnitsScaleGroup(e,t){try{const n=zt(e);if(!n)return F.err(new K("Object must expose a Three.js Object3D",Y.INVALID_PARAMETER));const s=new E.Group;return s.name=$o,s.scale.setScalar(t),s.add(n),F.ok(new De(s))}catch(n){return F.err(new K("Failed to apply the units scale to the model",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene();if(t.ambient){const s=new E.Color(t.ambient.color||"#404040"),r=t.ambient.intensity??Math.PI,o=new E.AmbientLight(s,r);n.add(o)}if(t.hemisphere){const s=new E.Color(t.hemisphere.skyColor||"#ffffbb"),r=new E.Color(t.hemisphere.groundColor||"#080820"),o=t.hemisphere.intensity??1,a=new E.HemisphereLight(s,r,o);n.add(a)}if(t.directional){const s=new E.Color(t.directional.color||"#ffffff"),r=t.directional.intensity??Math.PI,o=new E.DirectionalLight(s,r);if(t.directional.position){const a=t.directional.position;if(a instanceof E.Vector3)o.position.copy(a);else if(Array.isArray(a))o.position.set(a[0],a[1],a[2]);else if(typeof a=="object"&&"x"in a&&"y"in a&&"z"in a){const c=a;o.position.set(c.x,c.y,c.z)}}else o.position.set(6,6,6);if(t.directional.castShadow&&(o.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(o.shadow.mapSize.width=a.mapSize.width,o.shadow.mapSize.height=a.mapSize.height),a.camera){const c=o.shadow.camera;a.camera.near!==void 0&&(c.near=a.camera.near),a.camera.far!==void 0&&(c.far=a.camera.far),a.camera.left!==void 0&&(c.left=a.camera.left),a.camera.right!==void 0&&(c.right=a.camera.right),a.camera.top!==void 0&&(c.top=a.camera.top),a.camera.bottom!==void 0&&(c.bottom=a.camera.bottom)}a.bias!==void 0&&(o.shadow.bias=a.bias),a.radius!==void 0&&(o.shadow.radius=a.radius)}o.target.position.set(0,0,0),n.add(o),n.add(o.target),o.shadow&&o.shadow.camera.updateProjectionMatrix()}return F.ok(void 0)}catch(n){return F.err(new K("Failed to add lighting to scene",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene(),s=document.createElement("canvas");s.width=2,s.height=512;const r=s.getContext("2d");if(!r)return F.err(new K("Failed to create canvas context",Y.SCENE_OPERATION_FAILED));const o=r.createLinearGradient(0,0,0,s.height);o.addColorStop(0,t.topColor),o.addColorStop(1,t.bottomColor),r.fillStyle=o,r.fillRect(0,0,s.width,s.height);const a=new E.CanvasTexture(s);a.needsUpdate=!0;const c=n.background;return c instanceof E.Texture&&c!==n.environment&&c.dispose(),n.background=a,F.ok(void 0)}catch(n){return F.err(new K("Failed to create gradient background",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}fitCameraToObject(e,t,n){try{const s=zt(e)??e,r=vn(t)??t,o=xi(n)??n,a=new E.Box3().setFromObject(s),c=a.getCenter(new E.Vector3),u=a.getSize(new E.Vector3),d=Math.max(u.x,u.y,u.z);let h;"fov"in r?h=r.fov*(Math.PI/180):h=50*(Math.PI/180);let f=Math.abs(d/2/Math.tan(h/2));f*=2;const m=-Math.PI/4,w=Math.PI/8,b=c.x+f*Math.sin(m)*Math.cos(w),_=c.y+f*Math.sin(w),A=c.z+f*Math.cos(m)*Math.cos(w);return r.position.set(b,_,A),r.lookAt(c),r.updateProjectionMatrix(),o&&o.target&&(o.target.copy(c),o.update()),F.ok(void 0)}catch(s){return F.err(new K("Failed to fit camera to object",Y.CAMERA_INIT_FAILED,{originalError:s}))}}}class Sl{constructor(){this.events=new Es,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-BCGY9F7h.cjs"));if(this.disposed)return F.ok(void 0);const n=new t;return this.inner=n,n.events.on("pathtracing:paused",s=>{this.events.emit("pathtracing:paused",s)}),this.pendingSettings&&(n.updateSettings(this.pendingSettings),this.pendingSettings=void 0),this.pendingEnabled!==void 0&&(n.setEnabled(this.pendingEnabled),this.pendingEnabled=void 0),n.initialize(e)}setEnabled(e){this.inner?this.inner.setEnabled(e):this.pendingEnabled=e}updateSettings(e){this.inner?this.inner.updateSettings(e):this.pendingSettings={...this.pendingSettings,...e}}render(e,t){return this.inner?this.inner.render(e,t):Promise.resolve(F.ok(void 0))}getSampleCount(){var e;return((e=this.inner)==null?void 0:e.getSampleCount())??0}isEnabled(){var e;return((e=this.inner)==null?void 0:e.isEnabled())??!1}isPathTracerDisposed(){var e;return((e=this.inner)==null?void 0:e.isPathTracerDisposed())??!1}reset(e){var t;(t=this.inner)==null||t.reset(e)}dispose(){var e;this.disposed=!0,(e=this.inner)==null||e.dispose()}isSupported(){var e;return((e=this.inner)==null?void 0:e.isSupported())??!0}}/*!
|
|
1
|
+
"use strict";var jo=Object.create;var zi=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var Zo=Object.getOwnPropertyNames;var Ko=Object.getPrototypeOf,Xo=Object.prototype.hasOwnProperty;var Yo=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zo(e))!Xo.call(i,s)&&s!==t&&zi(i,s,{get:()=>e[s],enumerable:!(n=Wo(e,s))||n.enumerable});return i};var Rs=(i,e,t)=>(t=i!=null?jo(Ko(i)):{},Yo(e||!i||!i.__esModule?zi(t,"default",{value:i,enumerable:!0}):t,i));const me=require("react/jsx-runtime"),se=require("react"),p=require("three");function qo(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const E=qo(p);class K extends Error{constructor(e,t,n){super(e),this.code=t,this.context=n,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,K)}static fromError(e,t,n){if(e instanceof K)return e;const s=e instanceof Error?e.message:String(e),r={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new K(s,t,r)}}var Y=(i=>(i.SCENE_INIT_FAILED="SCENE_INIT_FAILED",i.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",i.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",i.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",i.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",i.INITIALIZATION_FAILED="INITIALIZATION_FAILED",i.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",i.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",i.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",i.INVALID_CONFIGURATION="INVALID_CONFIGURATION",i.RENDER_ERROR="RENDER_ERROR",i.RENDER_FAILED="RENDER_FAILED",i.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",i.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",i.INVALID_STATE="INVALID_STATE",i.INVALID_PARAMETER="INVALID_PARAMETER",i.OPERATION_FAILED="OPERATION_FAILED",i.UNKNOWN="UNKNOWN",i))(Y||{});const F={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return F.ok(i())}catch(e){return F.err(e instanceof K?e:new K(String(e),Y.UNKNOWN,{originalError:e}))}}};class Es{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);return n&&n.add(t),()=>{var s;(s=this.listeners.get(e))==null||s.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(s=>{try{s(t)}catch(r){console.error(`Error in event listener for ${String(e)}:`,r)}})}once(e,t){const n=this.on(e,s=>{n(),t(s)});return n}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t;return((t=this.listeners.get(e))==null?void 0:t.size)||0}off(e,t){var n;(n=this.listeners.get(e))==null||n.delete(t)}removeListener(e,t){this.off(e,t)}}const $s=300,vs={meters:1,centimeters:.01,millimeters:.001,feet:.3048,inches:.0254},$o="softbox-units-scale";function Mr(i){const e=i??"meters";if(!Object.prototype.hasOwnProperty.call(vs,e))throw new K(`Unknown units '${String(e)}'. Valid values: ${Object.keys(vs).join(", ")}`,Y.INVALID_PARAMETER);return vs[e]}const Ui="#1a1a1f";class Qo{configureScene(e,t,n){var a,c,u;if(n.helpers){const d={grid:n.helpers.grid,axes:n.helpers.axes,gridColor:"#AAAAAA"},h=t.addHelpers(e,d);h.ok||console.warn("Failed to add helpers:",h.error)}const s=n.lighting;if(s){const d={ambient:s.ambientLight?{color:String(s.ambientLight.color),intensity:s.ambientLight.intensity}:void 0,hemisphere:s.hemisphereLight?{skyColor:String(s.hemisphereLight.skyColor),groundColor:String(s.hemisphereLight.groundColor),intensity:s.hemisphereLight.intensity}:void 0,directional:s.directionalLight?{color:String(s.directionalLight.color),intensity:s.directionalLight.intensity,position:Array.isArray(s.directionalLight.position)?s.directionalLight.position:void 0,castShadow:s.directionalLight.castShadow,shadow:s.directionalLight.shadow}:void 0},h=t.addLighting(e,d);h.ok||console.warn("Failed to add lighting:",h.error)}const r=(a=n.environment)==null?void 0:a.url,o=(((c=n.helpers)==null?void 0:c.studioEnvironment)??!1)&&(((u=n.helpers)==null?void 0:u.darkStudioMode)??!1);if(n.backgroundColor&&!r&&!o){const d=String(n.backgroundColor),h=t.createGradientBackground(e,{topColor:d,bottomColor:d});h.ok||console.warn("Failed to set background:",h.error)}}async configureEnvironment(e,t,n,s,r,o){var d,h,f,m,w,b;const a=await t.initialize({renderer:s,autoDispose:!0});if(o())return;a.ok||console.warn("Failed to initialize environment service:",a.error);const c={backgroundBlurriness:(d=r.environment)==null?void 0:d.backgroundBlurriness,backgroundIntensity:(h=r.environment)==null?void 0:h.backgroundIntensity,environmentIntensity:(f=r.environment)==null?void 0:f.environmentIntensity},u=(m=r.environment)==null?void 0:m.url;if(u){const _=await t.loadEnvironmentMap(u);if(o())return;_.ok?t.applyToScene(e,_.value,c):console.warn("Failed to load environment map:",_.error)}else if((w=r.helpers)!=null&&w.studioEnvironment){const _=t.createStudioEnvironment();if(_.ok){if(t.applyToScene(e,_.value,{...c,setBackground:!1}),(b=r.helpers)!=null&&b.darkStudioMode&&n){const A=n.createGradientBackground(e,{topColor:Ui,bottomColor:Ui});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",_.error)}}}class Jo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,this.continuousReasons=new Set,this.alwaysRender=!1,this.enableIdleDetection=e.enableIdleDetection??!0,this.idleDelay=e.idleDelay??1e3,this.targetFPS=e.targetFPS??60,this.frameInterval=1e3/this.targetFPS,this.enableFrameRateLimiting=e.enableFrameRateLimiting??!0,this.alwaysRender=e.alwaysRender??!1,this.lastRenderTime=performance.now()}requestRender(){this.needsRender=!0,this.wakeUp()}requireContinuous(e){this.continuousReasons.add(e),this.continuousRenderingEnabled=!0,this.wakeUp()}releaseContinuous(e){this.continuousReasons.delete(e),this.continuousRenderingEnabled=this.continuousReasons.size>0}hasContinuousDemand(){return this.continuousReasons.size>0}setAlwaysRender(e){this.alwaysRender=e,e&&this.wakeUp()}wakeUp(){this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1}start(e){if(this.animationFrameId!==null)return;const t=n=>{if(this.animationFrameId===null)return;const s=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&s<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(s),this.lastRenderTime=n,this.needsRender=!1),this.enableIdleDetection&&!this.alwaysRender&&(this.continuousRenderingEnabled||this.needsRender?this.wakeUp():this.idleTimeout===null&&!this.isIdle&&(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0},this.idleDelay))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):this.animationFrameId=null};this.animationFrameId=requestAnimationFrame(t)}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1,this.needsRender=!1,this.continuousRenderingEnabled=!1,this.continuousReasons.clear(),this.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}function Vn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ps(i,e){if(!Vn(i)||!Vn(e))return e===void 0?i:e;const t=e,n={...i};for(const s of Object.keys(t)){const r=t[s];if(r===void 0)continue;const o=n[s];n[s]=Vn(o)&&Vn(r)?ps(o,r):r}return n}class Rr{static serialize(e,t,n,s){const r=t.position,o=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:r.x,y:r.y,z:r.z},cameraTarget:{x:o.x,y:o.y,z:o.z},controlsTarget:{x:o.x,y:o.y,z:o.z},rendererSize:{width:s.clientWidth,height:s.clientHeight}}}static async restore(e,t,n,s){t.position.set(e.cameraPosition.x,e.cameraPosition.y,e.cameraPosition.z),t.lookAt({x:e.cameraTarget.x,y:e.cameraTarget.y,z:e.cameraTarget.z,set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),n.target&&n.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),n.update&&n.update(),e.modelUrl&&s&&await s(e.modelUrl)}}function Qs(i,e){i.type==="perspective"&&"aspect"in i&&(i.aspect=e),i.updateProjectionMatrix()}class gt{constructor(e={}){this.data=Object.freeze({status:"idle",currentModel:null,error:null,isInitialized:!1,loadProgress:0,renderInfo:{frameCount:0,fps:0,lastRenderTime:0,averageRenderTime:0},...e})}get status(){return this.data.status}get currentModel(){return this.data.currentModel}get error(){return this.data.error}get isInitialized(){return this.data.isInitialized}get loadProgress(){return this.data.loadProgress}get renderInfo(){return this.data.renderInfo}setInitialized(){return new gt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new gt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new gt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new gt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new gt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new gt({...this.data,status:"rendering"})}updateRenderInfo(e){return new gt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new gt({...this.data,status:"disposed",currentModel:null})}canLoad(){return this.data.isInitialized&&(this.data.status==="idle"||this.data.status==="loaded"||this.data.status==="error"||this.data.status==="rendering")}canRender(){return this.data.isInitialized&&this.data.status==="loaded"&&this.data.currentModel!==null}isLoading(){return this.data.status==="loading"}hasError(){return this.data.status==="error"&&this.data.error!==null}toJSON(){return{...this.data}}}class ea{constructor(){this.state=new gt,this.stateChangeCallbacks=new Set}getState(){return this.state}setInitialized(){this.updateState(this.state.setInitialized())}startLoading(){this.updateState(this.state.startLoading())}setLoaded(e){this.updateState(this.state.setLoaded(e))}setError(e){this.updateState(this.state.setError(e))}startRendering(){this.updateState(this.state.startRendering())}updateRenderInfo(e){this.updateState(this.state.updateRenderInfo(e))}setDisposed(){this.updateState(this.state.dispose())}canLoad(){return this.state.canLoad()}isInitialized(){return this.state.isInitialized}getStatus(){return this.state.status}getCurrentModel(){return this.state.currentModel}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>{this.stateChangeCallbacks.delete(e)}}clearCallbacks(){this.stateChangeCallbacks.clear()}updateState(e){this.state=e,this.stateChangeCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("Error in state change callback:",n)}})}}function vr(i){const e=i.toDataURL("image/png");return!e||e==="data:,"?null:e}class ta{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,s){if(this.isShowingScreenshot)return;const r=this.renderer.getDomElement(),o=vr(r);if(!o){console.warn("[ScreenshotManager] Screenshot capture produced no image, keeping live scene");return}const a=document.createElement("img");a.src=o,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.pointerEvents="auto",a.style.cursor="grab";const c=r.parentElement;if(c){this.serializedSceneState=Rr.serialize(n,e,t,r),r.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const u=()=>{this.restore()};a.addEventListener("mousedown",u),a.addEventListener("touchstart",u);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,s==null||s()}}async restore(){if(!this.isShowingScreenshot||!this.screenshotElement)return;const e=this.renderer.getDomElement(),t=this.screenshotElement.parentElement;t&&(this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),t.removeChild(this.screenshotElement),e.style.display="",this.screenshotElement=null,this.isShowingScreenshot=!1,this.onRestore&&await this.onRestore())}getSerializedState(){return this.serializedSceneState}dispose(){this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),this.screenshotElement&&this.screenshotElement.parentElement&&this.screenshotElement.parentElement.removeChild(this.screenshotElement),this.isShowingScreenshot&&(this.renderer.getDomElement().style.display=""),this.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class na{constructor(e){this.currentModel=null,this.modelLoader=e.modelLoader,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.floorAlignmentService=e.floorAlignmentService,this.sceneSetupService=e.sceneSetupService,this.renderer=e.renderer,this.autoFitToObject=e.autoFitToObject??!1,this.unitsScaleToMeters=e.unitsScaleToMeters??1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const n=performance.now();try{let s;if(typeof e=="string"){this.lastModelUrl=e,t.emit("model:loading",{url:e});const a=await this.modelLoader.load(e,(c,u)=>{t.emit("model:progress",{url:e,loaded:c,total:u})});if(!a.ok)throw a.error;s=a.value.scene}else s=e;if(this.unitsScaleToMeters!==1){if(!this.sceneSetupService)throw new K("A units conversion is configured but no scene setup service is available to apply it",Y.INVALID_PARAMETER);const a=this.sceneSetupService.wrapInUnitsScaleGroup(s,this.unitsScaleToMeters);if(!a.ok)throw a.error;s=a.value}this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const r=this.scene.add(s);if(!r.ok)throw r.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(s);a.ok||console.warn("Failed to align model to floor:",a.error)}if(s.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=s,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,s,2);a.ok||console.warn("Failed to add dynamic grid:",a.error);const c=this.sceneSetupService.snapObjectToFloor(this.scene,s);c.ok||console.warn("Failed to snap object to floor:",c.error);const u=this.sceneSetupService.fitShadowCameraToObject(this.scene,s);if(u.ok||console.warn("Failed to fit shadow camera to object:",u.error),this.renderer){const d=this.sceneSetupService.bakeContactShadow(this.scene,s,this.renderer);d.ok||console.warn("Failed to bake contact shadow:",d.error)}}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(s,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const o=performance.now()-n;return t.emit("model:loaded",{model:s,loadTime:o}),F.ok(s)}catch(s){const r=s instanceof K?s:new K("Failed to load model",Y.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:r,url:typeof e=="string"?e:void 0}),F.err(r)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.dispose()}dispose(){var e,t;this.disposeCurrentModel(),(t=(e=this.modelLoader).dispose)==null||t.call(e),this.lastModelUrl=void 0}}class sa{constructor(e){this.scene=e.scene,this.pathTracingService=e.pathTracingService,this.environmentService=e.environmentService}updateServices(e){e.pathTracingService&&(this.pathTracingService=e.pathTracingService),e.environmentService&&(this.environmentService=e.environmentService)}disposeSceneResources(e=!1){this.scene.disposeContents({keepBackgrounds:!0}),this.triggerGarbageCollection()}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.disposeContents(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}function Cr(i){return typeof i=="object"&&i!==null&&"getInternalRenderer"in i&&typeof i.getInternalRenderer=="function"}class ia{constructor(e){this.completeHandled=!1,this.selfPauseListeners=new Set,this.deps=e}isEnabled(){var e;return!!(this.deps.service&&(((e=this.deps.getOptions().pathTracing)==null?void 0:e.enabled)??!1))}getMaxSamples(){var e;return((e=this.deps.getOptions().pathTracing)==null?void 0:e.maxSamples)??$s}isCompleteHandled(){return this.completeHandled}isAccumulating(){var e;return!!((e=this.deps.service)!=null&&e.isEnabled())}onSelfPause(e){return this.selfPauseListeners.add(e),()=>this.selfPauseListeners.delete(e)}async initialize(){var u;const{service:e,getOptions:t,isDisposed:n,renderer:s,renderLoopManager:r,schedule:o}=this.deps;if(!e||!(((u=t().pathTracing)==null?void 0:u.enabled)??!1))return;const a=await e.initialize({enabled:!0,renderer:s});if(n())return;if(!a.ok){console.warn("Failed to initialize path tracing:",a.error);return}const c=t().pathTracing;c&&e.updateSettings({samples:c.maxSamples??$s,bounces:c.bounces,transmissiveBounces:c.transmissiveBounces,renderScale:c.renderScale,lowResScale:c.lowResScale,dynamicLowRes:c.dynamicLowRes,enablePathTracing:c.enabled??!0}),e.events.on("pathtracing:paused",({reason:d})=>{r.releaseContinuous("path-tracing"),t().staticScene||r.setAlwaysRender(!1),o(()=>{r.hasContinuousDemand()||r.stop()},100),d==="gave-up"&&this.selfPauseListeners.forEach(h=>h())})}resetAccumulation(e=!1){this.deps.service&&this.isEnabled()&&(this.deps.service.reset(e),this.completeHandled=!1)}getSampleCount(){var e;return((e=this.deps.service)==null?void 0:e.getSampleCount())||0}beforeFrame(){var e;return{wasActive:((e=this.deps.service)==null?void 0:e.isEnabled())||!1,samples:this.getSampleCount()}}render(e,t){const n=this.deps.service;if(!n||n.isPathTracerDisposed())return null;const s=n.getSampleCount(),r=s>=this.getMaxSamples()&&s>0;return!n.isEnabled()&&!r?null:(s===0&&(this.startTime=performance.now()),n.render(e,t))}detectCompletion(e,t){const n=this.deps.service;if(!n)return;(n.getSampleCount()||0)>=this.getMaxSamples()&&!this.completeHandled&&e.wasActive&&this.handleComplete(e.samples,t)}handleComplete(e,t){const{events:n,renderLoopManager:s,getOptions:r,schedule:o,replaceWithScreenshot:a,renderer:c}=this.deps;this.completeHandled=!0,s.releaseContinuous("path-tracing"),r().staticScene||s.setAlwaysRender(!1),n.emit("pathtracing:complete",{samples:e,totalTime:t-(this.startTime||0)});const u=()=>{s.hasContinuousDemand()||s.stop()};if(r().replaceWithScreenshotOnComplete){o(()=>{a(),o(u,200)},100);return}if(s.requestRender(),o(u,100),Cr(c)){const d=c.getInternalRenderer();d&&(d.autoClear=!1)}}onResizeStart(){var t;const e=((t=this.deps.service)==null?void 0:t.isEnabled())??!1;return this.deps.service&&this.completeHandled&&(this.deps.service.reset(),this.completeHandled=!1),e}onResizeEnd(e){e&&this.deps.service&&this.deps.service.setEnabled(!0)}}function Ir(){const i="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?i[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}const ra=i=>[i,"video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].filter(t=>!!t).find(t=>MediaRecorder.isTypeSupported(t));class oa{constructor(e){this.pendingSettlers=new Set,this.pathTracedWaitSettlers=new Set,this.deps=e}async captureStill(e={}){return this.deps.isDisposed()?F.err(new K("Cannot capture a still from a disposed viewer",Y.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?F.err(new K("Viewer was disposed while a model load finished",Y.INVALID_STATE)):this.deps.isScreenshotActive()?F.err(new K("Cannot capture a still while a screenshot is replacing the canvas",Y.INVALID_STATE)):this.deps.pathTracing.isEnabled()?this.capturePathTracedStill(e):this.captureRasterStill(e))}settleOnDispose(){[...this.pendingSettlers].forEach(e=>e("disposed"))}notifyTurntableEnabled(){[...this.pathTracedWaitSettlers].forEach(e=>e("turntable"))}async captureVideo(e={}){var d;if(this.deps.isDisposed())return F.err(new K("Cannot capture video from a disposed viewer",Y.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return F.err(new K("Viewer was disposed while a model load finished",Y.INVALID_STATE));if(this.deps.isScreenshotActive())return F.err(new K("Cannot capture video while a screenshot is replacing the canvas",Y.INVALID_STATE));const t=e.duration??3;if(!(t>0))return F.err(new K("Video duration must be a positive number of seconds",Y.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return F.err(new K("Video capture needs MediaRecorder and canvas.captureStream support",Y.UNSUPPORTED_FORMAT));const s=n.captureStream(e.fps??30);let r;try{r=new MediaRecorder(s,{mimeType:ra(e.mimeType),videoBitsPerSecond:e.videoBitsPerSecond})}catch(h){return s.getTracks().forEach(f=>f.stop()),F.err(new K("Failed to start the video recorder",Y.OPERATION_FAILED,{originalError:h}))}const o=s.getVideoTracks()[0],a=(d=o==null?void 0:o.requestFrame)==null?void 0:d.bind(o),c=a?this.deps.events.on("render:complete",()=>a()):()=>{},u=`video-capture:${Ir()}`;return this.deps.renderLoopManager.requireContinuous(u),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(h=>{const f=[];let m=null,w=!1;const b=A=>{w||(w=!0,this.pendingSettlers.delete(_),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(u),s.getTracks().forEach(T=>T.stop()),h(A))},_=()=>{b(F.err(new K("Viewer was disposed during video capture",Y.INVALID_STATE)));try{r.stop()}catch{}};this.pendingSettlers.add(_),r.ondataavailable=A=>{A.data.size>0&&f.push(A.data)},r.onstop=()=>{b(F.ok(new Blob(f,{type:r.mimeType||"video/webm"})))},r.onerror=()=>{b(F.err(new K("Video recording failed",Y.OPERATION_FAILED)))},r.start(250),m=setTimeout(()=>{r.state!=="inactive"&&r.stop()},t*1e3)})}async capturePathTracedStill(e){if(e.width!==void 0||e.height!==void 0)return F.err(new K("Path-traced stills are captured at the canvas resolution; omit width/height",Y.INVALID_PARAMETER));if(this.deps.isAutoRotating())return F.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",Y.INVALID_STATE));const t=this.deps.pathTracing.isAccumulating()&&this.deps.getStatus()!=="error";if(!this.deps.pathTracing.isCompleteHandled()&&t){const n=await this.waitForPathTracingOutcome();if(n==="disposed")return F.err(new K("Viewer was disposed while waiting for the path tracer",Y.INVALID_STATE));if(n==="error")return F.err(new K("Model failed while waiting for the path tracer",Y.RENDER_FAILED));if(n==="turntable")return F.err(new K("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",Y.INVALID_STATE))}return this.readCanvasPng()}waitForPathTracingOutcome(){return new Promise(e=>{let t=()=>{},n=()=>{},s=()=>{},r=()=>{};const o=a=>{this.pendingSettlers.delete(o),this.pathTracedWaitSettlers.delete(o),t(),n(),s(),r(),e(a)};this.pendingSettlers.add(o),this.pathTracedWaitSettlers.add(o),t=this.deps.events.once("pathtracing:complete",()=>o("complete")),n=this.deps.events.once("model:error",()=>o("error")),s=this.deps.pathTracing.onSelfPause(()=>o("complete")),r=this.deps.events.on("controls:change",()=>{this.deps.isAutoRotating()&&o("turntable")})})}captureRasterStill(e){const{renderer:t,scene:n,camera:s,renderLoopManager:r}=this.deps,o=t.getDomElement(),a=t.getPixelRatio(),c=o.clientWidth>0&&o.clientHeight>0,u=c?o.clientWidth:Math.round(o.width/a),d=c?o.clientHeight:Math.round(o.height/a);if(u<=0||d<=0)return F.err(new K("Cannot capture: the canvas has no size",Y.INVALID_STATE));const h=u/d,f=Math.round(e.width??(e.height!==void 0?e.height*h:u*a)),m=Math.round(e.height??(e.width!==void 0?e.width/h:d*a)),w=t.capabilities.maxTextureSize;if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0||f>w||m>w)return F.err(new K(`Requested still size ${f}x${m} is outside 1..${w}`,Y.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),Qs(s,f/m);const b=t.render(n,s),_=b.ok?this.readCanvasPng():F.err(b.error);return t.setSize(u,d),t.setPixelRatio(a),Qs(s,h),t.render(n,s),r.requestRender(),_}readCanvasPng(){const e=vr(this.deps.renderer.getDomElement());return e?F.ok(e):F.err(new K("Canvas produced an empty image",Y.RENDER_FAILED))}}class aa{constructor(e){var r;this.frameCount=0,this.disposed=!1,this.pendingTimers=new Set,this.modelLoadChain=Promise.resolve(),this.renderer=e.renderer,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.options=e.options,this.rendererOptions=e.rendererOptions,this.sceneSetupService=e.sceneSetupService,this.environmentService=e.environmentService,this.selectionService=e.selectionService,this.anchorProjectionService=e.anchorProjectionService,this.animationService=e.animationService,this.stateManager=new ea,this.screenshotManager=new ta({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}});const t=Mr(this.options.units);this.modelManager=new na({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,renderer:this.renderer,autoFitToObject:(r=this.options.camera)==null?void 0:r.autoFitToObject,unitsScaleToMeters:t}),this.resourceManager=new sa({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new Qo,this.events=new Es;const n=this.options.rendering||{},s=this.options.staticScene!==!1;this.renderLoopManager=new Jo({enableIdleDetection:n.enableIdleDetection??s,idleDelay:n.idleDelay,targetFPS:n.targetFPS,enableFrameRateLimiting:n.enableFrameRateLimiting,alwaysRender:!1}),this.pathTracing=new ia({service:e.pathTracingService,events:this.events,renderLoopManager:this.renderLoopManager,renderer:this.renderer,getOptions:()=>this.options,isDisposed:()=>this.disposed,schedule:(o,a)=>this.schedule(o,a),replaceWithScreenshot:()=>this.replaceWithScreenshot()}),this.capture=new oa({renderer:this.renderer,scene:this.scene,camera:this.camera,events:this.events,renderLoopManager:this.renderLoopManager,pathTracing:this.pathTracing,getStatus:()=>this.stateManager.getStatus(),isDisposed:()=>this.disposed,awaitModelLoads:()=>this.modelLoadChain,reviveRenderLoop:()=>this.reviveRenderLoop(),isAutoRotating:()=>this.controls.autoRotate,isScreenshotActive:()=>this.screenshotManager.isActive()})}async initialize(){var e,t;try{const n=this.renderer.initialize(this.rendererOptions||{});return n.ok?(this.sceneSetupService&&this.sceneConfigurator.configureScene(this.scene,this.sceneSetupService,this.options),this.environmentService&&(await this.sceneConfigurator.configureEnvironment(this.scene,this.environmentService,this.sceneSetupService,this.renderer,this.options,()=>this.disposed),this.disposed)||(await this.pathTracing.initialize(),this.disposed)||(this.selectionService&&this.selectionService.initialize({canvas:this.renderer.getDomElement(),camera:this.camera,getPickRoot:()=>this.modelManager.getCurrentModel(),bvh:(e=this.options.selection)==null?void 0:e.bvh,onPick:s=>{s&&!this.disposed&&this.events.emit("object:selected",s)}}),this.stateManager.setInitialized(),this.startRenderLoop(),this.options.staticScene?this.pathTracing.isEnabled()&&this.renderLoopManager.requireContinuous("path-tracing"):this.renderLoopManager.setAlwaysRender(!0),(t=this.options.controls)!=null&&t.autoRotate&&this.renderLoopManager.requireContinuous("turntable"),this.renderLoopManager.requestRender()),F.ok(void 0)):n}catch(n){const s=new K("Failed to initialize viewer",Y.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),F.err(s)}}loadModel(e){const t=this.modelLoadChain.then(()=>this.runLoadModel(e));return this.modelLoadChain=t.then(()=>{},()=>{}),t}async runLoadModel(e){if(this.disposed)return F.err(new K("Cannot load model after dispose",Y.INVALID_STATE));if(!this.stateManager.canLoad())return F.err(new K("Cannot load model in current state",Y.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const t=await this.modelManager.loadModel(e,this.events);return this.disposed?(t.ok&&this.modelManager.disposeCurrentModel(),F.err(new K("Viewer was disposed while the model was loading",Y.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(!0),F.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof K?t:new K("Failed to load model",Y.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),F.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var o;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.isDisposed()){this.renderLoopManager.stop();return}const t=performance.now(),n=e>0?1e3/e:0;this.controls.update()&&(this.events.emit("controls:change",{controls:this.controls}),this.pathTracing.resetAccumulation(),this.renderLoopManager.requestRender()),(o=this.animationService)!=null&&o.isPlaying()&&this.animationService.update(e/1e3);const r=this.pathTracing.beforeFrame();this.renderFrame().catch(a=>{console.error("[ViewerCore] Render frame error:",a)}),this.pathTracing.detectCompletion(r,t),this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t})})}stopRenderLoop(){this.renderLoopManager.stop()}schedule(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),!this.disposed&&e()},t);this.pendingTimers.add(n)}async renderFrame(){const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.screenshotManager.isActive())return;this.stateManager.startRendering();const t=await(this.pathTracing.render(this.scene,this.camera)??Promise.resolve(this.renderer.render(this.scene,this.camera)));if(!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}this.events.emit("render:complete",{frame:this.frameCount,renderTime:performance.now()-e,samples:this.pathTracing.getSampleCount()})}updateOptions(e){var h,f,m,w,b,_,A,T,x;if(this.disposed)return;const t=(h=this.options.animations)==null?void 0:h.autoplay,n=(f=this.options.controls)==null?void 0:f.autoRotate;this.options=ps(this.options,e);let s=!1;e.backgroundColor!==void 0&&this.applyBackgroundColor(e.backgroundColor);const r=(m=e.renderer)==null?void 0:m.toneMappingExposure;r!==void 0&&(this.renderer.setToneMappingExposure(r),s=!0);const o=(w=e.environment)==null?void 0:w.environmentIntensity;o!==void 0&&(this.scene.setEnvironmentIntensity(o),s=!0);const a=(b=e.controls)==null?void 0:b.autoRotate;a!==void 0&&a!==n&&(this.controls.autoRotate=a,a?(this.renderLoopManager.requireContinuous("turntable"),this.capture.notifyTurntableEnabled()):this.renderLoopManager.releaseContinuous("turntable"),s=!0);const c=(_=e.controls)==null?void 0:_.autoRotateSpeed;c!==void 0&&(this.controls.autoRotateSpeed=c,s=!0);const u=(A=e.animations)==null?void 0:A.autoplay;u!==void 0&&u!==t&&(u?this.modelManager.getCurrentModel()&&this.autoplayFromOptions(u):this.pauseAnimations(),s=!0);const d=(T=e.animations)==null?void 0:T.speed;d!==void 0&&((x=this.animationService)==null||x.setSpeed(d),s=!0),s&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}applyBackgroundColor(e){var n;if((n=this.options.environment)!=null&&n.url||!this.sceneSetupService)return;const t=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(e),bottomColor:String(e)});if(!t.ok){console.warn("Failed to update background color:",t.error);return}this.renderLoopManager.requestRender()}resize(e,t){if(this.disposed)return;const n=this.renderer.getDomElement();if(n.width===e&&n.height===t)return;const s=this.pathTracing.onResizeStart();Qs(this.camera,e/t),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}this.pathTracing.onResizeEnd(s),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}getRenderer(){return this.renderer}getScene(){return this.scene}getCamera(){return this.camera}getControls(){return this.controls}getModel(){return this.modelManager.getCurrentModel()}requestRender(){this.renderLoopManager.requestRender()}reviveRenderLoop(){this.stateManager.isInitialized()&&!this.renderLoopManager.isRunning()&&this.startRenderLoop()}getAnimationNames(){var e;return((e=this.animationService)==null?void 0:e.getClipNames())??[]}playAnimations(e){var n;if(!this.animationService)return e!==void 0?F.err(new K(`Cannot play animation clip '${e}': the viewer was assembled without an animation service`,Y.INVALID_STATE)):F.ok(void 0);const t=this.animationService.play(e);return t.ok?(this.animationService.isPlaying()&&((n=this.sceneSetupService)==null||n.setContactShadowMode(this.scene,"live"),this.renderLoopManager.requireContinuous("animations"),this.reviveRenderLoop(),this.renderLoopManager.requestRender()),F.ok(void 0)):t}autoplayFromOptions(e){const t=this.playAnimations(typeof e=="string"?e:void 0);t.ok||console.error("animations.autoplay failed:",t.error.message)}pauseAnimations(){var e;(e=this.animationService)==null||e.pause(),this.renderLoopManager.releaseContinuous("animations"),this.rebakeContactShadowForCurrentPose(),this.renderLoopManager.requestRender()}rebakeContactShadowForCurrentPose(){const e=this.modelManager.getCurrentModel();if(!e||!this.sceneSetupService)return;const t=this.sceneSetupService.bakeContactShadow(this.scene,e,this.renderer);t.ok||console.warn("Failed to re-bake contact shadow after pausing animations:",t.error)}attachAnimations(e){if(!this.animationService)return;this.renderLoopManager.releaseContinuous("animations"),this.animationService.attach(e);const t=this.options.animations;(t==null?void 0:t.speed)!==void 0&&this.animationService.setSpeed(t.speed);const n=t==null?void 0:t.autoplay;n&&this.autoplayFromOptions(n)}createAnchorProjector(){return this.anchorProjectionService?this.anchorProjectionService.createProjector({camera:this.camera,getCanvas:()=>this.renderer.getDomElement(),getModel:()=>this.getModel()}):null}captureStill(e={}){return this.capture.captureStill(e)}captureVideo(e={}){return this.capture.captureVideo(e)}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){const e=this.screenshotManager.getSerializedState();e&&await Rr.restore(e,this.camera,this.controls,async t=>{const n=await this.loadModel(t);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){var e,t;this.disposed=!0,this.pendingTimers.forEach(n=>clearTimeout(n)),this.pendingTimers.clear(),this.stopRenderLoop(),(e=this.selectionService)==null||e.dispose(),(t=this.animationService)==null||t.detach(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.capture.settleOnDispose(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class Pt{constructor(e){this.vector=e}get x(){return this.vector.x}set x(e){this.vector.x=e}get y(){return this.vector.y}set y(e){this.vector.y=e}get z(){return this.vector.z}set z(e){this.vector.z=e}set(e,t,n){this.vector.set(e,t,n)}copy(e){this.vector.set(e.x,e.y,e.z)}add(e){this.vector.x+=e.x,this.vector.y+=e.y,this.vector.z+=e.z}multiply(e){this.vector.x*=e.x,this.vector.y*=e.y,this.vector.z*=e.z}normalize(){this.vector.normalize()}length(){return this.vector.length()}getThreeVector(){return this.vector}static fromThreeVector(e){return new Pt(e)}static create(e=0,t=0,n=0){return new Pt(new E.Vector3(e,t,n))}}const Lr=0,ca=1,Pr=2,Vi=2,Cs=1.25,Hi=1,He=32,Ne=He/4,wi=65535,la=wi<<16,us=Math.pow(2,-24),Ei=Symbol("SKIP_GENERATION"),Or={strategy:Lr,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Ei]:!1};function Ae(i,e,t){return t.min.x=e[i],t.min.y=e[i+1],t.min.z=e[i+2],t.max.x=e[i+3],t.max.y=e[i+4],t.max.z=e[i+5],t}function Gi(i){let e=-1,t=-1/0;for(let n=0;n<3;n++){const s=i[n+3]-i[n];s>t&&(t=s,e=n)}return e}function ji(i,e){e.set(i)}function Wi(i,e,t){let n,s;for(let r=0;r<3;r++){const o=r+3;n=i[r],s=e[r],t[r]=n<s?n:s,n=i[o],s=e[o],t[o]=n>s?n:s}}function Hn(i,e,t){for(let n=0;n<3;n++){const s=e[i+2*n],r=e[i+2*n+1],o=s-r,a=s+r;o<t[n]&&(t[n]=o),a>t[n+3]&&(t[n+3]=a)}}function un(i){const e=i[3]-i[0],t=i[4]-i[1],n=i[5]-i[2];return 2*(e*t+t*n+n*e)}function Ie(i,e){return e[i+15]===wi}function Ge(i,e){return e[i+6]}function Xe(i,e){return e[i+14]}function Be(i){return i+Ne}function ze(i,e){const t=e[i+6];return i+t*Ne}function Ts(i,e){return e[i+7]}function ha(i){return i}function Is(i,e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0,h=1/0,f=1/0,m=1/0,w=-1/0,b=-1/0,_=-1/0;const A=i.offset||0;for(let T=(e-A)*6,x=(e+t-A)*6;T<x;T+=6){const S=i[T+0],M=i[T+1],P=S-M,I=S+M;P<r&&(r=P),I>c&&(c=I),S<h&&(h=S),S>w&&(w=S);const C=i[T+2],D=i[T+3],L=C-D,k=C+D;L<o&&(o=L),k>u&&(u=k),C<f&&(f=C),C>b&&(b=C);const N=i[T+4],H=i[T+5],j=N-H,$=N+H;j<a&&(a=j),$>d&&(d=$),N<m&&(m=N),N>_&&(_=N)}n[0]=r,n[1]=o,n[2]=a,n[3]=c,n[4]=u,n[5]=d,s[0]=h,s[1]=f,s[2]=m,s[3]=w,s[4]=b,s[5]=_}const Et=32,ua=(i,e)=>i.candidate-e.candidate,Mt=new Array(Et).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Gn=new Float32Array(6);function da(i,e,t,n,s,r){let o=-1,a=0;if(r===Lr)o=Gi(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ca)o=Gi(i),o!==-1&&(a=fa(t,n,s,o));else if(r===Pr){const c=un(i);let u=Cs*s;const d=t.offset||0,h=(n-d)*6,f=(n+s-d)*6;for(let m=0;m<3;m++){const w=e[m],A=(e[m+3]-w)/Et;if(s<Et/4){const T=[...Mt];T.length=s;let x=0;for(let M=h;M<f;M+=6,x++){const P=T[x];P.candidate=t[M+2*m],P.count=0;const{bounds:I,leftCacheBounds:C,rightCacheBounds:D}=P;for(let L=0;L<3;L++)D[L]=1/0,D[L+3]=-1/0,C[L]=1/0,C[L+3]=-1/0,I[L]=1/0,I[L+3]=-1/0;Hn(M,t,I)}T.sort(ua);let S=s;for(let M=0;M<S;M++){const P=T[M];for(;M+1<S&&T[M+1].candidate===P.candidate;)T.splice(M+1,1),S--}for(let M=h;M<f;M+=6){const P=t[M+2*m];for(let I=0;I<S;I++){const C=T[I];P>=C.candidate?Hn(M,t,C.rightCacheBounds):(Hn(M,t,C.leftCacheBounds),C.count++)}}for(let M=0;M<S;M++){const P=T[M],I=P.count,C=s-P.count,D=P.leftCacheBounds,L=P.rightCacheBounds;let k=0;I!==0&&(k=un(D)/c);let N=0;C!==0&&(N=un(L)/c);const H=Hi+Cs*(k*I+N*C);H<u&&(o=m,u=H,a=P.candidate)}}else{for(let S=0;S<Et;S++){const M=Mt[S];M.count=0,M.candidate=w+A+S*A;const P=M.bounds;for(let I=0;I<3;I++)P[I]=1/0,P[I+3]=-1/0}for(let S=h;S<f;S+=6){let I=~~((t[S+2*m]-w)/A);I>=Et&&(I=Et-1);const C=Mt[I];C.count++,Hn(S,t,C.bounds)}const T=Mt[Et-1];ji(T.bounds,T.rightCacheBounds);for(let S=Et-2;S>=0;S--){const M=Mt[S],P=Mt[S+1];Wi(M.bounds,P.rightCacheBounds,M.rightCacheBounds)}let x=0;for(let S=0;S<Et-1;S++){const M=Mt[S],P=M.count,I=M.bounds,D=Mt[S+1].rightCacheBounds;P!==0&&(x===0?ji(I,Gn):Wi(I,Gn,Gn)),x+=P;let L=0,k=0;x!==0&&(L=un(Gn)/c);const N=s-x;N!==0&&(k=un(D)/c);const H=Hi+Cs*(L*x+k*N);H<u&&(o=m,u=H,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function fa(i,e,t,n){let s=0;const r=i.offset;for(let o=e,a=e+t;o<a;o++)s+=i[(o-r)*6+n*2];return s/t}class Ls{constructor(){this.boundingData=new Float32Array(6)}}function pa(i,e,t,n,s,r){let o=n,a=n+s-1;const c=r.pos,u=r.axis*2,d=t.offset||0;for(;;){for(;o<=a&&t[(o-d)*6+u]<c;)o++;for(;o<=a&&t[(a-d)*6+u]>=c;)a--;if(o<a){for(let h=0;h<e;h++){let f=i[o*e+h];i[o*e+h]=i[a*e+h],i[a*e+h]=f}for(let h=0;h<6;h++){const f=o-d,m=a-d,w=t[f*6+h];t[f*6+h]=t[m*6+h],t[m*6+h]=w}o++,a--}else return o}}let Dr,ds,Js,Nr;const ma=Math.pow(2,32);function ei(i){return"count"in i?1:1+ei(i.left)+ei(i.right)}function ga(i,e,t){return Dr=new Float32Array(t),ds=new Uint32Array(t),Js=new Uint16Array(t),Nr=new Uint8Array(t),ti(i,e)}function ti(i,e){const t=i/4,n=i/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Dr[t+o]=r[o];if(s)return e.buffer?(Nr.set(new Uint8Array(e.buffer),i),i+e.buffer.byteLength):(ds[t+6]=e.offset,Js[n+14]=e.count,Js[n+15]=wi,i+He);{const{left:o,right:a,splitAxis:c}=e,u=i+He;let d=ti(u,o);const h=i/He,m=d/He-h;if(m>ma)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ds[t+6]=m,ds[t+7]=c,ti(d,a)}}function ya(i,e,t,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:c,strategy:u,onProgress:d}=s,h=i.primitiveBuffer,f=i.primitiveBufferStride,m=new Float32Array(6);let w=!1;const b=new Ls;return Is(e,t,n,b.boundingData,m),A(b,t,n,m),b;function _(T){d&&d((T-r.offset)/r.count)}function A(T,x,S,M=null,P=0){if(!w&&P>=o&&(w=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`)),S<=c||P>=o)return _(x+S),T.offset=x,T.count=S,T;const I=da(T.boundingData,M,e,x,S,u);if(I.axis===-1)return _(x+S),T.offset=x,T.count=S,T;const C=pa(h,f,e,x,S,I);if(C===x||C===x+S)_(x+S),T.offset=x,T.count=S;else{T.splitAxis=I.axis;const D=new Ls,L=x,k=C-x;T.left=D,Is(e,L,k,D.boundingData,m),A(D,L,k,m,P+1);const N=new Ls,H=C,j=S-k;T.right=N,Is(e,H,j,N.boundingData,m),A(N,H,j,m,P+1)}return T}}function wa(i,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=i.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,i.computePrimitiveBounds(o.offset,o.count,a),i._roots=n.map(c=>{const u=ya(i,a,c.offset,c.count,e,o),d=ei(u),h=new t(He*d);return ga(0,u,h),h})}class Ti{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Ea{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=n=>{t&&e.push(t),t=n,this.float32Array=new Float32Array(n),this.uint16Array=new Uint16Array(n),this.uint32Array=new Uint32Array(n)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const be=new Ea;let Lt,nn;const jt=[],jn=new Ti(()=>new p.Box3);function Ta(i,e,t,n,s,r){Lt=jn.getPrimitive(),nn=jn.getPrimitive(),jt.push(Lt,nn),be.setBuffer(i._roots[e]);const o=ni(0,i.geometry,t,n,s,r);be.clearBuffer(),jn.releasePrimitive(Lt),jn.releasePrimitive(nn),jt.pop(),jt.pop();const a=jt.length;return a>0&&(nn=jt[a-1],Lt=jt[a-2]),o}function ni(i,e,t,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:c,uint32Array:u}=be;let d=i*2;if(Ie(d,c)){const f=Ge(i,u),m=Xe(d,c);return Ae(i,a,Lt),n(f,m,!1,o,r+i/Ne,Lt)}else{let L=function(N){const{uint16Array:H,uint32Array:j}=be;let $=N*2;for(;!Ie($,H);)N=Be(N),$=N*2;return Ge(N,j)},k=function(N){const{uint16Array:H,uint32Array:j}=be;let $=N*2;for(;!Ie($,H);)N=ze(N,j),$=N*2;return Ge(N,j)+Xe($,H)};const f=Be(i),m=ze(i,u);let w=f,b=m,_,A,T,x;if(s&&(T=Lt,x=nn,Ae(w,a,T),Ae(b,a,x),_=s(T),A=s(x),A<_)){w=m,b=f;const N=_;_=A,A=N,T=x}T||(T=Lt,Ae(w,a,T));const S=Ie(w*2,c),M=t(T,S,_,o+1,r+w/Ne);let P;if(M===Vi){const N=L(w),j=k(w)-N;P=n(N,j,!0,o+1,r+w/Ne,T)}else P=M&&ni(w,e,t,n,s,r,o+1);if(P)return!0;x=nn,Ae(b,a,x);const I=Ie(b*2,c),C=t(x,I,A,o+1,r+b/Ne);let D;if(C===Vi){const N=L(b),j=k(b)-N;D=n(N,j,!0,o+1,r+b/Ne,x)}else D=C&&ni(b,e,t,n,s,r,o+1);return!!D}}const Sn=new be.constructor,ms=new be.constructor,Ct=new Ti(()=>new p.Box3),Wt=new p.Box3,Zt=new p.Box3,Ps=new p.Box3,Os=new p.Box3;let Ds=!1;function Sa(i,e,t,n){if(Ds)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ds=!0;const s=i._roots,r=e._roots;let o,a=0,c=0;const u=new p.Matrix4().copy(t).invert();for(let d=0,h=s.length;d<h;d++){Sn.setBuffer(s[d]),c=0;const f=Ct.getPrimitive();Ae(0,Sn.float32Array,f),f.applyMatrix4(u);for(let m=0,w=r.length;m<w&&(ms.setBuffer(r[m]),o=ht(0,0,t,u,n,a,c,0,0,f),ms.clearBuffer(),c+=r[m].byteLength/He,!o);m++);if(Ct.releasePrimitive(f),Sn.clearBuffer(),a+=s[d].byteLength/He,o)break}return Ds=!1,o}function ht(i,e,t,n,s,r=0,o=0,a=0,c=0,u=null,d=!1){let h,f;d?(h=ms,f=Sn):(h=Sn,f=ms);const m=h.float32Array,w=h.uint32Array,b=h.uint16Array,_=f.float32Array,A=f.uint32Array,T=f.uint16Array,x=i*2,S=e*2,M=Ie(x,b),P=Ie(S,T);let I=!1;if(P&&M)d?I=s(Ge(e,A),Xe(e*2,T),Ge(i,w),Xe(i*2,b),c,o+e/Ne,a,r+i/Ne):I=s(Ge(i,w),Xe(i*2,b),Ge(e,A),Xe(e*2,T),a,r+i/Ne,c,o+e/Ne);else if(P){const C=Ct.getPrimitive();Ae(e,_,C),C.applyMatrix4(t);const D=Be(i),L=ze(i,w);Ae(D,m,Wt),Ae(L,m,Zt);const k=C.intersectsBox(Wt),N=C.intersectsBox(Zt);I=k&&ht(e,D,n,t,s,o,r,c,a+1,C,!d)||N&&ht(e,L,n,t,s,o,r,c,a+1,C,!d),Ct.releasePrimitive(C)}else{const C=Be(e),D=ze(e,A);Ae(C,_,Ps),Ae(D,_,Os);const L=u.intersectsBox(Ps),k=u.intersectsBox(Os);if(L&&k)I=ht(i,C,t,n,s,r,o,a,c+1,u,d)||ht(i,D,t,n,s,r,o,a,c+1,u,d);else if(L)if(M)I=ht(i,C,t,n,s,r,o,a,c+1,u,d);else{const N=Ct.getPrimitive();N.copy(Ps).applyMatrix4(t);const H=Be(i),j=ze(i,w);Ae(H,m,Wt),Ae(j,m,Zt);const $=N.intersectsBox(Wt),re=N.intersectsBox(Zt);I=$&&ht(C,H,n,t,s,o,r,c,a+1,N,!d)||re&&ht(C,j,n,t,s,o,r,c,a+1,N,!d),Ct.releasePrimitive(N)}else if(k)if(M)I=ht(i,D,t,n,s,r,o,a,c+1,u,d);else{const N=Ct.getPrimitive();N.copy(Os).applyMatrix4(t);const H=Be(i),j=ze(i,w);Ae(H,m,Wt),Ae(j,m,Zt);const $=N.intersectsBox(Wt),re=N.intersectsBox(Zt);I=$&&ht(D,H,n,t,s,o,r,c,a+1,N,!d)||re&&ht(D,j,n,t,s,o,r,c,a+1,N,!d),Ct.releasePrimitive(N)}}return I}const Zi=new p.Box3,Kt=new Float32Array(6);class _a{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Or,...e},wa(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,s){let r=1/0,o=1/0,a=1/0,c=-1/0,u=-1/0,d=-1/0;for(let h=e,f=e+t;h<f;h++){this.writePrimitiveBounds(h,Kt,0);const[m,w,b,_,A,T]=Kt;m<r&&(r=m),_>c&&(c=_),w<o&&(o=w),A>u&&(u=A),b<a&&(a=b),T>d&&(d=T)}return n[s+0]=r,n[s+1]=o,n[s+2]=a,n[s+3]=c,n[s+4]=u,n[s+5]=d,n}computePrimitiveBounds(e,t,n){const s=n.offset||0;for(let r=e,o=e+t;r<o;r++){this.writePrimitiveBounds(r,Kt,0);const[a,c,u,d,h,f]=Kt,m=(a+d)/2,w=(c+h)/2,b=(u+f)/2,_=(d-a)/2,A=(h-c)/2,T=(f-u)/2,x=(r-s)*6;n[x+0]=m,n[x+1]=_+(Math.abs(m)+_)*us,n[x+2]=w,n[x+3]=A+(Math.abs(w)+A)*us,n[x+4]=b,n[x+5]=T+(Math.abs(b)+T)*us}return n}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,s=t.length;n<s;n++)t[n]+=e;else{const n=this._roots;for(let s=0;s<n.length;s++){const r=n[s],o=new Uint32Array(r),a=new Uint16Array(r),c=r.byteLength/He;for(let u=0;u<c;u++){const d=Ne*u,h=2*d;Ie(h,a)&&(o[d+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],s=new Uint32Array(n),r=new Uint16Array(n);o(0);function o(a,c=0){const u=a*2,d=Ie(u,r);if(d){const h=s[a+6],f=r[u+14];e(c,d,new Float32Array(n,a*4,6),h,f)}else{const h=Be(a),f=ze(a,s),m=Ts(a,s);e(c,d,new Float32Array(n,a*4,6),m)||(o(h,c+1),o(f,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const s=e[t],r=new Uint32Array(s),o=new Uint16Array(s),a=new Float32Array(s),c=s.byteLength/He;for(let u=c-1;u>=0;u--){const d=u*Ne,h=d*2;if(Ie(h,o)){const m=Ge(d,r),w=Xe(h,o);this.writePrimitiveRangeBounds(m,w,Kt,0),a.set(Kt,d)}else{const m=Be(d),w=ze(d,r);for(let b=0;b<3;b++){const _=a[m+b],A=a[m+b+3],T=a[w+b],x=a[w+b+3];a[d+b]=_<T?_:T,a[d+b+3]=A>x?A:x}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{Ae(0,new Float32Array(n),Zi),e.union(Zi)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:s,intersectsPrimitive:r,scratchPrimitive:o,iterate:a}=e;if(s&&r){const h=s;s=(f,m,w,b,_)=>h(f,m,w,b,_)?!0:a(f,m,this,r,w,b,o)}else s||(r?s=(h,f,m,w)=>a(h,f,this,r,m,w,o):s=(h,f,m)=>m);let c=!1,u=0;const d=this._roots;for(let h=0,f=d.length;h<f;h++){const m=d[h];if(c=Ta(this,h,n,s,t,u),c)break;u+=m.byteLength/He}return c}bvhcast(e,t,n){let{intersectsRanges:s}=n;return Sa(this,e,t,s)}}function ba(){return typeof SharedArrayBuffer<"u"}function Ss(i){return i.index?i.index.count:i.attributes.position.count}function _s(i){return Ss(i)/3}function kr(i,e=ArrayBuffer){return i>65535?new Uint32Array(new e(4*i)):new Uint16Array(new e(2*i))}function xa(i,e){if(!i.index){const t=i.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=kr(t,n);i.setIndex(new p.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function Aa(i,e,t){const n=Ss(i)/t,s=e||i.drawRange,r=s.start/t,o=(s.start+s.count)/t,a=Math.max(0,r),c=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function Ma(i,e){return i.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Ki(i,e,t){const n=Aa(i,e,t),s=Ma(i,t);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,c=Ss(i)/t,u=[];for(const f of s){const{offset:m,count:w}=f,b=m,_=isFinite(w)?w:c-m,A=m+_;b<a&&A>o&&(u.push({pos:Math.max(o,b),isStart:!0}),u.push({pos:Math.min(a,A),isStart:!1}))}u.sort((f,m)=>f.pos!==m.pos?f.pos-m.pos:f.type==="end"?-1:1);let d=0,h=null;for(const f of u){const m=f.pos;d!==0&&m!==h&&r.push({offset:h,count:m-h}),d+=f.isStart?1:-1,h=m}return r}function Ra(i,e){const t=i[i.length-1],n=t.offset+t.count>2**16,s=i.reduce((u,d)=>u+d.count,0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let c=0;for(let u=0;u<i.length;u++){const{offset:d,count:h}=i[u];for(let f=0;f<h;f++)a[c+f]=d+f;c+=h}return a}class va extends _a{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(t.useSharedArrayBuffer&&!ba())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?n=>this._indirectBuffer[n]:n=>n,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,t={...Or,...t},t[Ei]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=Ki(t,e.range,n),r=Ra(s,e.useSharedArrayBuffer);this._indirectBuffer=r}else xa(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new p.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Ki(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class bt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const c=e[r][t];n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}setFromPoints(e,t){let n=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],c=e.dot(a);n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}bt.prototype.setFromBox=(function(){const i=new p.Vector3;return function(t,n){const s=n.min,r=n.max;let o=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)for(let d=0;d<=1;d++){i.x=s.x*c+r.x*(1-c),i.y=s.y*u+r.y*(1-u),i.z=s.z*d+r.z*(1-d);const h=t.dot(i);o=Math.min(h,o),a=Math.max(h,a)}this.min=o,this.max=a}})();const Ca=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Vector3;return function(s,r,o){const a=s.start,c=i,u=r.start,d=e;t.subVectors(a,u),i.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const h=t.dot(d),f=d.dot(c),m=d.dot(d),w=t.dot(c),_=c.dot(c)*m-f*f;let A,T;_!==0?A=(h*f-w*m)/_:A=0,T=(h+A*f)/m,o.x=A,o.y=T}})(),Si=(function(){const i=new p.Vector2,e=new p.Vector3,t=new p.Vector3;return function(s,r,o,a){Ca(s,r,i);let c=i.x,u=i.y;if(c>=0&&c<=1&&u>=0&&u<=1){s.at(c,o),r.at(u,a);return}else if(c>=0&&c<=1){u<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(u>=0&&u<=1){c<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let d;c<0?d=s.start:d=s.end;let h;u<0?h=r.start:h=r.end;const f=e,m=t;if(s.closestPointToPoint(h,!0,e),r.closestPointToPoint(d,!0,t),f.distanceToSquared(h)<=m.distanceToSquared(d)){o.copy(f),a.copy(h);return}else{o.copy(d),a.copy(m);return}}}})(),Ia=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Plane,n=new p.Line3;return function(r,o){const{radius:a,center:c}=r,{a:u,b:d,c:h}=o;if(n.start=u,n.end=d,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a||(n.start=u,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a)||(n.start=d,n.end=h,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a))return!0;const b=o.getPlane(t);if(Math.abs(b.distanceToPoint(c))<=a){const A=b.projectPoint(c,e);if(o.containsPoint(A))return!0}return!1}})(),La=["x","y","z"],Tt=1e-15,Xi=Tt*Tt;function nt(i){return Math.abs(i)<Tt}class dt extends p.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new p.Vector3),this.satBounds=new Array(4).fill().map(()=>new bt),this.points=[this.a,this.b,this.c],this.plane=new p.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new p.Line3,this.needsUpdate=!0}intersectsSphere(e){return Ia(e,this)}update(){const e=this.a,t=this.b,n=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],c=o[0];this.getNormal(a),c.setFromPoints(a,s);const u=r[1],d=o[1];u.subVectors(e,t),d.setFromPoints(u,s);const h=r[2],f=o[2];h.subVectors(t,n),f.setFromPoints(h,s);const m=r[3],w=o[3];m.subVectors(n,e),w.setFromPoints(m,s);const b=u.length(),_=h.length(),A=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,b<Tt?_<Tt||A<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):_<Tt?A<Tt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<Tt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}dt.prototype.closestPointToSegment=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Line3;return function(s,r=null,o=null){const{start:a,end:c}=s,u=this.points;let d,h=1/0;for(let f=0;f<3;f++){const m=(f+1)%3;t.start.copy(u[f]),t.end.copy(u[m]),Si(t,s,i,e),d=i.distanceToSquared(e),d<h&&(h=d,r&&r.copy(i),o&&o.copy(e))}return this.closestPointToPoint(a,i),d=a.distanceToSquared(i),d<h&&(h=d,r&&r.copy(i),o&&o.copy(a)),this.closestPointToPoint(c,i),d=c.distanceToSquared(i),d<h&&(h=d,r&&r.copy(i),o&&o.copy(c)),Math.sqrt(h)}})();dt.prototype.intersectsTriangle=(function(){const i=new dt,e=new bt,t=new bt,n=new p.Vector3,s=new p.Vector3,r=new p.Vector3,o=new p.Vector3,a=new p.Line3,c=new p.Line3,u=new p.Vector3,d=new p.Vector2,h=new p.Vector2;function f(x,S,M,P){const I=n;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?I.copy(x.plane.normal):I.copy(S.plane.normal);const C=x.satBounds,D=x.satAxes;for(let N=1;N<4;N++){const H=C[N],j=D[N];if(e.setFromPoints(j,S.points),H.isSeparated(e)||(o.copy(I).cross(j),e.setFromPoints(o,x.points),t.setFromPoints(o,S.points),e.isSeparated(t)))return!1}const L=S.satBounds,k=S.satAxes;for(let N=1;N<4;N++){const H=L[N],j=k[N];if(e.setFromPoints(j,x.points),H.isSeparated(e)||(o.crossVectors(I,j),e.setFromPoints(o,x.points),t.setFromPoints(o,S.points),e.isSeparated(t)))return!1}return M&&(P||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),M.start.set(0,0,0),M.end.set(0,0,0)),!0}function m(x,S,M,P,I,C,D,L,k,N,H){let j=D/(D-L);N.x=P+(I-P)*j,H.start.subVectors(S,x).multiplyScalar(j).add(x),j=D/(D-k),N.y=P+(C-P)*j,H.end.subVectors(M,x).multiplyScalar(j).add(x)}function w(x,S,M,P,I,C,D,L,k,N,H){if(I>0)m(x.c,x.a,x.b,P,S,M,k,D,L,N,H);else if(C>0)m(x.b,x.a,x.c,M,S,P,L,D,k,N,H);else if(L*k>0||D!=0)m(x.a,x.b,x.c,S,M,P,D,L,k,N,H);else if(L!=0)m(x.b,x.a,x.c,M,S,P,L,D,k,N,H);else if(k!=0)m(x.c,x.a,x.b,P,S,M,k,D,L,N,H);else return!0;return!1}function b(x,S,M,P){const I=S.degenerateSegment,C=x.plane.distanceToPoint(I.start),D=x.plane.distanceToPoint(I.end);return nt(C)?nt(D)?f(x,S,M,P):(M&&(M.start.copy(I.start),M.end.copy(I.start)),x.containsPoint(I.start)):nt(D)?(M&&(M.start.copy(I.end),M.end.copy(I.end)),x.containsPoint(I.end)):x.plane.intersectLine(I,n)!=null?(M&&(M.start.copy(n),M.end.copy(n)),x.containsPoint(n)):!1}function _(x,S,M){const P=S.a;return nt(x.plane.distanceToPoint(P))&&x.containsPoint(P)?(M&&(M.start.copy(P),M.end.copy(P)),!0):!1}function A(x,S,M){const P=x.degenerateSegment,I=S.a;return P.closestPointToPoint(I,!0,n),I.distanceToSquared(n)<Xi?(M&&(M.start.copy(I),M.end.copy(I)),!0):!1}function T(x,S,M,P){if(x.isDegenerateIntoSegment)if(S.isDegenerateIntoSegment){const I=x.degenerateSegment,C=S.degenerateSegment,D=s,L=r;I.delta(D),C.delta(L);const k=n.subVectors(C.start,I.start),N=D.x*L.y-D.y*L.x;if(nt(N))return!1;const H=(k.x*L.y-k.y*L.x)/N,j=-(D.x*k.y-D.y*k.x)/N;if(H<0||H>1||j<0||j>1)return!1;const $=I.start.z+D.z*H,re=C.start.z+L.z*j;return nt($-re)?(M&&(M.start.copy(I.start).addScaledVector(D,H),M.end.copy(I.start).addScaledVector(D,H)),!0):!1}else return S.isDegenerateIntoPoint?A(x,S,M):b(S,x,M,P);else{if(x.isDegenerateIntoPoint)return S.isDegenerateIntoPoint?S.a.distanceToSquared(x.a)<Xi?(M&&(M.start.copy(x.a),M.end.copy(x.a)),!0):!1:S.isDegenerateIntoSegment?A(S,x,M):_(S,x,M);if(S.isDegenerateIntoPoint)return _(x,S,M);if(S.isDegenerateIntoSegment)return b(x,S,M,P)}}return function(S,M=null,P=!1){this.needsUpdate&&this.update(),S.isExtendedTriangle?S.needsUpdate&&S.update():(i.copy(S),i.update(),S=i);const I=T(this,S,M,P);if(I!==void 0)return I;const C=this.plane,D=S.plane;let L=D.distanceToPoint(this.a),k=D.distanceToPoint(this.b),N=D.distanceToPoint(this.c);nt(L)&&(L=0),nt(k)&&(k=0),nt(N)&&(N=0);const H=L*k,j=L*N;if(H>0&&j>0)return!1;let $=C.distanceToPoint(S.a),re=C.distanceToPoint(S.b),ke=C.distanceToPoint(S.c);nt($)&&($=0),nt(re)&&(re=0),nt(ke)&&(ke=0);const ot=$*re,ve=$*ke;if(ot>0&&ve>0)return!1;s.copy(C.normal),r.copy(D.normal);const Ue=s.cross(r);let je=0,Me=Math.abs(Ue.x);const ye=Math.abs(Ue.y);ye>Me&&(Me=ye,je=1),Math.abs(Ue.z)>Me&&(je=2);const We=La[je],xt=this.a[We],ge=this.b[We],at=this.c[We],ct=S.a[We],an=S.b[We],Vt=S.c[We];if(w(this,xt,ge,at,H,j,L,k,N,d,a))return f(this,S,M,P);if(w(S,ct,an,Vt,ot,ve,$,re,ke,h,c))return f(this,S,M,P);if(d.y<d.x){const wt=d.y;d.y=d.x,d.x=wt,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(h.y<h.x){const wt=h.y;h.y=h.x,h.x=wt,u.copy(c.start),c.start.copy(c.end),c.end.copy(u)}return d.y<h.x||h.y<d.x?!1:(M&&(h.x>d.x?M.start.copy(c.start):M.start.copy(a.start),h.y<d.y?M.end.copy(c.end):M.end.copy(a.end)),!0)}})();dt.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();dt.prototype.distanceToTriangle=(function(){const i=new p.Vector3,e=new p.Vector3,t=["a","b","c"],n=new p.Line3,s=new p.Line3;return function(o,a=null,c=null){const u=a||c?n:null;if(this.intersectsTriangle(o,u,!0))return(a||c)&&(a&&u.getCenter(a),c&&u.getCenter(c)),0;let d=1/0;for(let h=0;h<3;h++){let f;const m=t[h],w=o[m];this.closestPointToPoint(w,i),f=w.distanceToSquared(i),f<d&&(d=f,a&&a.copy(i),c&&c.copy(w));const b=this[m];o.closestPointToPoint(b,i),f=b.distanceToSquared(i),f<d&&(d=f,a&&a.copy(b),c&&c.copy(i))}for(let h=0;h<3;h++){const f=t[h],m=t[(h+1)%3];n.set(this[f],this[m]);for(let w=0;w<3;w++){const b=t[w],_=t[(w+1)%3];s.set(o[b],o[_]),Si(n,s,i,e);const A=i.distanceToSquared(e);A<d&&(d=A,a&&a.copy(i),c&&c.copy(e))}}return Math.sqrt(d)}})();class Ye{constructor(e,t,n){this.isOrientedBox=!0,this.min=new p.Vector3,this.max=new p.Vector3,this.matrix=new p.Matrix4,this.invMatrix=new p.Matrix4,this.points=new Array(8).fill().map(()=>new p.Vector3),this.satAxes=new Array(3).fill().map(()=>new p.Vector3),this.satBounds=new Array(3).fill().map(()=>new bt),this.alignedSatBounds=new Array(3).fill().map(()=>new bt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ye.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,s=this.points;for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)for(let h=0;h<=1;h++){const f=1*u|2*d|4*h,m=s[f];m.x=u?n.x:t.x,m.y=d?n.y:t.y,m.z=h?n.z:t.z,m.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let u=0;u<3;u++){const d=o[u],h=r[u],f=1<<u,m=s[f];d.subVectors(a,m),h.setFromPoints(d,s)}const c=this.alignedSatBounds;c[0].setFromPointsField(s,"x"),c[1].setFromPointsField(s,"y"),c[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();Ye.prototype.intersectsBox=(function(){const i=new bt;return function(t){this.needsUpdate&&this.update();const n=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(i.min=n.x,i.max=s.x,a[0].isSeparated(i)||(i.min=n.y,i.max=s.y,a[1].isSeparated(i))||(i.min=n.z,i.max=s.z,a[2].isSeparated(i)))return!1;for(let c=0;c<3;c++){const u=o[c],d=r[c];if(i.setFromBox(u,t),d.isSeparated(i))return!1}return!0}})();Ye.prototype.intersectsTriangle=(function(){const i=new dt,e=new Array(3),t=new bt,n=new bt,s=new p.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(i.copy(o),i.update(),o=i);const a=this.satBounds,c=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const m=a[f],w=c[f];if(t.setFromPoints(w,e),m.isSeparated(t))return!1}const u=o.satBounds,d=o.satAxes,h=this.points;for(let f=0;f<3;f++){const m=u[f],w=d[f];if(t.setFromPoints(w,h),m.isSeparated(t))return!1}for(let f=0;f<3;f++){const m=c[f];for(let w=0;w<4;w++){const b=d[w];if(s.crossVectors(m,b),t.setFromPoints(s,e),n.setFromPoints(s,h),t.isSeparated(n))return!1}}return!0}})();Ye.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();Ye.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();Ye.prototype.distanceToBox=(function(){const i=["x","y","z"],e=new Array(12).fill().map(()=>new p.Line3),t=new Array(12).fill().map(()=>new p.Line3),n=new p.Vector3,s=new p.Vector3;return function(o,a=0,c=null,u=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(c||u)&&(o.getCenter(s),this.closestPointToPoint(s,n),o.closestPointToPoint(n,s),c&&c.copy(n),u&&u.copy(s)),0;const d=a*a,h=o.min,f=o.max,m=this.points;let w=1/0;for(let _=0;_<8;_++){const A=m[_];s.copy(A).clamp(h,f);const T=A.distanceToSquared(s);if(T<w&&(w=T,c&&c.copy(A),u&&u.copy(s),T<d))return Math.sqrt(T)}let b=0;for(let _=0;_<3;_++)for(let A=0;A<=1;A++)for(let T=0;T<=1;T++){const x=(_+1)%3,S=(_+2)%3,M=A<<x|T<<S,P=1<<_|A<<x|T<<S,I=m[M],C=m[P];e[b].set(I,C);const L=i[_],k=i[x],N=i[S],H=t[b],j=H.start,$=H.end;j[L]=h[L],j[k]=A?h[k]:f[k],j[N]=T?h[N]:f[k],$[L]=f[L],$[k]=A?h[k]:f[k],$[N]=T?h[N]:f[k],b++}for(let _=0;_<=1;_++)for(let A=0;A<=1;A++)for(let T=0;T<=1;T++){s.x=_?f.x:h.x,s.y=A?f.y:h.y,s.z=T?f.z:h.z,this.closestPointToPoint(s,n);const x=s.distanceToSquared(n);if(x<w&&(w=x,c&&c.copy(n),u&&u.copy(s),x<d))return Math.sqrt(x)}for(let _=0;_<12;_++){const A=e[_];for(let T=0;T<12;T++){const x=t[T];Si(A,x,n,s);const S=n.distanceToSquared(s);if(S<w&&(w=S,c&&c.copy(n),u&&u.copy(s),S<d))return Math.sqrt(S)}}return Math.sqrt(w)}})();class Pa extends Ti{constructor(){super(()=>new dt)}}const rt=new Pa,dn=new p.Vector3,Ns=new p.Vector3;function Oa(i,e,t={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,c=null;if(i.shapecast({boundsTraverseOrder:d=>(dn.copy(e).clamp(d.min,d.max),dn.distanceToSquared(e)),intersectsBounds:(d,h,f)=>f<a&&f<o,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,dn);const f=e.distanceToSquared(dn);return f<a&&(Ns.copy(dn),a=f,c=h),f<r}}),a===1/0)return null;const u=Math.sqrt(a);return t.point?t.point.copy(Ns):t.point=Ns.clone(),t.distance=u,t.faceIndex=c,t}const Wn=parseInt(p.REVISION)>=169,Da=parseInt(p.REVISION)<=161,Nt=new p.Vector3,kt=new p.Vector3,Ft=new p.Vector3,Zn=new p.Vector2,Kn=new p.Vector2,Xn=new p.Vector2,Yi=new p.Vector3,qi=new p.Vector3,$i=new p.Vector3,fn=new p.Vector3;function Na(i,e,t,n,s,r,o,a){let c;if(r===p.BackSide?c=i.intersectTriangle(n,t,e,!0,s):c=i.intersectTriangle(e,t,n,r!==p.DoubleSide,s),c===null)return null;const u=i.origin.distanceTo(s);return u<o||u>a?null:{distance:u,point:s.clone()}}function Qi(i,e,t,n,s,r,o,a,c,u,d){Nt.fromBufferAttribute(e,r),kt.fromBufferAttribute(e,o),Ft.fromBufferAttribute(e,a);const h=Na(i,Nt,kt,Ft,fn,c,u,d);if(h){if(n){Zn.fromBufferAttribute(n,r),Kn.fromBufferAttribute(n,o),Xn.fromBufferAttribute(n,a),h.uv=new p.Vector2;const m=p.Triangle.getInterpolation(fn,Nt,kt,Ft,Zn,Kn,Xn,h.uv);Wn||(h.uv=m)}if(s){Zn.fromBufferAttribute(s,r),Kn.fromBufferAttribute(s,o),Xn.fromBufferAttribute(s,a),h.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(fn,Nt,kt,Ft,Zn,Kn,Xn,h.uv1);Wn||(h.uv1=m),Da&&(h.uv2=h.uv1)}if(t){Yi.fromBufferAttribute(t,r),qi.fromBufferAttribute(t,o),$i.fromBufferAttribute(t,a),h.normal=new p.Vector3;const m=p.Triangle.getInterpolation(fn,Nt,kt,Ft,Yi,qi,$i,h.normal);h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1),Wn||(h.normal=m)}const f={a:r,b:o,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(Nt,kt,Ft,f.normal),h.face=f,h.faceIndex=r,Wn){const m=new p.Vector3;p.Triangle.getBarycoord(fn,Nt,kt,Ft,m),h.barycoord=m}}return h}function Ji(i){return i&&i.isMaterial?i.side:i}function bs(i,e,t,n,s,r,o){const a=n*3;let c=a+0,u=a+1,d=a+2;const{index:h,groups:f}=i;i.index&&(c=h.getX(c),u=h.getX(u),d=h.getX(d));const{position:m,normal:w,uv:b,uv1:_}=i.attributes;if(Array.isArray(e)){const A=n*3;for(let T=0,x=f.length;T<x;T++){const{start:S,count:M,materialIndex:P}=f[T];if(A>=S&&A<S+M){const I=Ji(e[P]),C=Qi(t,m,w,b,_,c,u,d,I,r,o);if(C)if(C.faceIndex=n,C.face.materialIndex=P,s)s.push(C);else return C}}}else{const A=Ji(e),T=Qi(t,m,w,b,_,c,u,d,A,r,o);if(T)if(T.faceIndex=n,T.face.materialIndex=0,s)s.push(T);else return T}return null}function Le(i,e,t,n){const s=i.a,r=i.b,o=i.c;let a=e,c=e+1,u=e+2;t&&(a=t.getX(a),c=t.getX(c),u=t.getX(u)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(c),r.y=n.getY(c),r.z=n.getZ(c),o.x=n.getX(u),o.y=n.getY(u),o.z=n.getZ(u)}function ka(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++)bs(c,e,t,d,r,o,a)}function Fa(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let u=1/0,d=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,h,null,r,o),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ba(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=i,h=e+i;d<h;d++){let f;if(f=d,Le(o,f*3,c,u),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function za(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)r=d[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,u),u+=r.byteLength;function h(f,m,w=!1){const b=f*2;if(Ie(b,a)){const _=Ge(f,o),A=Xe(b,a);let T=1/0,x=1/0,S=1/0,M=-1/0,P=-1/0,I=-1/0;for(let C=3*_,D=3*(_+A);C<D;C++){let L=n[C];const k=s.getX(L),N=s.getY(L),H=s.getZ(L);k<T&&(T=k),k>M&&(M=k),N<x&&(x=N),N>P&&(P=N),H<S&&(S=H),H>I&&(I=H)}return c[f+0]!==T||c[f+1]!==x||c[f+2]!==S||c[f+3]!==M||c[f+4]!==P||c[f+5]!==I?(c[f+0]=T,c[f+1]=x,c[f+2]=S,c[f+3]=M,c[f+4]=P,c[f+5]=I,!0):!1}else{const _=Be(f),A=ze(f,o);let T=w,x=!1,S=!1;if(e){if(!T){const L=_/Ne+m/He,k=A/Ne+m/He;x=e.has(L),S=e.has(k),T=!x&&!S}}else x=!0,S=!0;const M=T||x,P=T||S;let I=!1;M&&(I=h(_,m,T));let C=!1;P&&(C=h(A,m,T));const D=I||C;if(D)for(let L=0;L<3;L++){const k=_+L,N=A+L,H=c[k],j=c[k+3],$=c[N],re=c[N+3];c[f+L]=H<$?H:$,c[f+L+3]=j>re?j:re}return D}}}function Ot(i,e,t,n,s){let r,o,a,c,u,d;const h=1/t.direction.x,f=1/t.direction.y,m=1/t.direction.z,w=t.origin.x,b=t.origin.y,_=t.origin.z;let A=e[i],T=e[i+3],x=e[i+1],S=e[i+3+1],M=e[i+2],P=e[i+3+2];return h>=0?(r=(A-w)*h,o=(T-w)*h):(r=(T-w)*h,o=(A-w)*h),f>=0?(a=(x-b)*f,c=(S-b)*f):(a=(S-b)*f,c=(x-b)*f),r>c||a>o||((a>r||isNaN(r))&&(r=a),(c<o||isNaN(o))&&(o=c),m>=0?(u=(M-_)*m,d=(P-_)*m):(u=(P-_)*m,d=(M-_)*m),r>d||u>o)?!1:((u>r||r!==r)&&(r=u),(d<o||o!==o)&&(o=d),r<=s&&o>=n)}function Ua(i,e,t,n,s,r,o,a){const{geometry:c,_indirectBuffer:u}=i;for(let d=n,h=n+s;d<h;d++){let f=u?u[d]:d;bs(c,e,t,f,r,o,a)}}function Va(i,e,t,n,s,r,o){const{geometry:a,_indirectBuffer:c}=i;let u=1/0,d=null;for(let h=n,f=n+s;h<f;h++){let m;m=bs(a,e,t,c?c[h]:h,null,r,o),m&&m.distance<u&&(d=m,u=m.distance)}return d}function Ha(i,e,t,n,s,r,o){const{geometry:a}=t,{index:c}=a,u=a.attributes.position;for(let d=i,h=e+i;d<h;d++){let f;if(f=t.resolveTriangleIndex(d),Le(o,f*3,c,u),o.needsUpdate=!0,n(o,f,s,r))return!0}return!1}function Ga(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),si(0,i,t,n,s,r,o),be.clearBuffer()}function si(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ie(d,c)){const f=Ge(i,u),m=Xe(d,c);ka(e,t,n,f,m,s,r,o)}else{const f=Be(i);Ot(f,a,n,r,o)&&si(f,e,t,n,s,r,o);const m=ze(i,u);Ot(m,a,n,r,o)&&si(m,e,t,n,s,r,o)}}const ja=["x","y","z"];function Wa(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=ii(0,i,t,n,s,r);return be.clearBuffer(),o}function ii(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ie(u,a)){const h=Ge(i,c),f=Xe(u,a);return Fa(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=ja[h],w=n.direction[f]>=0;let b,_;w?(b=Be(i),_=ze(i,c)):(b=ze(i,c),_=Be(i));const T=Ot(b,o,n,s,r)?ii(b,e,t,n,s,r):null;if(T){const M=T.point[f];if(w?M<=o[_+h]:M>=o[_+h+3])return T}const S=Ot(_,o,n,s,r)?ii(_,e,t,n,s,r):null;return T&&S?T.distance<=S.distance?T:S:T||S||null}}const Yn=new p.Box3,Xt=new dt,Yt=new dt,pn=new p.Matrix4,er=new Ye,qn=new Ye;function Za(i,e,t,n){be.setBuffer(i._roots[e]);const s=ri(0,i,t,n);return be.clearBuffer(),s}function ri(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),er.set(t.boundingBox.min,t.boundingBox.max,n),s=er),Ie(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,b=Ge(i,a),_=Xe(c,o);if(pn.copy(n).invert(),t.boundsTree)return Ae(i,r,qn),qn.matrix.copy(pn),qn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>qn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let x=b*3,S=(_+b)*3;x<S;x+=3)if(Le(Yt,x,h,f),Yt.needsUpdate=!0,T.intersectsTriangle(Yt))return!0;return!1}});{const A=_s(t);for(let T=b*3,x=(_+b)*3;T<x;T+=3){Le(Xt,T,h,f),Xt.a.applyMatrix4(pn),Xt.b.applyMatrix4(pn),Xt.c.applyMatrix4(pn),Xt.needsUpdate=!0;for(let S=0,M=A*3;S<M;S+=3)if(Le(Yt,S,m,w),Yt.needsUpdate=!0,Xt.intersectsTriangle(Yt))return!0}}}else{const d=Be(i),h=ze(i,a);return Ae(d,r,Yn),!!(s.intersectsBox(Yn)&&ri(d,e,t,n,s)||(Ae(h,r,Yn),s.intersectsBox(Yn)&&ri(h,e,t,n,s)))}}const $n=new p.Matrix4,ks=new Ye,mn=new Ye,Ka=new p.Vector3,Xa=new p.Vector3,Ya=new p.Vector3,qa=new p.Vector3;function $a(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),ks.set(e.boundingBox.min,e.boundingBox.max,t),ks.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let w=Ka,b=Xa,_=null,A=null;s&&(_=Ya,A=qa);let T=1/0,x=null,S=null;return $n.copy(t).invert(),mn.matrix.copy($n),i.shapecast({boundsTraverseOrder:M=>ks.distanceToBox(M),intersectsBounds:(M,P,I)=>I<T&&I<o?(P&&(mn.min.copy(M.min),mn.max.copy(M.max),mn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>mn.distanceToBox(C),intersectsBounds:(C,D,L)=>L<T&&L<o,intersectsRange:(C,D)=>{for(let L=C,k=C+D;L<k;L++){Le(m,3*L,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let N=M,H=M+P;N<H;N++){Le(f,3*N,u,c),f.needsUpdate=!0;const j=f.distanceToTriangle(m,w,_);if(j<T&&(b.copy(w),A&&A.copy(_),T=j,x=N,S=L),j<r)return!0}}}});{const I=_s(e);for(let C=0,D=I;C<D;C++){Le(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let L=M,k=M+P;L<k;L++){Le(f,3*L,u,c),f.needsUpdate=!0;const N=f.distanceToTriangle(m,w,_);if(N<T&&(b.copy(w),A&&A.copy(_),T=N,x=L,S=C),N<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=T,n.faceIndex=x,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4($n),b.applyMatrix4($n),s.distance=b.sub(s.point).length(),s.faceIndex=S),n)}function Qa(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,c,u=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)r=d[f],o=new Uint32Array(r),a=new Uint16Array(r),c=new Float32Array(r),h(0,u),u+=r.byteLength;function h(f,m,w=!1){const b=f*2;if(Ie(b,a)){const _=Ge(f,o),A=Xe(b,a);let T=1/0,x=1/0,S=1/0,M=-1/0,P=-1/0,I=-1/0;for(let C=_,D=_+A;C<D;C++){const L=3*i.resolveTriangleIndex(C);for(let k=0;k<3;k++){let N=L+k;N=n?n[N]:N;const H=s.getX(N),j=s.getY(N),$=s.getZ(N);H<T&&(T=H),H>M&&(M=H),j<x&&(x=j),j>P&&(P=j),$<S&&(S=$),$>I&&(I=$)}}return c[f+0]!==T||c[f+1]!==x||c[f+2]!==S||c[f+3]!==M||c[f+4]!==P||c[f+5]!==I?(c[f+0]=T,c[f+1]=x,c[f+2]=S,c[f+3]=M,c[f+4]=P,c[f+5]=I,!0):!1}else{const _=Be(f),A=ze(f,o);let T=w,x=!1,S=!1;if(e){if(!T){const L=_/Ne+m/He,k=A/Ne+m/He;x=e.has(L),S=e.has(k),T=!x&&!S}}else x=!0,S=!0;const M=T||x,P=T||S;let I=!1;M&&(I=h(_,m,T));let C=!1;P&&(C=h(A,m,T));const D=I||C;if(D)for(let L=0;L<3;L++){const k=_+L,N=A+L,H=c[k],j=c[k+3],$=c[N],re=c[N+3];c[f+L]=H<$?H:$,c[f+L+3]=j>re?j:re}return D}}}function Ja(i,e,t,n,s,r,o){be.setBuffer(i._roots[e]),oi(0,i,t,n,s,r,o),be.clearBuffer()}function oi(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=be,d=i*2;if(Ie(d,c)){const f=Ge(i,u),m=Xe(d,c);Ua(e,t,n,f,m,s,r,o)}else{const f=Be(i);Ot(f,a,n,r,o)&&oi(f,e,t,n,s,r,o);const m=ze(i,u);Ot(m,a,n,r,o)&&oi(m,e,t,n,s,r,o)}}const ec=["x","y","z"];function tc(i,e,t,n,s,r){be.setBuffer(i._roots[e]);const o=ai(0,i,t,n,s,r);return be.clearBuffer(),o}function ai(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=be;let u=i*2;if(Ie(u,a)){const h=Ge(i,c),f=Xe(u,a);return Va(e,t,n,h,f,s,r)}else{const h=Ts(i,c),f=ec[h],w=n.direction[f]>=0;let b,_;w?(b=Be(i),_=ze(i,c)):(b=ze(i,c),_=Be(i));const T=Ot(b,o,n,s,r)?ai(b,e,t,n,s,r):null;if(T){const M=T.point[f];if(w?M<=o[_+h]:M>=o[_+h+3])return T}const S=Ot(_,o,n,s,r)?ai(_,e,t,n,s,r):null;return T&&S?T.distance<=S.distance?T:S:T||S||null}}const Qn=new p.Box3,qt=new dt,$t=new dt,gn=new p.Matrix4,tr=new Ye,Jn=new Ye;function nc(i,e,t,n){be.setBuffer(i._roots[e]);const s=ci(0,i,t,n);return be.clearBuffer(),s}function ci(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=be;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),tr.set(t.boundingBox.min,t.boundingBox.max,n),s=tr),Ie(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,b=Ge(i,a),_=Xe(c,o);if(gn.copy(n).invert(),t.boundsTree)return Ae(i,r,Jn),Jn.matrix.copy(gn),Jn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>Jn.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let x=b,S=_+b;x<S;x++)if(Le($t,3*e.resolveTriangleIndex(x),h,f),$t.needsUpdate=!0,T.intersectsTriangle($t))return!0;return!1}});{const A=_s(t);for(let T=b,x=_+b;T<x;T++){const S=e.resolveTriangleIndex(T);Le(qt,3*S,h,f),qt.a.applyMatrix4(gn),qt.b.applyMatrix4(gn),qt.c.applyMatrix4(gn),qt.needsUpdate=!0;for(let M=0,P=A*3;M<P;M+=3)if(Le($t,M,m,w),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const d=Be(i),h=ze(i,a);return Ae(d,r,Qn),!!(s.intersectsBox(Qn)&&ci(d,e,t,n,s)||(Ae(h,r,Qn),s.intersectsBox(Qn)&&ci(h,e,t,n,s)))}}const es=new p.Matrix4,Fs=new Ye,yn=new Ye,sc=new p.Vector3,ic=new p.Vector3,rc=new p.Vector3,oc=new p.Vector3;function ac(i,e,t,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Fs.set(e.boundingBox.min,e.boundingBox.max,t),Fs.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,u=a.index,d=e.attributes.position,h=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let w=sc,b=ic,_=null,A=null;s&&(_=rc,A=oc);let T=1/0,x=null,S=null;return es.copy(t).invert(),yn.matrix.copy(es),i.shapecast({boundsTraverseOrder:M=>Fs.distanceToBox(M),intersectsBounds:(M,P,I)=>I<T&&I<o?(P&&(yn.min.copy(M.min),yn.max.copy(M.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(M,P)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:C=>yn.distanceToBox(C),intersectsBounds:(C,D,L)=>L<T&&L<o,intersectsRange:(C,D)=>{for(let L=C,k=C+D;L<k;L++){const N=I.resolveTriangleIndex(L);Le(m,3*N,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let H=M,j=M+P;H<j;H++){const $=i.resolveTriangleIndex(H);Le(f,3*$,u,c),f.needsUpdate=!0;const re=f.distanceToTriangle(m,w,_);if(re<T&&(b.copy(w),A&&A.copy(_),T=re,x=H,S=L),re<r)return!0}}}})}else{const I=_s(e);for(let C=0,D=I;C<D;C++){Le(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let L=M,k=M+P;L<k;L++){const N=i.resolveTriangleIndex(L);Le(f,3*N,u,c),f.needsUpdate=!0;const H=f.distanceToTriangle(m,w,_);if(H<T&&(b.copy(w),A&&A.copy(_),T=H,x=L,S=C),H<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=T,n.faceIndex=x,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(es),b.applyMatrix4(es),s.distance=b.sub(s.point).length(),s.faceIndex=S),n)}function nr(i,e,t){return i===null?null:(i.point.applyMatrix4(e.matrixWorld),i.distance=i.point.distanceTo(t.ray.origin),i.object=e,i)}const ts=new Ye,ns=new p.Ray,sr=new p.Vector3,ir=new p.Matrix4,rr=new p.Vector3,Bs=["getX","getY","getZ"];class xn extends va{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,s=e._roots,r=e._indirectBuffer,o=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(c=>c.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:s,roots:r,indirectBuffer:o}=e;e.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(r));const a=new xn(t,{...n,[Ei]:!0});if(a._roots=r,a._indirectBuffer=o||null,n.setIndex){const u=t.getIndex();if(u===null){const d=new p.BufferAttribute(e.index,1,!1);t.setIndex(d)}else u.array!==s&&(u.array.set(s),u.needsUpdate=!0)}return a;function c(u){for(let d=0;d<u.length;d++){const h=u[d],f=new Uint32Array(h),m=new Uint16Array(h);for(let w=0,b=h.byteLength/He;w<b;w++){const _=Ne*w,A=2*_;Ie(A,m)||(f[_+6]=f[_+6]/Ne-w)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,u=(r?r[e]:e)*3;let d=u+0,h=u+1,f=u+2;a&&(d=a[d],h=a[h],f=a[f]);for(let m=0;m<3;m++){const w=o[Bs[m]](d),b=o[Bs[m]](h),_=o[Bs[m]](f);let A=w;b<A&&(A=b),_<A&&(A=_);let T=w;b>T&&(T=b),_>T&&(T=_),t[n+m]=A,t[n+m+3]=T}return t}computePrimitiveBounds(e,t,n){const s=this.geometry,r=this._indirectBuffer,o=s.attributes.position,a=s.index?s.index.array:null,c=o.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const u=o.array,d=o.offset||0;let h=3;o.isInterleavedBufferAttribute&&(h=o.data.stride);const f=["getX","getY","getZ"],m=n.offset;for(let w=e,b=e+t;w<b;w++){const A=(r?r[w]:w)*3,T=(w-m)*6;let x=A+0,S=A+1,M=A+2;a&&(x=a[x],S=a[S],M=a[M]),c||(x=x*h+d,S=S*h+d,M=M*h+d);for(let P=0;P<3;P++){let I,C,D;c?(I=o[f[P]](x),C=o[f[P]](S),D=o[f[P]](M)):(I=u[x+P],C=u[S+P],D=u[M+P]);let L=I;C<L&&(L=C),D<L&&(L=D);let k=I;C>k&&(k=C),D>k&&(k=D);const N=(k-L)/2,H=P*2;n[T+H+0]=L+N,n[T+H+1]=N+(Math.abs(L)+N)*us}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;ir.copy(e.matrixWorld).invert(),ns.copy(t.ray).applyMatrix4(ir),rr.setFromMatrixScale(e.matrixWorld),sr.copy(ns.direction).multiply(rr);const r=sr.length(),o=t.near/r,a=t.far/r;if(t.firstHitOnly===!0){let c=this.raycastFirst(ns,s,o,a);c=nr(c,e,t),c&&n.push(c)}else{const c=this.raycast(ns,s,o,a);for(let u=0,d=c.length;u<d;u++){const h=nr(c[u],e,t);h&&n.push(h)}}return n}refit(e=null){return(this.indirect?Qa:za)(this,e)}raycast(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots,o=[],a=this.indirect?Ja:Ga;for(let c=0,u=r.length;c<u;c++)a(this,c,t,e,o,n,s);return o}raycastFirst(e,t=p.FrontSide,n=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?tc:Wa;for(let c=0,u=r.length;c<u;c++){const d=a(this,c,t,e,n,s);d!=null&&(o==null||d.distance<o.distance)&&(o=d)}return o}intersectsGeometry(e,t){let n=!1;const s=this._roots,r=this.indirect?nc:Za;for(let o=0,a=s.length;o<a&&(n=r(this,o,e,t),!n);o++);return n}shapecast(e){const t=rt.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Ha:Ba});return rt.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:s,intersectsTriangles:r}=n;const o=rt.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,u=this.indirect?w=>{const b=this.resolveTriangleIndex(w);Le(o,b*3,a,c)}:w=>{Le(o,w*3,a,c)},d=rt.getPrimitive(),h=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?w=>{const b=e.resolveTriangleIndex(w);Le(d,b*3,h,f)}:w=>{Le(d,w*3,h,f)};if(r){if(!(e instanceof xn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const w=(b,_,A,T,x,S,M,P)=>{for(let I=A,C=A+T;I<C;I++){m(I),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let D=b,L=b+_;D<L;D++)if(u(D),o.needsUpdate=!0,r(o,d,D,I,x,S,M,P))return!0}return!1};if(s){const b=s;s=function(_,A,T,x,S,M,P,I){return b(_,A,T,x,S,M,P,I)?!0:w(_,A,T,x,S,M,P,I)}}else s=w}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return ts.set(e.min,e.max,t),ts.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ts.intersectsBox(n),intersectsTriangle:n=>ts.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},s={},r=0,o=1/0){return(this.indirect?ac:$a)(this,e,t,n,s,r,o)}closestPointToPoint(e,t={},n=0,s=1/0){return Oa(this,e,t,n,s)}}const tn={Mesh:p.Mesh.prototype.raycast,Line:p.Line.prototype.raycast,LineSegments:p.LineSegments.prototype.raycast,LineLoop:p.LineLoop.prototype.raycast,Points:p.Points.prototype.raycast,BatchedMesh:p.BatchedMesh.prototype.raycast},Ve=new p.Mesh,ss=[];function cc(i,e){if(this.isBatchedMesh)lc.call(this,i,e);else{const{geometry:t}=this;if(t.boundsTree)t.boundsTree.raycastObject3D(this,i,e);else{let n;if(this instanceof p.Mesh)n=tn.Mesh;else if(this instanceof p.LineSegments)n=tn.LineSegments;else if(this instanceof p.LineLoop)n=tn.LineLoop;else if(this instanceof p.Line)n=tn.Line;else if(this instanceof p.Points)n=tn.Points;else throw new Error("BVH: Fallback raycast function not found.");n.call(this,i,e)}}}function lc(i,e){if(this.boundsTrees){const t=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ve.material=this.material,Ve.geometry=this.geometry;const o=Ve.geometry.boundsTree,a=Ve.geometry.drawRange;Ve.geometry.boundingSphere===null&&(Ve.geometry.boundingSphere=new p.Sphere);for(let c=0,u=n.length;c<u;c++){if(!this.getVisibleAt(c))continue;const d=n[c].geometryIndex;if(Ve.geometry.boundsTree=t[d],this.getMatrixAt(c,Ve.matrixWorld).premultiply(r),!Ve.geometry.boundsTree){this.getBoundingBoxAt(d,Ve.geometry.boundingBox),this.getBoundingSphereAt(d,Ve.geometry.boundingSphere);const h=s[d];Ve.geometry.setDrawRange(h.start,h.count)}Ve.raycast(i,ss);for(let h=0,f=ss.length;h<f;h++){const m=ss[h];m.object=this,m.batchId=c,e.push(m)}ss.length=0}Ve.geometry.boundsTree=o,Ve.geometry.drawRange=a,Ve.material=null,Ve.geometry=null}else tn.BatchedMesh.call(this,i,e)}function Fr(i){i.traverse(e=>{var s,r,o;const t=e;if(!t.isMesh||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh)return;const n=t.geometry;!((s=n==null?void 0:n.attributes)!=null&&s.position)||(o=(r=n.morphAttributes)==null?void 0:r.position)!=null&&o.length||(n.boundsTree||(n.boundsTree=new xn(n)),t.raycast=cc)})}function hc(i){i.boundsTree&&(i.boundsTree=void 0)}function or(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof E.Texture&&s.dispose()}const t=i;if(t.isShaderMaterial&&t.uniforms)for(const n of Object.values(t.uniforms))(n==null?void 0:n.value)instanceof E.Texture&&n.value.dispose();i.dispose()}function xs(i){i.traverse(e=>{var r;const t=e;t.geometry&&typeof t.geometry.dispose=="function"&&(hc(t.geometry),t.geometry.dispose());const n=t.material;Array.isArray(n)?n.forEach(or):n&&or(n);const s=e;s.isLight&&((r=s.shadow)!=null&&r.dispose)&&s.shadow.dispose()})}function uc(i,e){if(!(e!=null&&e.keepBackgrounds)){i.background instanceof E.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof E.Texture&&(i.environment.dispose(),i.environment=null);const t=i;t.__originalEnvironmentTexture&&(t.__originalEnvironmentTexture=void 0)}for(const t of[...i.children])xs(t),i.remove(t)}class De{constructor(e){this.object=e,this.positionAdapter=Pt.fromThreeVector(e.position),this.rotationAdapter=Pt.fromThreeVector(e.rotation),this.scaleAdapter=Pt.fromThreeVector(e.scale)}get id(){return this.object.uuid}get name(){return this.object.name}set name(e){this.object.name=e}get visible(){return this.object.visible}set visible(e){this.object.visible=e}get castShadow(){return this.object.castShadow}set castShadow(e){this.object.castShadow=e}get receiveShadow(){return this.object.receiveShadow}set receiveShadow(e){this.object.receiveShadow=e}get position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof De?(this.object.add(e.getThreeObject()),F.ok(void 0)):F.err(new K("Child must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to add child object",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof De?(this.object.remove(e.getThreeObject()),F.ok(void 0)):F.err(new K("Child must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to remove child object",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new De(t))})}clone(){return new De(this.object.clone())}dispose(){xs(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new De(e)}static create(){return new De(new E.Object3D)}}class St{constructor(e){this.scene=e||new E.Scene}get id(){return this.scene.uuid}get name(){return this.scene.name}set name(e){this.scene.name=e}add(e){try{return e instanceof De?(this.scene.add(e.getThreeObject()),F.ok(void 0)):F.err(new K("Object must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to add object to scene",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof De?(this.scene.remove(e.getThreeObject()),F.ok(void 0)):F.err(new K("Object must be a ThreeObject3DAdapter",Y.INVALID_PARAMETER))}catch(t){return F.err(new K("Failed to remove object from scene",Y.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeContents(e){uc(this.scene,e)}traverse(e){this.scene.traverse(t=>{e(new De(t))})}get background(){return this.scene.background instanceof E.Color?new li(this.scene.background):this.scene.background instanceof E.Texture?new is(this.scene.background):null}set background(e){e instanceof li?this.scene.background=e.getThreeColor():e instanceof is?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new ar(this.scene.fog):null}set fog(e){e instanceof ar?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new is(this.scene.environment):null}set environment(e){e instanceof is?this.scene.environment=e.getThreeTexture():this.scene.environment=null}setEnvironmentIntensity(e){this.scene.environmentIntensity=e}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class li{constructor(e){this.color=e}get r(){return this.color.r}set r(e){this.color.r=e}get g(){return this.color.g}set g(e){this.color.g=e}get b(){return this.color.b}set b(e){this.color.b=e}setHex(e){this.color.setHex(e)}setRGB(e,t,n){this.color.setRGB(e,t,n)}getHex(){return this.color.getHex()}getThreeColor(){return this.color}}let is=class{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image||null}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}};class ar{constructor(e){this.fog=e}get color(){return new li(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Br extends De{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Pt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof E.PerspectiveCamera||this.camera instanceof E.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new E.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class _i extends Br{constructor(e){const t=e||new E.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=75,t=1,n=.1,s=1e3){return new _i(new E.PerspectiveCamera(e,t,n,s))}}class dc{constructor(e){this.renderer=null,this._id=Ir(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new E.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:E.BasicShadowMap,pcf:E.PCFShadowMap,pcfsoft:E.PCFSoftShadowMap,vsm:E.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:E.NoToneMapping,linear:E.LinearToneMapping,reinhard:E.ReinhardToneMapping,cineon:E.CineonToneMapping,aces:E.ACESFilmicToneMapping};this.renderer.toneMapping=t[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}if(e.pixelRatio!==void 0?this.renderer.setPixelRatio(e.pixelRatio):this.renderer.setPixelRatio(window.devicePixelRatio),this.canvas){const{clientWidth:t,clientHeight:n}=this.canvas.parentElement||this.canvas;t&&n&&this.renderer.setSize(t,n)}return this.renderer.outputColorSpace=E.SRGBColorSpace,F.ok(void 0)}catch(t){return F.err(new K("Failed to initialize renderer",Y.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return F.err(new K("Renderer not initialized",Y.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof St))return F.err(new K("Scene must be a ThreeSceneAdapter",Y.INVALID_PARAMETER));if(!(t instanceof Br))return F.err(new K("Camera must be a ThreeCameraAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),F.ok(void 0)}catch(n){return F.err(new K("Failed to render frame",Y.RENDER_FAILED,{originalError:n}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const n=this.renderer.domElement;n.style.width="100%",n.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(e)}getPixelRatio(){return this.renderer?this.renderer.getPixelRatio():1}setToneMappingExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}getDomElement(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.domElement}getContext(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.getContext()}get capabilities(){if(!this.renderer)return{maxTextureSize:0,maxCubemapSize:0,maxAttributes:0,maxVertexUniforms:0,maxFragmentUniforms:0,maxSamples:0,isWebGL2:!1};const e=this.renderer.capabilities;return{maxTextureSize:e.maxTextureSize,maxCubemapSize:e.maxCubemapSize,maxAttributes:e.maxAttributes,maxVertexUniforms:e.maxVertexUniforms,maxFragmentUniforms:e.maxFragmentUniforms,maxSamples:e.maxSamples||0,isWebGL2:e.isWebGL2}}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}isDisposed(){return this.renderer===null}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function cr(i,e){if(e===p.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===p.TriangleFanDrawMode||e===p.TriangleStripDrawMode){let t=i.getIndex();if(t===null){const o=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);i.setIndex(o),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===p.TriangleFanDrawMode)for(let o=1;o<=n;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}function fc(i){const e=new Map,t=new Map,n=i.clone();return zr(i,n,function(s,r){e.set(r,s),t.set(s,r)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=e.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(c){return t.get(c)}),r.bind(r.skeleton,r.bindMatrix)}),n}function zr(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)zr(i.children[n],e.children[n],t)}class pc extends p.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Ec(t)}),this.register(function(t){return new Tc(t)}),this.register(function(t){return new Cc(t)}),this.register(function(t){return new Ic(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new _c(t)}),this.register(function(t){return new bc(t)}),this.register(function(t){return new xc(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new wc(t)}),this.register(function(t){return new Mc(t)}),this.register(function(t){return new Sc(t)}),this.register(function(t){return new vc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new gc(t)}),this.register(function(t){return new lr(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new lr(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Pc(t)})}load(e,t,n,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const u=p.LoaderUtils.extractUrlBase(e);o=p.LoaderUtils.resolveURL(u,this.path)}else o=p.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(u){s?s(u):console.error(u),r.manager.itemError(e),r.manager.itemEnd(e)},c=new p.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(u){try{r.parse(u,o,function(d){t(d),r.manager.itemEnd(e)},a)}catch(d){a(d)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const o={},a={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===Ur){try{o[le.KHR_BINARY_GLTF]=new Oc(e)}catch(h){s&&s(h);return}r=JSON.parse(o[le.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const u=new Zc(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](u);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,o[h.name]=!0}if(r.extensionsUsed)for(let d=0;d<r.extensionsUsed.length;++d){const h=r.extensionsUsed[d],f=r.extensionsRequired||[];switch(h){case le.KHR_MATERIALS_UNLIT:o[h]=new yc;break;case le.KHR_DRACO_MESH_COMPRESSION:o[h]=new Dc(r,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:o[h]=new Nc;break;case le.KHR_MESH_QUANTIZATION:o[h]=new kc;break;default:f.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}u.setExtensions(o),u.setPlugins(a),u.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function mc(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function Re(i,e,t){const n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class gc{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let u;const d=new p.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],p.LinearSRGBColorSpace);const h=c.range!==void 0?c.range:0;switch(c.type){case"directional":u=new p.DirectionalLight(d),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new p.PointLight(d),u.distance=h;break;case"spot":u=new p.SpotLight(d),u.distance=h,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,u.angle=c.spot.outerConeAngle,u.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return u.position.set(0,0,0),yt(u,c),c.intensity!==void 0&&(u.intensity=c.intensity),u.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(u),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class yc{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return p.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new p.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),e.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,p.SRGBColorSpace))}return Promise.all(s)}}class wc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class Ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const r=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new p.Vector2(r,r)}return Promise.all(s)}}class Tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class Sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class _c{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(t.sheenColor=new p.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){const r=n.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,p.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class bc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class xc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const r=n.attenuationColor||[1,1,1];return t.attenuationColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),Promise.all(s)}}class Ac{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class Mc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const r=n.specularColorFactor||[1,1,1];return t.specularColor=new p.Color().setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,p.SRGBColorSpace)),Promise.all(s)}}class Rc{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(s)}}class vc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class Cc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class Ic{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,o.source,c)}}class Lc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let c=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(c=u)}return n.loadTextureImage(e,o.source,c)}}class lr{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const c=s.byteOffset||0,u=s.byteLength||0,d=s.count,h=s.byteStride,f=new Uint8Array(a,c,u);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(d,h,f,s.mode,s.filter).then(function(m){return m.buffer}):o.ready.then(function(){const m=new ArrayBuffer(d*h);return o.decodeGltfBuffer(new Uint8Array(m),d,h,f,s.mode,s.filter),m})})}else return null}}class Pc{constructor(e){this.name=le.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const u of s.primitives)if(u.mode!==st.TRIANGLES&&u.mode!==st.TRIANGLE_STRIP&&u.mode!==st.TRIANGLE_FAN&&u.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],c={};for(const u in o)a.push(this.parser.getDependency("accessor",o[u]).then(d=>(c[u]=d,c[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(u=>{const d=u.pop(),h=d.isGroup?d.children:[d],f=u[0].count,m=[];for(const w of h){const b=new p.Matrix4,_=new p.Vector3,A=new p.Quaternion,T=new p.Vector3(1,1,1),x=new p.InstancedMesh(w.geometry,w.material,f);for(let S=0;S<f;S++)c.TRANSLATION&&_.fromBufferAttribute(c.TRANSLATION,S),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,S),c.SCALE&&T.fromBufferAttribute(c.SCALE,S),x.setMatrixAt(S,b.compose(_,A,T));for(const S in c)if(S==="_COLOR_0"){const M=c[S];x.instanceColor=new p.InstancedBufferAttribute(M.array,M.itemSize,M.normalized)}else S!=="TRANSLATION"&&S!=="ROTATION"&&S!=="SCALE"&&w.geometry.setAttribute(S,c[S]);p.Object3D.prototype.copy.call(x,w),this.parser.assignFinalMaterial(x),m.push(x)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const Ur="glTF",wn=12,hr={JSON:1313821514,BIN:5130562};class Oc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,wn),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Ur)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-wn,r=new DataView(e,wn);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const c=r.getUint32(o,!0);if(o+=4,c===hr.JSON){const u=new Uint8Array(e,wn+o,a);this.content=n.decode(u)}else if(c===hr.BIN){const u=wn+o;this.body=e.slice(u,u+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Dc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},u={};for(const d in o){const h=hi[d]||d.toLowerCase();a[h]=o[d]}for(const d in e.attributes){const h=hi[d]||d.toLowerCase();if(o[d]!==void 0){const f=n.accessors[e.attributes[d]],m=rn[f.componentType];u[h]=m.name,c[h]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(d){return new Promise(function(h,f){s.decodeDracoFile(d,function(m){for(const w in m.attributes){const b=m.attributes[w],_=c[w];_!==void 0&&(b.normalized=_)}h(m)},a,u,p.LinearSRGBColorSpace,f)})})}}class Nc{constructor(){this.name=le.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class kc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Vr extends p.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let o=0;o!==s;o++)t[o]=n[r+o];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,u=a*3,d=s-t,h=(n-t)/d,f=h*h,m=f*h,w=e*u,b=w-u,_=-2*m+3*f,A=m-f,T=1-_,x=A-f+h;for(let S=0;S!==a;S++){const M=o[b+S+a],P=o[b+S+c]*d,I=o[w+S+a],C=o[w+S]*d;r[S]=T*M+x*P+_*I+A*C}return r}}const Fc=new p.Quaternion;class Bc extends Vr{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return Fc.fromArray(r).normalize().toArray(r),r}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},rn={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},ur={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},dr={33071:p.ClampToEdgeWrapping,33648:p.MirroredRepeatWrapping,10497:p.RepeatWrapping},zs={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},hi={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Rt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},zc={CUBICSPLINE:void 0,LINEAR:p.InterpolateLinear,STEP:p.InterpolateDiscrete},Us={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Uc(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new p.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:p.FrontSide})),i.DefaultMaterial}function Bt(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function yt(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Vc(i,e,t){let n=!1,s=!1,r=!1;for(let u=0,d=e.length;u<d;u++){const h=e[u];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(i);const o=[],a=[],c=[];for(let u=0,d=e.length;u<d;u++){const h=e[u];if(n){const f=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):i.attributes.position;o.push(f)}if(s){const f=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):i.attributes.normal;a.push(f)}if(r){const f=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):i.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(u){const d=u[0],h=u[1],f=u[2];return n&&(i.morphAttributes.position=d),s&&(i.morphAttributes.normal=h),r&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function Hc(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Gc(i){let e;const t=i.extensions&&i.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Vs(t.attributes):e=i.indices+":"+Vs(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Vs(i.targets[n]);return e}function Vs(i){let e="";const t=Object.keys(i).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+i[t[n]]+";";return e}function ui(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function jc(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Wc=new p.Matrix4;class Zc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new mc,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&o<98?this.textureLoader=new p.TextureLoader(this.options.manager):this.textureLoader=new p.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new p.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return Bt(r,a,s),yt(a,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(const c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const o=t[s].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(o,a)=>{const c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(const[u,d]of o.children.entries())r(d,a.children[u])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){n.load(p.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=zs[s.type],a=rn[s.componentType],c=s.normalized===!0,u=new a(s.count*o);return Promise.resolve(new p.BufferAttribute(u,o,c))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],c=zs[s.type],u=rn[s.componentType],d=u.BYTES_PER_ELEMENT,h=d*c,f=s.byteOffset||0,m=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,w=s.normalized===!0;let b,_;if(m&&m!==h){const A=Math.floor(f/m),T="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let x=t.cache.get(T);x||(b=new u(a,A*m,s.count*m/d),x=new p.InterleavedBuffer(b,m/d),t.cache.add(T,x)),_=new p.InterleavedBufferAttribute(x,c,f%m/d,w)}else a===null?b=new u(s.count*c):b=new u(a,f,s.count*c),_=new p.BufferAttribute(b,c,w);if(s.sparse!==void 0){const A=zs.SCALAR,T=rn[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,S=s.sparse.values.byteOffset||0,M=new T(o[1],x,s.sparse.count*A),P=new u(o[2],S,s.sparse.count*c);a!==null&&(_=new p.BufferAttribute(_.array.slice(),_.itemSize,_.normalized)),_.normalized=!1;for(let I=0,C=M.length;I<C;I++){const D=M[I];if(_.setX(D,P[I*c]),c>=2&&_.setY(D,P[I*c+1]),c>=3&&_.setZ(D,P[I*c+2]),c>=4&&_.setW(D,P[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=w}return _})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,o=t.images[r];let a=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){const s=this,r=this.json,o=r.textures[e],a=r.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const u=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=o.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return d.magFilter=ur[f.magFilter]||p.LinearFilter,d.minFilter=ur[f.minFilter]||p.LinearMipmapLinearFilter,d.wrapS=dr[f.wrapS]||p.RepeatWrapping,d.wrapT=dr[f.wrapT]||p.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==p.NearestFilter&&d.minFilter!==p.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=u,u}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const o=s.images[e],a=self.URL||self.webkitURL;let c=o.uri||"",u=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(h){u=!0;const f=new Blob([h],{type:o.mimeType});return c=a.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(h){return new Promise(function(f,m){let w=f;t.isImageBitmapLoader===!0&&(w=function(b){const _=new p.Texture(b);_.needsUpdate=!0,f(_)}),t.load(p.LoaderUtils.resolveURL(h,r.path),w,void 0,m)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),yt(h,o),h.userData.mimeType=o.mimeType||jc(o.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=r.associations.get(o);o=r.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,c)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.PointsMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.LineBasicMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(s||r||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),r&&(c.vertexColors=!0),o&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return p.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let o;const a={},c=r.extensions||{},u=[];if(c[le.KHR_MATERIALS_UNLIT]){const h=s[le.KHR_MATERIALS_UNLIT];o=h.getMaterialType(),u.push(h.extendParams(a,r,t))}else{const h=r.pbrMetallicRoughness||{};if(a.color=new p.Color(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){const f=h.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],p.LinearSRGBColorSpace),a.opacity=f[3]}h.baseColorTexture!==void 0&&u.push(t.assignTexture(a,"map",h.baseColorTexture,p.SRGBColorSpace)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),u.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=p.DoubleSide);const d=r.alphaMode||Us.OPAQUE;if(d===Us.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Us.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new p.Vector2(1,1),r.normalTexture.scale!==void 0)){const h=r.normalTexture.scale;a.normalScale.set(h,h)}if(r.occlusionTexture!==void 0&&o!==p.MeshBasicMaterial&&(u.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==p.MeshBasicMaterial){const h=r.emissiveFactor;a.emissive=new p.Color().setRGB(h[0],h[1],h[2],p.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==p.MeshBasicMaterial&&u.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,p.SRGBColorSpace)),Promise.all(u).then(function(){const h=new o(a);return r.name&&(h.name=r.name),yt(h,r),t.associations.set(h,{materials:e}),r.extensions&&Bt(s,h,r),h})}createUniqueName(e){const t=p.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return fr(c,a,t)})}const o=[];for(let a=0,c=e.length;a<c;a++){const u=e[a],d=Gc(u),h=s[d];if(h)o.push(h.promise);else{let f;u.extensions&&u.extensions[le.KHR_DRACO_MESH_COMPRESSION]?f=r(u):f=fr(new p.BufferGeometry,u,t),s[d]={primitive:u,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],o=r.primitives,a=[];for(let c=0,u=o.length;c<u;c++){const d=o[c].material===void 0?Uc(this.cache):this.getDependency("material",o[c].material);a.push(d)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){const u=c.slice(0,c.length-1),d=c[c.length-1],h=[];for(let m=0,w=d.length;m<w;m++){const b=d[m],_=o[m];let A;const T=u[m];if(_.mode===st.TRIANGLES||_.mode===st.TRIANGLE_STRIP||_.mode===st.TRIANGLE_FAN||_.mode===void 0)A=r.isSkinnedMesh===!0?new p.SkinnedMesh(b,T):new p.Mesh(b,T),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),_.mode===st.TRIANGLE_STRIP?A.geometry=cr(A.geometry,p.TriangleStripDrawMode):_.mode===st.TRIANGLE_FAN&&(A.geometry=cr(A.geometry,p.TriangleFanDrawMode));else if(_.mode===st.LINES)A=new p.LineSegments(b,T);else if(_.mode===st.LINE_STRIP)A=new p.Line(b,T);else if(_.mode===st.LINE_LOOP)A=new p.LineLoop(b,T);else if(_.mode===st.POINTS)A=new p.Points(b,T);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+_.mode);Object.keys(A.geometry.morphAttributes).length>0&&Hc(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),yt(A,r),_.extensions&&Bt(s,A,_),t.assignFinalMaterial(A),h.push(A)}for(let m=0,w=h.length;m<w;m++)t.associations.set(h[m],{meshes:e,primitives:m});if(h.length===1)return r.extensions&&Bt(s,h[0],r),h[0];const f=new p.Group;r.extensions&&Bt(s,f,r),t.associations.set(f,{meshes:e});for(let m=0,w=h.length;m<w;m++)f.add(h[m]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new p.PerspectiveCamera(p.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new p.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),yt(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),o=s,a=[],c=[];for(let u=0,d=o.length;u<d;u++){const h=o[u];if(h){a.push(h);const f=new p.Matrix4;r!==null&&f.fromArray(r.array,u*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[u])}return new p.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,o=[],a=[],c=[],u=[],d=[];for(let h=0,f=s.channels.length;h<f;h++){const m=s.channels[h],w=s.samplers[m.sampler],b=m.target,_=b.node,A=s.parameters!==void 0?s.parameters[w.input]:w.input,T=s.parameters!==void 0?s.parameters[w.output]:w.output;b.node!==void 0&&(o.push(this.getDependency("node",_)),a.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",T)),u.push(w),d.push(b))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(h){const f=h[0],m=h[1],w=h[2],b=h[3],_=h[4],A=[];for(let x=0,S=f.length;x<S;x++){const M=f[x],P=m[x],I=w[x],C=b[x],D=_[x];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();const L=n._createAnimationTracks(M,P,I,C,D);if(L)for(let k=0;k<L.length;k++)A.push(L[k])}const T=new p.AnimationClip(r,void 0,A);return yt(T,s),T})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const o=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,u=s.weights.length;c<u;c++)a.morphTargetInfluences[c]=s.weights[c]}),o})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),o=[],a=s.children||[];for(let u=0,d=a.length;u<d;u++)o.push(n.getDependency("node",a[u]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),c]).then(function(u){const d=u[0],h=u[1],f=u[2];f!==null&&d.traverse(function(m){m.isSkinnedMesh&&m.bind(f,Wc)});for(let m=0,w=h.length;m<w;m++)d.add(h[m]);if(d.userData.pivot!==void 0&&h.length>0){const m=d.userData.pivot,w=h[0];d.pivot=new p.Vector3().fromArray(m),d.position.x-=m[0],d.position.y-=m[1],d.position.z-=m[2],w.position.set(0,0,0),delete d.userData.pivot}return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],o=r.name?s.createUniqueName(r.name):"",a=[],c=s._invokeOne(function(u){return u.createNodeMesh&&u.createNodeMesh(e)});return c&&a.push(c),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(u){return s._getNodeRef(s.cameraCache,r.camera,u)})),s._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(e)}).forEach(function(u){a.push(u)}),this.nodeCache[e]=Promise.all(a).then(function(u){let d;if(r.isBone===!0?d=new p.Bone:u.length>1?d=new p.Group:u.length===1?d=u[0]:d=new p.Object3D,d!==u[0])for(let h=0,f=u.length;h<f;h++)d.add(u[h]);if(r.name&&(d.userData.name=r.name,d.name=o),yt(d,r),r.extensions&&Bt(n,d,r),r.matrix!==void 0){const h=new p.Matrix4;h.fromArray(r.matrix),d.applyMatrix4(h)}else r.translation!==void 0&&d.position.fromArray(r.translation),r.rotation!==void 0&&d.quaternion.fromArray(r.rotation),r.scale!==void 0&&d.scale.fromArray(r.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const h=s.associations.get(d);s.associations.set(d,{...h})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new p.Group;n.name&&(r.name=s.createUniqueName(n.name)),yt(r,n),n.extensions&&Bt(t,r,n);const o=n.nodes||[],a=[];for(let c=0,u=o.length;c<u;c++)a.push(s.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let d=0,h=c.length;d<h;d++){const f=c[d];f.parent!==null?r.add(fc(f)):r.add(f)}const u=d=>{const h=new Map;for(const[f,m]of s.associations)(f instanceof p.Material||f instanceof p.Texture)&&h.set(f,m);return d.traverse(f=>{const m=s.associations.get(f);m!=null&&h.set(f,m)}),h};return s.associations=u(r),r})}_createAnimationTracks(e,t,n,s,r){const o=[],a=e.name?e.name:e.uuid,c=[];function u(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}Rt[r.path]===Rt.weights?(u(e),e.isGroup&&e.children.forEach(u)):c.push(a);let d;switch(Rt[r.path]){case Rt.weights:d=p.NumberKeyframeTrack;break;case Rt.rotation:d=p.QuaternionKeyframeTrack;break;case Rt.translation:case Rt.scale:d=p.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:d=p.NumberKeyframeTrack;break;case 2:case 3:default:d=p.VectorKeyframeTrack;break}break}const h=s.interpolation!==void 0?zc[s.interpolation]:p.InterpolateLinear,f=this._getArrayFromAccessor(n);for(let m=0,w=c.length;m<w;m++){const b=new d(c[m]+"."+Rt[r.path],t.array,f,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),o.push(b)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=ui(t.constructor),s=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof p.QuaternionKeyframeTrack?Bc:Vr;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Kc(i,e,t){const n=e.attributes,s=new p.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,u=a.max;if(c!==void 0&&u!==void 0){if(s.set(new p.Vector3(c[0],c[1],c[2]),new p.Vector3(u[0],u[1],u[2])),a.normalized){const d=ui(rn[a.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const a=new p.Vector3,c=new p.Vector3;for(let u=0,d=r.length;u<d;u++){const h=r[u];if(h.POSITION!==void 0){const f=t.json.accessors[h.POSITION],m=f.min,w=f.max;if(m!==void 0&&w!==void 0){if(c.setX(Math.max(Math.abs(m[0]),Math.abs(w[0]))),c.setY(Math.max(Math.abs(m[1]),Math.abs(w[1]))),c.setZ(Math.max(Math.abs(m[2]),Math.abs(w[2]))),f.normalized){const b=ui(rn[f.componentType]);c.multiplyScalar(b)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}i.boundingBox=s;const o=new p.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=o}function fr(i,e,t){const n=e.attributes,s=[];function r(o,a){return t.getDependency("accessor",o).then(function(c){i.setAttribute(a,c)})}for(const o in n){const a=hi[o]||o.toLowerCase();a in i.attributes||s.push(r(n[o],a))}if(e.indices!==void 0&&!i.index){const o=t.getDependency("accessor",e.indices).then(function(a){i.setIndex(a)});s.push(o)}return p.ColorManagement.workingColorSpace!==p.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${p.ColorManagement.workingColorSpace}" not supported.`),yt(i,e),Kc(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?Vc(i,e.targets,t):i})}const Xc=E.REVISION.replace(/\D/g,""),Hr=`https://cdn.jsdelivr.net/npm/three@0.${Xc}/examples/jsm/libs`,Yc=`${Hr}/draco/`,qc=`${Hr}/basis/`;class $c{constructor(e={}){this.loadingManager=new E.LoadingManager,this.loader=new pc(this.loadingManager),this.config=e}ensureDecoders(){return this.decodersReady||(this.decodersReady=this.configureDecoders()),this.decodersReady}async configureDecoders(){const e=this.config,t=[];(e.draco??!0)&&t.push(this.configureDraco(e)),(e.ktx2??!0)&&t.push(this.configureKtx2(e)),(e.meshopt??!0)&&t.push(this.configureMeshopt());const n=await Promise.allSettled(t);for(const s of n)s.status==="rejected"&&console.warn("softbox: a compression decoder failed to initialize; compressed assets using it may not load.",s.reason)}async configureDraco(e){const{DRACOLoader:t}=await import("three/examples/jsm/loaders/DRACOLoader.js"),n=new t(this.loadingManager);n.setDecoderPath(e.dracoDecoderPath??Yc),this.dracoLoader=n,this.loader.setDRACOLoader(n)}async configureKtx2(e){const{KTX2Loader:t}=await import("three/examples/jsm/loaders/KTX2Loader.js"),n=new t(this.loadingManager);n.setTranscoderPath(e.ktx2TranscoderPath??qc),e.renderer&&n.detectSupport(e.renderer),this.ktx2Loader=n,this.loader.setKTX2Loader(n)}async configureMeshopt(){const e=await import("three/examples/jsm/libs/meshopt_decoder.module.js");this.loader.setMeshoptDecoder(e.MeshoptDecoder)}async load(e,t){try{return await this.ensureDecoders(),new Promise(n=>{this.loader.load(e,s=>{var o;(this.config.bvh??!0)&&Fr(s.scene),s.scene.animations=s.animations;const r={scene:new De(s.scene),animations:this.convertAnimations(s.animations),cameras:(o=s.cameras)==null?void 0:o.map(a=>{const c=a instanceof E.PerspectiveCamera,u=a instanceof E.OrthographicCamera;return{name:a.name,type:a.type,fov:c?a.fov:void 0,aspect:c?a.aspect:void 0,near:c||u?a.near:.1,far:c||u?a.far:1e3}}),userData:s.userData};n(F.ok(r))},s=>{s.total>0&&(t==null||t(s.loaded,s.total))},s=>{n(F.err(new K("Failed to load GLTF model",Y.MODEL_LOAD_FAILED,{url:e,originalError:s})))})})}catch(n){return F.err(new K("Failed to initiate model loading",Y.MODEL_LOAD_FAILED,{url:e,originalError:n}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}dispose(){var e,t;(e=this.dracoLoader)==null||e.dispose(),(t=this.ktx2Loader)==null||t.dispose()}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(n=>({name:n.name,type:this.getTrackType(n),times:n.times,values:n.values}))}))}getTrackType(e){return e instanceof E.VectorKeyframeTrack?"vector":e instanceof E.QuaternionKeyframeTrack?"quaternion":e instanceof E.NumberKeyframeTrack?"number":e instanceof E.BooleanKeyframeTrack?"boolean":"number"}}class pr{static createLoader(e,t={}){var s;const n=(s=e.split(".").pop())==null?void 0:s.toLowerCase();switch(n){case"gltf":case"glb":return new $c(t);default:throw new K(`Unsupported file format: ${n}`,Y.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const mr={type:"change"},bi={type:"start"},Gr={type:"end"},rs=new p.Ray,gr=new p.Plane,Qc=Math.cos(70*p.MathUtils.DEG2RAD),Pe=new p.Vector3,$e=2*Math.PI,Ee={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Hs=1e-6;class jr extends p.Controls{constructor(e,t=null){super(e,t),this.state=Ee.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=el.bind(this),this._onPointerDown=Jc.bind(this),this._onPointerUp=tl.bind(this),this._onContextMenu=cl.bind(this),this._onMouseWheel=il.bind(this),this._onKeyDown=rl.bind(this),this._onTouchStart=ol.bind(this),this._onTouchMove=al.bind(this),this._onMouseDown=nl.bind(this),this._onMouseMove=sl.bind(this),this._interceptControlDown=ll.bind(this),this._interceptControlUp=hl.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(mr),this.update(),this.state=Ee.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Pe.copy(t).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===Ee.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=$e:n>Math.PI&&(n-=$e),s<-Math.PI?s+=$e:s>Math.PI&&(s-=$e),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Pe.setFromSpherical(this._spherical),Pe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Pe),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Pe.length();o=this._clampDistance(a*this._scale);const c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const u=new p.Vector3(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).add(a),this.object.updateMatrixWorld(),o=Pe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(rs.origin.copy(this.object.position),rs.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(rs.direction))<Qc?this.object.lookAt(this.target):(gr.setFromNormalAndCoplanarPoint(this.object.up,this.target),rs.intersectPlane(gr,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Hs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Hs||this._lastTargetPosition.distanceToSquared(this.target)>Hs?(this.dispatchEvent(mr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?$e/60*this.autoRotateSpeed*e:$e/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Pe.setFromMatrixColumn(t,0),Pe.multiplyScalar(-e),this._panOffset.add(Pe)}_panUp(e,t){this.screenSpacePanning===!0?Pe.setFromMatrixColumn(t,1):(Pe.setFromMatrixColumn(t,0),Pe.crossVectors(this.object.up,Pe)),Pe.multiplyScalar(e),this._panOffset.add(Pe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Pe.copy(s).sub(this.target);let r=Pe.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function Jc(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function el(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function tl(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Gr),this.state=Ee.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function nl(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Ee.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ee.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ee.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ee.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ee.PAN}break;default:this.state=Ee.NONE}this.state!==Ee.NONE&&this.dispatchEvent(bi)}function sl(i){switch(this.state){case Ee.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Ee.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Ee.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function il(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ee.NONE||(i.preventDefault(),this.dispatchEvent(bi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Gr))}function rl(i){this.enabled!==!1&&this._handleKeyDown(i)}function ol(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Ee.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Ee.TOUCH_PAN;break;default:this.state=Ee.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Ee.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Ee.TOUCH_DOLLY_ROTATE;break;default:this.state=Ee.NONE}break;default:this.state=Ee.NONE}this.state!==Ee.NONE&&this.dispatchEvent(bi)}function al(i){switch(this._trackPointer(i),this.state){case Ee.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Ee.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Ee.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Ee.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Ee.NONE}}function cl(i){this.enabled!==!1&&i.preventDefault()}function ll(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function hl(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Gs=new p.Plane,os=new p.Raycaster,Qt=new p.Vector2,js=new p.Vector3;class ul extends jr{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE},this._panWorldStart=new p.Vector3}_handleMouseDownPan(e){if(super._handleMouseDownPan(e),this._panOffset.set(0,0,0),this.screenSpacePanning===!0)return;Gs.setFromNormalAndCoplanarPoint(this.object.up,this.target);const n=this.domElement.getBoundingClientRect();Qt.x=(e.clientX-n.left)/n.width*2-1,Qt.y=-((e.clientY-n.top)/n.height)*2+1,os.setFromCamera(Qt,this.object),os.ray.intersectPlane(Gs,this._panWorldStart)}_handleMouseMovePan(e){if(this.screenSpacePanning===!0){super._handleMouseMovePan(e);return}const n=this.domElement.getBoundingClientRect();Qt.x=(e.clientX-n.left)/n.width*2-1,Qt.y=-((e.clientY-n.top)/n.height)*2+1,os.setFromCamera(Qt,this.object),os.ray.intersectPlane(Gs,js)&&(js.sub(this._panWorldStart),this._panOffset.copy(js).negate(),this.update())}}class Wr{constructor(e){this.controls=e,this.targetAdapter=Pt.fromThreeVector(e.target)}get enabled(){return this.controls.enabled}set enabled(e){this.controls.enabled=e}get enableDamping(){return this.controls.enableDamping}set enableDamping(e){this.controls.enableDamping=e}get dampingFactor(){return this.controls.dampingFactor}set dampingFactor(e){this.controls.dampingFactor=e}get enableZoom(){return this.controls.enableZoom}set enableZoom(e){this.controls.enableZoom=e}get enableRotate(){return this.controls.enableRotate}set enableRotate(e){this.controls.enableRotate=e}get enablePan(){return this.controls.enablePan}set enablePan(e){this.controls.enablePan=e}get zoomSpeed(){return this.controls.zoomSpeed}set zoomSpeed(e){this.controls.zoomSpeed=e}get minDistance(){return this.controls.minDistance}set minDistance(e){this.controls.minDistance=e}get maxDistance(){return this.controls.maxDistance}set maxDistance(e){this.controls.maxDistance=e}get rotateSpeed(){return this.controls.rotateSpeed}set rotateSpeed(e){this.controls.rotateSpeed=e}get minPolarAngle(){return this.controls.minPolarAngle}set minPolarAngle(e){this.controls.minPolarAngle=e}get maxPolarAngle(){return this.controls.maxPolarAngle}set maxPolarAngle(e){this.controls.maxPolarAngle=e}get minAzimuthAngle(){return this.controls.minAzimuthAngle}set minAzimuthAngle(e){this.controls.minAzimuthAngle=e}get maxAzimuthAngle(){return this.controls.maxAzimuthAngle}set maxAzimuthAngle(e){this.controls.maxAzimuthAngle=e}get panSpeed(){return this.controls.panSpeed}set panSpeed(e){this.controls.panSpeed=e}get screenSpacePanning(){return this.controls.screenSpacePanning}set screenSpacePanning(e){this.controls.screenSpacePanning=e}get target(){return this.targetAdapter}update(){return this.controls.update()}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}get autoRotate(){return this.controls.autoRotate}set autoRotate(e){this.controls.autoRotate=e}get autoRotateSpeed(){return this.controls.autoRotateSpeed}set autoRotateSpeed(e){this.controls.autoRotateSpeed=e}getThreeControls(){return this.controls}}class dl extends Wr{constructor(e,t){super(new jr(e,t))}get type(){return"orbit"}}class fl extends Wr{constructor(e,t){const n=new ul(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Rn=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function zt(i){return Rn(i,"getThreeObject")??(i instanceof E.Object3D?i:null)}function vn(i){return Rn(i,"getThreeCamera")??(i instanceof E.Camera?i:null)}function di(i){return Rn(i,"getThreeScene")??(i instanceof E.Scene?i:null)}function Zr(i){return Rn(i,"getThreeRenderer")??(i instanceof E.WebGLRenderer?i:null)}function xi(i){return Rn(i,"getThreeControls")}const fi="contact-shadow-baked",on="contact-shadow-live",Ai="softboxContactShadowHelper",yr=Math.PI*(3-Math.sqrt(5)),xe=class xe{constructor(e){this.explicitPasses=e==null?void 0:e.passes}bake(e){const{renderer:t,scene:n,object:s,light:r}=e;if(t.getContext().isContextLost()){this.leaveLiveCatcherInCharge(n);return}const o=this.measureBakeRegion(s);if(!o)return;const a=n.getObjectByName(on);(a==null?void 0:a.geometry)instanceof E.CircleGeometry&&(o.halfExtent=Math.min(o.halfExtent,a.geometry.parameters.radius));const c=new E.WebGLRenderTarget(xe.ACCUMULATION_TEXTURE_SIZE,xe.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?E.HalfFloatType:E.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),u=new E.CircleGeometry(o.halfExtent,64);if(this.accumulateShadowPasses(t,s,r,o,c,u),t.getContext().isContextLost()){c.dispose(),u.dispose(),this.leaveLiveCatcherInCharge(n),console.warn("Contact-shadow bake aborted: WebGL context was lost mid-bake");return}this.installBakedMesh(n,o,c,u)}leaveLiveCatcherInCharge(e){this.evictBakedMesh(e);const t=e.getObjectByName(on);t&&(t.visible=!0)}evictBakedMesh(e){const t=e.getObjectByName(fi);t&&(e.remove(t),xs(t))}measureBakeRegion(e){const t=new E.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new E.Vector3),s=t.getCenter(new E.Vector3),o=Math.max(Math.max(n.x,n.z)*1.6+n.y,.05);return{center:s,halfExtent:o,objectHeight:n.y}}accumulateShadowPasses(e,t,n,s,r,o){const a=new E.Scene,c=t.parent;a.add(t);const u=this.disableColorWrite(t),d=this.createBakeLight(n);a.add(d),a.add(d.target),d.target.position.copy(n.target.parent?n.target.getWorldPosition(new E.Vector3):n.target.position);const h=new E.ShadowMaterial({transparent:!0,opacity:0,depthWrite:!1});h.blending=E.CustomBlending,h.blendEquation=E.AddEquation,h.blendSrc=E.OneFactor,h.blendDst=E.OneFactor;const f=new E.Mesh(o,h);f.rotation.x=-Math.PI/2,f.position.set(s.center.x,0,s.center.z),f.receiveShadow=!0,a.add(f);const m=this.createBakeCamera(s);a.add(m);const w=e.getRenderTarget(),b=e.autoClear,_=e.getClearColor(new E.Color),A=e.getClearAlpha(),T=e.shadowMap.autoUpdate;try{e.shadowMap.autoUpdate=!0,e.setRenderTarget(r),e.setClearColor(0,0),e.clear(!0,!1,!1),e.autoClear=!1;const x=this.explicitPasses??this.measureAffordablePasses(e,a,m,n,d,r);h.opacity=1/x;for(const S of this.sampleLightPositions(n,x))d.position.copy(S),e.render(a,m)}finally{e.autoClear=b,e.setClearColor(_,A),e.setRenderTarget(w),e.shadowMap.autoUpdate=T,this.restoreColorWrite(u),c?c.add(t):a.remove(t),d.dispose(),h.dispose()}}measureAffordablePasses(e,t,n,s,r,o){r.position.copy(s.position),e.render(t,n),this.awaitGpuIdle(e,o);const a=performance.now();e.render(t,n),this.awaitGpuIdle(e,o);const c=Math.max(performance.now()-a,.01);return E.MathUtils.clamp(Math.round(xe.BAKE_BUDGET_MS/c),xe.MIN_PASSES,xe.MAX_PASSES)}awaitGpuIdle(e,t){if(!e.capabilities.textureTypeReadable(t.texture.type))return;const n=t.texture.type===E.HalfFloatType?new Uint16Array(4):new Uint8Array(4);e.readRenderTargetPixels(t,0,0,1,1,n)}createBakeLight(e){const t=new E.DirectionalLight(16777215,1);t.castShadow=!0,t.shadow.mapSize.set(xe.BAKE_SHADOW_MAP_SIZE,xe.BAKE_SHADOW_MAP_SIZE),t.shadow.bias=e.shadow.bias,t.shadow.normalBias=e.shadow.normalBias,t.shadow.radius=4;const n=e.shadow.camera,s=t.shadow.camera;return s.left=n.left,s.right=n.right,s.top=n.top,s.bottom=n.bottom,s.near=n.near,s.far=n.far,s.updateProjectionMatrix(),t}createBakeCamera(e){const t=new E.OrthographicCamera(-e.halfExtent,e.halfExtent,e.halfExtent,-e.halfExtent,.1,Math.max(e.objectHeight,1)*4);return t.position.set(e.center.x,Math.max(e.objectHeight,1)*2,e.center.z),t.up.set(0,0,-1),t.lookAt(e.center.x,0,e.center.z),t.updateProjectionMatrix(),t.updateMatrixWorld(!0),t}sampleLightPositions(e,t){const n=e.position.clone(),s=e.target.parent?e.target.getWorldPosition(new E.Vector3):e.target.position.clone(),r=s.clone().sub(n),o=r.length(),a=r.normalize(),c=new E.Vector3().crossVectors(a,new E.Vector3(0,1,0));c.lengthSq()<1e-6&&c.set(1,0,0),c.normalize();const u=new E.Vector3().crossVectors(a,c),d=Math.round(t*xe.AMBIENT_RATIO),h=t-d,f=E.MathUtils.degToRad(xe.LIGHT_APERTURE_DEGREES),m=Math.tan(f/2)*o,w=[];for(let A=0;A<h;A++){const T=m*Math.sqrt((A+.5)/h),x=A*yr;w.push(n.clone().addScaledVector(c,T*Math.cos(x)).addScaledVector(u,T*Math.sin(x)))}const b=Math.sin(E.MathUtils.degToRad(xe.AMBIENT_MIN_ELEVATION_DEGREES)),_=.98;for(let A=0;A<d;A++){const T=Math.sqrt((A+.5)/d),x=b+(_-b)*T,S=Math.sqrt(1-x*x),M=A*yr;w.push(new E.Vector3(S*Math.cos(M),x,S*Math.sin(M)).multiplyScalar(o).add(s))}return w}installBakedMesh(e,t,n,s){this.evictBakedMesh(e);const r=new E.MeshBasicMaterial({map:n.texture,transparent:!0,opacity:xe.SHADOW_STRENGTH,depthWrite:!1,toneMapped:!1});r.onBeforeCompile=u=>{u.fragmentShader=u.fragmentShader.replace("#include <map_fragment>",`#include <map_fragment>
|
|
2
|
+
diffuseColor.a = pow(diffuseColor.a, 0.75);`)},r.customProgramCacheKey=()=>"contact-shadow-alpha-gamma",r.addEventListener("dispose",()=>n.dispose());const o=new E.Mesh(s,r);o.name=fi,o.userData[Ai]=!0,o.rotation.x=-Math.PI/2;const a=E.MathUtils.clamp(t.objectHeight*.0025,2e-4,.01);o.position.set(t.center.x,a,t.center.z),o.userData.renderTarget=n,e.add(o);const c=e.getObjectByName(on);c&&(c.visible=!1)}disableColorWrite(e){const t=new Map;return e.traverse(n=>{const s=n;if(!s.isMesh)return;const r=Array.isArray(s.material)?s.material:[s.material];for(const o of r)o&&!t.has(o)&&(t.set(o,o.colorWrite),o.colorWrite=!1)}),t}restoreColorWrite(e){e.forEach((t,n)=>{n.colorWrite=t})}};xe.AMBIENT_RATIO=.45,xe.LIGHT_APERTURE_DEGREES=9,xe.AMBIENT_MIN_ELEVATION_DEGREES=55,xe.ACCUMULATION_TEXTURE_SIZE=1024,xe.BAKE_SHADOW_MAP_SIZE=1024,xe.SHADOW_STRENGTH=.85,xe.BAKE_BUDGET_MS=100,xe.MIN_PASSES=24,xe.MAX_PASSES=96;let pi=xe;const bn=class bn{static getHeight(e){return e*this.HEIGHT_RATIO}static getBevelSize(e){return e*this.BEVEL_RATIO}static getBevelThickness(e){return this.getBevelSize(e)}static getBaseSize(e){return e+this.getBevelSize(e)+this.getBevelThickness(e)}static getGapFactor(){return this.GAP_FACTOR}static getGridSpacing(e){const t=this.getBaseSize(e),n=this.getGapFactor();return{width:Math.sqrt(3)*t*n,height:2*t*n}}static getYPosition(e){return-this.getBevelSize(e)}};bn.HEIGHT_RATIO=.075,bn.BEVEL_RATIO=.04,bn.GAP_FACTOR=1.05;let Ut=bn;var _t=(i=>(i.SQUARE_WIRE="square_wire",i.HEXAGONAL_WIRE="hexagonal_wire",i.HEXAGONAL_GLASS="hexagonal_glass",i.STONE_TILES="stone_tiles",i.CUSTOM="custom",i))(_t||{});class pl{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new E.Color(e.color||8947848),r=new E.Color(e.centerLineColor||e.color||4473924),o=new E.GridHelper(t,n,r,s);if(e.opacity!==void 0&&e.opacity<1){const a=o.material;a.transparent=!0,a.opacity=e.opacity}return o}dispose(){}}class ml{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new E.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)??Math.floor(e.divisions/2),s=e.size/Math.max(1,n*2),r=new E.Color(e.color||8947848),o=e.opacity||.4,a=new E.LineBasicMaterial({color:r,transparent:!0,opacity:o}),c=s*Math.sqrt(3),u=s*2;for(let h=-n;h<=n;h++){const f=Math.max(-n,-h-n),m=Math.min(n,-h+n);for(let w=f;w<=m;w++){const b=c*(h+w/2),_=u*.75*w,A=[],T=Math.PI*2/6;for(let M=0;M<=6;M++){const P=M*T+Math.PI/6,I=b+s*Math.cos(P),C=_+s*Math.sin(P);A.push(new E.Vector3(I,0,C))}const x=new E.BufferGeometry().setFromPoints(A),S=new E.Line(x,a);t.add(S)}}return t}dispose(){}}class gl{constructor(e,t,n,s={}){this.position=e,this.size=t,this.color=n,this.materialOptions=s,this.height=Ut.getHeight(this.size),this.bevel=Ut.getBevelSize(this.size)}createGeometry(){const e=new E.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let o=0;o<6;o++){const a=t*Math.cos(o*n),c=t*Math.sin(o*n);o===0?e.moveTo(a,c):e.lineTo(a,c)}e.closePath();const s={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:2},r=new E.ExtrudeGeometry(e,s);return r.rotateZ(Math.PI/6),r.rotateX(Math.PI/2),r.translate(this.position.x,this.position.y,this.position.z),r}createMaterial(){const{metalness:e=0,roughness:t=.15,transmission:n=1,thickness:s=.4,ior:r=1.5}=this.materialOptions,o=n>0;return new E.MeshPhysicalMaterial({color:new E.Color(this.color),metalness:e,roughness:t,transparent:o,transmission:n,thickness:s,ior:r,opacity:1,clearcoat:o?1:0,clearcoatRoughness:.05,sheen:o?1:0,sheenColor:new E.Color(16777215),envMapIntensity:1})}}function yl(i,e){var d;const t=i.getIndex()?i.toNonIndexed():i,n=t.getAttribute("position").array,s=t.getAttribute("normal").array,r=(d=t.getAttribute("uv"))==null?void 0:d.array,o=new Float32Array(n.length*e.length),a=new Float32Array(s.length*e.length),c=r?new Float32Array(r.length*e.length):void 0;e.forEach((h,f)=>{const m=f*n.length;o.set(n,m);for(let w=m;w<m+n.length;w+=3)o[w]+=h.x,o[w+1]+=h.y,o[w+2]+=h.z;a.set(s,f*s.length),c&&r&&c.set(r,f*r.length)});const u=new E.BufferGeometry;return u.setAttribute("position",new E.BufferAttribute(o,3)),u.setAttribute("normal",new E.BufferAttribute(a,3)),c&&u.setAttribute("uv",new E.BufferAttribute(c,2)),u}class wl{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var w,b,_,A,T,x,S;const t=new E.Group,n=((w=e.styleOptions)==null?void 0:w.hexRadius)??Math.floor(e.divisions/2),s=((b=e.styleOptions)==null?void 0:b.tileSize)||1,r=String(e.color||"#ffffff"),o=Ut.getGridSpacing(s),a=o.width,c=o.height,u=new gl(new E.Vector3(0,0,0),s,r,{metalness:(_=e.styleOptions)==null?void 0:_.metalness,roughness:(A=e.styleOptions)==null?void 0:A.roughness,transmission:(T=e.styleOptions)==null?void 0:T.transmission,thickness:(x=e.styleOptions)==null?void 0:x.thickness,ior:(S=e.styleOptions)==null?void 0:S.ior}),d=u.createGeometry(),h=Ut.getYPosition(s),f=[];for(let M=-n;M<=n;M++){const P=Math.max(-n,-M-n),I=Math.min(n,-M+n);for(let C=P;C<=I;C++)f.push(new E.Vector3(a*(M+C/2),h,c*.75*C))}const m=new E.Mesh(yl(d,f),u.createMaterial());return m.receiveShadow=!0,t.add(m),d.dispose(),t.add(this.createShadowCatcher(a*(n+.5))),t}createShadowCatcher(e){const t=new E.Mesh(new E.CircleGeometry(Math.max(e,1),64),new E.ShadowMaterial({opacity:.35}));return t.name=on,t.userData[Ai]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class El{constructor(){this.name="Stone Tile Grid",this.textureLoader=new E.TextureLoader}createGrid(e){var m,w,b,_;const t=new E.Group,n=e.size,s=Math.max(1,e.divisions),r=n/s,o=r*.02,a=r-o,c=((m=e.styleOptions)==null?void 0:m.height)||r*.05,u=((w=e.styleOptions)==null?void 0:w.bevelSize)||c*.2,d=((b=e.styleOptions)==null?void 0:b.randomHeight)||!1,h=((_=e.styleOptions)==null?void 0:_.randomRotation)||!1,f=this.createStoneMaterial(e);for(let A=0;A<s;A++)for(let T=0;T<s;T++){const x=(A-s/2)*r+r/2,S=(T-s/2)*r+r/2,M=d?c*(.8+Math.random()*.4):c,P=new E.Shape,I=a/2;P.moveTo(-I,-I),P.lineTo(I,-I),P.lineTo(I,I),P.lineTo(-I,I),P.closePath();const C={depth:M,bevelEnabled:!0,bevelSize:u,bevelThickness:u,bevelSegments:2},D=new E.ExtrudeGeometry(P,C);D.rotateX(-Math.PI/2);const L=new E.Mesh(D,f);L.position.set(x,-M/2,S),L.castShadow=!0,L.receiveShadow=!0,h&&(L.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(L)}return t}createStoneMaterial(e){var o,a,c,u,d;const t=new E.Color(e.color||8421504),n=((o=e.styleOptions)==null?void 0:o.metalness)||0,s=((a=e.styleOptions)==null?void 0:a.roughness)||.8,r={color:t,metalness:n,roughness:s};if((c=e.styleOptions)!=null&&c.texture){const h=this.loadTexture(e.styleOptions.texture);h&&(r.map=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}if((u=e.styleOptions)!=null&&u.normalMap){const h=this.loadTexture(e.styleOptions.normalMap);h&&(r.normalMap=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const h=this.loadTexture(e.styleOptions.roughnessMap);h&&(r.roughnessMap=h,h.wrapS=h.wrapT=E.RepeatWrapping,h.repeat.set(1,1))}return new E.MeshStandardMaterial(r)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}const vi=class vi{static createGrid(e,t){const n=this.gridStyles.get(e);if(!n){console.warn(`Unknown grid type: ${e}, falling back to square wire grid`);const r=this.gridStyles.get(_t.SQUARE_WIRE);if(!r)throw new Error("Square wire grid style not found");return r.createGrid(t)}const s=n.createGrid(t);return s.name=`Grid_${e}`,s}static registerGridStyle(e,t){this.gridStyles.set(e,t)}static getAvailableTypes(){return Array.from(this.gridStyles.keys())}static disposeGridStyle(e){const t=this.gridStyles.get(e);t&&t.dispose&&t.dispose()}};vi.gridStyles=new Map([[_t.SQUARE_WIRE,new pl],[_t.HEXAGONAL_WIRE,new ml],[_t.HEXAGONAL_GLASS,new wl],[_t.STONE_TILES,new El]]);let gs=vi;const wr=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};class Tl{constructor(){this.contactShadowBaker=new pi}addHelpers(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene();if(t.grid){const s=n.userData,r=typeof t.grid=="object"?t.grid:null,o={enabled:!0,color:(r==null?void 0:r.colorGrid)||t.gridColor||"#AAAAAA",type:r!=null&&r.type?r.type:_t.HEXAGONAL_GLASS,opacity:r==null?void 0:r.opacity,styleOptions:r==null?void 0:r.styleOptions};if(n.userData={...s,gridOptions:o},r!=null&&r.size||r!=null&&r.divisions){const a=o.type||_t.HEXAGONAL_GLASS,c=r.size||10,u=r.divisions||10,d={size:c,divisions:u,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:Math.floor(u/2),tileSize:1,...o.styleOptions}},h=gs.createGrid(a,d);h.userData.isGrid=!0,h.userData.isDefaultGrid=!0,n.add(h)}}if(t.axes){const s=t.axesSize||5,r=new E.AxesHelper(s);n.add(r)}return F.ok(void 0)}catch(n){return F.err(new K("Failed to add helpers to scene",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}addDynamicGrid(e,t,n=1.2){var s;try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const r=e.getThreeScene(),o=r.userData,a=o==null?void 0:o.gridOptions;if(!(a!=null&&a.enabled))return F.ok(void 0);const c=[];r.traverse(D=>{var L,k,N;((L=D.userData)!=null&&L.isGrid||(k=D.userData)!=null&&k.isHexGrid||(N=D.userData)!=null&&N.isDefaultGrid)&&c.push(D)}),c.forEach(D=>{xs(D),r.remove(D)});let u;t instanceof De||"getThreeObject"in t&&typeof t.getThreeObject=="function"?u=t.getThreeObject():u=t;const d=new E.Box3().setFromObject(u),h=d.getSize(new E.Vector3);if(d.isEmpty()||!Number.isFinite(h.x)||!Number.isFinite(h.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),F.ok(void 0);const f=(s=a.styleOptions)==null?void 0:s.tileSize,m=typeof f=="number"?f:1,b=Ut.getGridSpacing(m).width,_=Math.max(h.x,h.z)*n+h.y;let A=_<=b?0:Math.ceil((_/b-1)/2);const T=60;A>T&&(console.warn(`Dynamic grid would need ${A} rings to cover the object; capping at ${T}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),A=T),_<b*.8?A=0:A<3&&_>b*2&&(A=3);const x=a.type||_t.HEXAGONAL_GLASS,M={size:Math.max(h.x,h.z)*n,divisions:A*2+1,color:a.color,opacity:a.opacity,styleOptions:{hexRadius:A,tileSize:m,...a.styleOptions}},P=gs.createGrid(x,M);P.userData.isGrid=!0,P.userData.isHexGrid=!0;const I=P.getObjectByName(on);I&&(I.position.y=E.MathUtils.clamp(h.y*.0025,2e-4,.002));const C=d.getCenter(new E.Vector3);return P.position.set(C.x,0,C.z),r.add(P),F.ok(void 0)}catch(r){return F.err(new K("Failed to add dynamic grid",Y.SCENE_OPERATION_FAILED,{originalError:r}))}}snapObjectToFloor(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));let n;t instanceof De||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=S=>{var P,I,C;let M=S;for(;M;){if((P=M.userData)!=null&&P.isGrid||(I=M.userData)!=null&&I.isHexGrid||(C=M.userData)!=null&&C.isDefaultGrid)return!0;M=M.parent}return!1},r=e.getThreeScene();r.updateMatrixWorld(!0);const o=[];r.traverse(S=>{S.isMesh&&s(S)&&o.push(S)});const a=[];if(n.traverse(S=>{S.isMesh&&a.push(S)}),o.length===0||a.length===0)return F.ok(void 0);let c=-1/0;const u=new E.Box3;for(const S of o)u.setFromObject(S),Number.isFinite(u.max.y)&&(c=Math.max(c,u.max.y));if(!Number.isFinite(c))return F.ok(void 0);const d=new E.Box3().setFromObject(n);if(d.isEmpty()||!Number.isFinite(d.min.x)||!Number.isFinite(d.max.x))return F.ok(void 0);const h=40,f=Math.max(1,d.max.y-d.min.y),m=d.max.y+f,w=d.min.y-f,b=new E.Raycaster,_=new E.Vector3(0,-1,0),A=new E.Vector3(0,1,0);let T=1/0;const x=(S,M,P,I)=>{b.set(new E.Vector3(S,M,P),I);for(const C of b.intersectObjects(a,!1))C.point.y<T&&(T=C.point.y)};for(let S=0;S<=h;S++)for(let M=0;M<=h;M++){const P=d.min.x+(d.max.x-d.min.x)*(S/h),I=d.min.z+(d.max.z-d.min.z)*(M/h);x(P,m,I,_),x(P,w,I,A)}if(Number.isFinite(T)){const S=T-c;Math.abs(S)>1e-4&&(n.position.y-=S)}return F.ok(void 0)}catch(n){return F.err(new K("Failed to snap object to floor",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}fitShadowCameraToObject(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));let n;t instanceof De||"getThreeObject"in t&&typeof t.getThreeObject=="function"?n=t.getThreeObject():n=t;const s=new E.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return F.ok(void 0);const r=s.getSize(new E.Vector3),o=s.getCenter(new E.Vector3),a=e.getThreeScene(),c=wr(a);if(!c||!c.castShadow)return F.ok(void 0);if(c.parent===a&&c.target.parent===a){const w=c.position.clone().sub(c.target.position);c.target.position.copy(o),c.position.copy(o).add(w)}const f=Math.max(r.x,r.y,r.z,.1)*2,m=c.shadow.camera;return m.left=-f,m.right=f,m.top=f,m.bottom=-f,m.updateProjectionMatrix(),F.ok(void 0)}catch(n){return F.err(new K("Failed to fit shadow camera to object",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}bakeContactShadow(e,t,n){try{const s=di(e);if(!s)return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const r=zt(t);if(!r)return F.err(new K("Object must expose a Three.js Object3D",Y.INVALID_PARAMETER));const o=Zr(n.getInternalRenderer());if(!o||!o.shadowMap.enabled)return F.ok(void 0);const a=wr(s);return!a||!a.castShadow||this.contactShadowBaker.bake({renderer:o,scene:s,object:r,light:a}),F.ok(void 0)}catch(s){return F.err(new K("Failed to bake contact shadow",Y.SCENE_OPERATION_FAILED,{originalError:s}))}}setContactShadowMode(e,t){try{const n=di(e);if(!n)return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const s=n.getObjectByName(fi),r=n.getObjectByName(on);return t==="baked"&&!s||(s&&(s.visible=t==="baked"),r&&(r.visible=t==="live")),F.ok(void 0)}catch(n){return F.err(new K("Failed to switch contact shadow mode",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}wrapInUnitsScaleGroup(e,t){try{const n=zt(e);if(!n)return F.err(new K("Object must expose a Three.js Object3D",Y.INVALID_PARAMETER));const s=new E.Group;return s.name=$o,s.scale.setScalar(t),s.add(n),F.ok(new De(s))}catch(n){return F.err(new K("Failed to apply the units scale to the model",Y.SCENE_OPERATION_FAILED,{originalError:n}))}}addLighting(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene();if(t.ambient){const s=new E.Color(t.ambient.color||"#404040"),r=t.ambient.intensity??Math.PI,o=new E.AmbientLight(s,r);n.add(o)}if(t.hemisphere){const s=new E.Color(t.hemisphere.skyColor||"#ffffbb"),r=new E.Color(t.hemisphere.groundColor||"#080820"),o=t.hemisphere.intensity??1,a=new E.HemisphereLight(s,r,o);n.add(a)}if(t.directional){const s=new E.Color(t.directional.color||"#ffffff"),r=t.directional.intensity??Math.PI,o=new E.DirectionalLight(s,r);if(t.directional.position){const a=t.directional.position;if(a instanceof E.Vector3)o.position.copy(a);else if(Array.isArray(a))o.position.set(a[0],a[1],a[2]);else if(typeof a=="object"&&"x"in a&&"y"in a&&"z"in a){const c=a;o.position.set(c.x,c.y,c.z)}}else o.position.set(6,6,6);if(t.directional.castShadow&&(o.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(o.shadow.mapSize.width=a.mapSize.width,o.shadow.mapSize.height=a.mapSize.height),a.camera){const c=o.shadow.camera;a.camera.near!==void 0&&(c.near=a.camera.near),a.camera.far!==void 0&&(c.far=a.camera.far),a.camera.left!==void 0&&(c.left=a.camera.left),a.camera.right!==void 0&&(c.right=a.camera.right),a.camera.top!==void 0&&(c.top=a.camera.top),a.camera.bottom!==void 0&&(c.bottom=a.camera.bottom)}a.bias!==void 0&&(o.shadow.bias=a.bias),a.radius!==void 0&&(o.shadow.radius=a.radius)}o.target.position.set(0,0,0),n.add(o),n.add(o.target),o.shadow&&o.shadow.camera.updateProjectionMatrix()}return F.ok(void 0)}catch(n){return F.err(new K("Failed to add lighting to scene",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof St))return F.err(new K("Scene must be ThreeSceneAdapter",Y.INVALID_PARAMETER));const n=e.getThreeScene(),s=document.createElement("canvas");s.width=2,s.height=512;const r=s.getContext("2d");if(!r)return F.err(new K("Failed to create canvas context",Y.SCENE_OPERATION_FAILED));const o=r.createLinearGradient(0,0,0,s.height);o.addColorStop(0,t.topColor),o.addColorStop(1,t.bottomColor),r.fillStyle=o,r.fillRect(0,0,s.width,s.height);const a=new E.CanvasTexture(s);a.needsUpdate=!0;const c=n.background;return c instanceof E.Texture&&c!==n.environment&&c.dispose(),n.background=a,F.ok(void 0)}catch(n){return F.err(new K("Failed to create gradient background",Y.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}fitCameraToObject(e,t,n){try{const s=zt(e)??e,r=vn(t)??t,o=xi(n)??n,a=new E.Box3().setFromObject(s),c=a.getCenter(new E.Vector3),u=a.getSize(new E.Vector3),d=Math.max(u.x,u.y,u.z);let h;"fov"in r?h=r.fov*(Math.PI/180):h=50*(Math.PI/180);let f=Math.abs(d/2/Math.tan(h/2));f*=2;const m=-Math.PI/4,w=Math.PI/8,b=c.x+f*Math.sin(m)*Math.cos(w),_=c.y+f*Math.sin(w),A=c.z+f*Math.cos(m)*Math.cos(w);return r.position.set(b,_,A),r.lookAt(c),r.updateProjectionMatrix(),o&&o.target&&(o.target.copy(c),o.update()),F.ok(void 0)}catch(s){return F.err(new K("Failed to fit camera to object",Y.CAMERA_INIT_FAILED,{originalError:s}))}}}class Sl{constructor(){this.events=new Es,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-CVTgPYSp.cjs"));if(this.disposed)return F.ok(void 0);const n=new t;return this.inner=n,n.events.on("pathtracing:paused",s=>{this.events.emit("pathtracing:paused",s)}),this.pendingSettings&&(n.updateSettings(this.pendingSettings),this.pendingSettings=void 0),this.pendingEnabled!==void 0&&(n.setEnabled(this.pendingEnabled),this.pendingEnabled=void 0),n.initialize(e)}setEnabled(e){this.inner?this.inner.setEnabled(e):this.pendingEnabled=e}updateSettings(e){this.inner?this.inner.updateSettings(e):this.pendingSettings={...this.pendingSettings,...e}}render(e,t){return this.inner?this.inner.render(e,t):Promise.resolve(F.ok(void 0))}getSampleCount(){var e;return((e=this.inner)==null?void 0:e.getSampleCount())??0}isEnabled(){var e;return((e=this.inner)==null?void 0:e.isEnabled())??!1}isPathTracerDisposed(){var e;return((e=this.inner)==null?void 0:e.isPathTracerDisposed())??!1}reset(e){var t;(t=this.inner)==null||t.reset(e)}dispose(){var e;this.disposed=!0,(e=this.inner)==null||e.dispose()}isSupported(){var e;return((e=this.inner)==null?void 0:e.isSupported())??!0}}/*!
|
|
3
3
|
fflate - fast JavaScript compression/decompression
|
|
4
4
|
<https://101arrowz.github.io/fflate>
|
|
5
5
|
Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
|