softbox 4.12.0 → 4.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +0,0 @@
1
- "use strict";var jo=Object.create;var Vi=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&&Vi(i,s,{get:()=>e[s],enumerable:!(n=Wo(e,s))||n.enumerable});return i};var Ps=(i,e,t)=>(t=i!=null?jo(Ko(i)):{},Yo(e||!i||!i.__esModule?Vi(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 y=qo(p);class Z 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,Z)}static fromError(e,t,n){if(e instanceof Z)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 Z(s,t,r)}}var K=(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))(K||{});const N={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return N.ok(i())}catch(e){return N.err(e instanceof Z?e:new Z(String(e),K.UNKNOWN,{originalError:e}))}}};class Ts{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 Js=300,Is={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(Is,e))throw new Z(`Unknown units '${String(e)}'. Valid values: ${Object.keys(Is).join(", ")}`,K.INVALID_PARAMETER);return Is[e]}const Hi="#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=n.backgroundColorEdge,f=h!==void 0?{topColor:d,bottomColor:String(h),radial:!0}:{topColor:d,bottomColor:d},m=t.createGradientBackground(e,f);m.ok||console.warn("Failed to set background:",m.error)}}async configureEnvironment(e,t,n,s,r,o){var d,h,f,m,w,x;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 b=await t.loadEnvironmentMap(u);if(o())return;b.ok?t.applyToScene(e,b.value,c):console.warn("Failed to load environment map:",b.error)}else if((w=r.helpers)!=null&&w.studioEnvironment){const b=t.createStudioEnvironment();if(b.ok){if(t.applyToScene(e,b.value,{...c,setBackground:!1}),(x=r.helpers)!=null&&x.darkStudioMode&&n){const v=n.createGradientBackground(e,{topColor:Hi,bottomColor:Hi});v.ok||console.warn("Failed to set dark studio background:",v.error)}}else console.warn("Failed to create studio environment:",b.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 Gn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function on(i,e){if(!Gn(i)||!Gn(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]=Gn(o)&&Gn(r)?on(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 ei(i,e){i.type==="perspective"&&"aspect"in i&&(i.aspect=e),i.updateProjectionMatrix()}class yt{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 yt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new yt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new yt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new yt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new yt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new yt({...this.data,status:"rendering"})}updateRenderInfo(e){return new yt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new yt({...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 yt,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 Cr(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=Cr(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.floorAlignment=e.floorAlignment??!0,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 Z("A units conversion is configured but no scene setup service is available to apply it",K.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.floorAlignment&&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);if(a.ok||console.warn("Failed to add dynamic grid:",a.error),this.floorAlignment){const u=this.sceneSetupService.snapObjectToFloor(this.scene,s);u.ok||console.warn("Failed to snap object to floor:",u.error)}const c=this.sceneSetupService.fitShadowCameraToObject(this.scene,s);if(c.ok||console.warn("Failed to fit shadow camera to object:",c.error),this.renderer){const u=this.sceneSetupService.bakeContactShadow(this.scene,s,this.renderer);u.ok||console.warn("Failed to bake contact shadow:",u.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}),N.ok(s)}catch(s){const r=s instanceof Z?s:new Z("Failed to load model",K.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:r,url:typeof e=="string"?e:void 0}),N.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))}}class ia{constructor(e){this.completeHandled=!1,this.suspendedForAnimation=!1,this.initialized=!1,this.initializing=!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)??Js}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(){this.isEnabled()&&await this.ensureInitialized()}async ensureInitialized(){const{service:e,getOptions:t,isDisposed:n,renderer:s,renderLoopManager:r,schedule:o}=this.deps;if(!(!e||this.initialized||this.initializing)){this.initializing=!0;try{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}this.initialized=!0;const c=t().pathTracing;c&&e.updateSettings({samples:c.maxSamples??Js,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:u})=>{r.releaseContinuous("path-tracing"),t().staticScene||r.setAlwaysRender(!1),o(()=>{r.hasContinuousDemand()||r.stop()},100),u==="gave-up"&&this.selfPauseListeners.forEach(d=>d())})}finally{this.initializing=!1}}}async enableRuntime(){var s;const{service:e,renderLoopManager:t,getOptions:n}=this.deps;return!e||(await this.ensureInitialized(),!this.initialized)||!(((s=n().pathTracing)==null?void 0:s.enabled)??!1)?!1:(e.setEnabled(!0),e.reset(!0),this.completeHandled=!1,this.suspendedForAnimation=!1,t.requireContinuous("path-tracing"),!0)}disableRuntime(){const{service:e,renderLoopManager:t}=this.deps;e&&(e.setEnabled(!1),e.reset(),t.releaseContinuous("path-tracing"),this.completeHandled=!1,this.suspendedForAnimation=!1,this.selfPauseListeners.forEach(n=>n()))}resetAccumulation(e=!1){const{service:t,renderLoopManager:n}=this.deps;!t||!this.isEnabled()||(t.reset(e),this.completeHandled=!1,!t.isEnabled()&&(t.canResume()||this.suspendedForAnimation)&&(this.suspendedForAnimation=!1,t.setEnabled(!0),n.requireContinuous("path-tracing")))}suspendWhileAnimating(){const e=this.deps.service;if(e)if(e.isEnabled()){const t=!this.suspendedForAnimation;this.suspendedForAnimation=!0,e.setEnabled(!1),this.deps.renderLoopManager.releaseContinuous("path-tracing"),t&&this.selfPauseListeners.forEach(n=>n())}else e.canResume()&&e.getSampleCount()>0&&(e.reset(),this.completeHandled=!1,this.suspendedForAnimation=!0)}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}=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 c=()=>{s.hasContinuousDemand()||s.stop()};if(r().replaceWithScreenshotOnComplete){o(()=>{a(),o(c,200)},100);return}s.requestRender(),o(c,100)}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 Pr(){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()?N.err(new Z("Cannot capture a still from a disposed viewer",K.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?N.err(new Z("Viewer was disposed while a model load finished",K.INVALID_STATE)):this.deps.isScreenshotActive()?N.err(new Z("Cannot capture a still while a screenshot is replacing the canvas",K.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 N.err(new Z("Cannot capture video from a disposed viewer",K.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return N.err(new Z("Viewer was disposed while a model load finished",K.INVALID_STATE));if(this.deps.isScreenshotActive())return N.err(new Z("Cannot capture video while a screenshot is replacing the canvas",K.INVALID_STATE));const t=e.duration??3;if(!(t>0))return N.err(new Z("Video duration must be a positive number of seconds",K.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return N.err(new Z("Video capture needs MediaRecorder and canvas.captureStream support",K.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()),N.err(new Z("Failed to start the video recorder",K.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:${Pr()}`;return this.deps.renderLoopManager.requireContinuous(u),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(h=>{const f=[];let m=null,w=!1;const x=v=>{w||(w=!0,this.pendingSettlers.delete(b),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(u),s.getTracks().forEach(T=>T.stop()),h(v))},b=()=>{x(N.err(new Z("Viewer was disposed during video capture",K.INVALID_STATE)));try{r.stop()}catch{}};this.pendingSettlers.add(b),r.ondataavailable=v=>{v.data.size>0&&f.push(v.data)},r.onstop=()=>{x(N.ok(new Blob(f,{type:r.mimeType||"video/webm"})))},r.onerror=()=>{x(N.err(new Z("Video recording failed",K.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 N.err(new Z("Path-traced stills are captured at the canvas resolution; omit width/height",K.INVALID_PARAMETER));if(this.deps.isAutoRotating())return N.err(new Z("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",K.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 N.err(new Z("Viewer was disposed while waiting for the path tracer",K.INVALID_STATE));if(n==="error")return N.err(new Z("Model failed while waiting for the path tracer",K.RENDER_FAILED));if(n==="turntable")return N.err(new Z("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",K.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 N.err(new Z("Cannot capture: the canvas has no size",K.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 N.err(new Z(`Requested still size ${f}x${m} is outside 1..${w}`,K.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),ei(s,f/m);const x=t.renderPostProcessed?t.renderPostProcessed(n,s):t.render(n,s),b=x.ok?this.readCanvasPng():N.err(x.error);return t.setSize(u,d),t.setPixelRatio(a),ei(s,h),t.render(n,s),r.requestRender(),b}readCanvasPng(){const e=Cr(this.deps.renderer.getDomElement());return e?N.ok(e):N.err(new Z("Canvas produced an empty image",K.RENDER_FAILED))}}class aa{constructor(e){var r;this.frameCount=0,this.disposed=!1,this.pendingTimers=new Set,this.modelLoadChain=Promise.resolve(),this.controlsChangeUnsubscribe=null,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,floorAlignment:this.options.floorAlignment,unitsScaleToMeters:t}),this.resourceManager=new sa({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new Qo,this.events=new Ts;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.controlsChangeUnsubscribe=this.controls.onChange(()=>{this.disposed||(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}),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()),N.ok(void 0)):n}catch(n){const s=new Z("Failed to initialize viewer",K.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),N.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 N.err(new Z("Cannot load model after dispose",K.INVALID_STATE));if(!this.stateManager.canLoad())return N.err(new Z("Cannot load model in current state",K.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(),N.err(new Z("Viewer was disposed while the model was loading",K.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.reviveRenderLoop(),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(!0),N.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof Z?t:new Z("Failed to load model",K.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),N.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var a;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,s=((a=this.animationService)==null?void 0:a.isPlaying())??!1;(this.controls.enabled?this.controls.update():!1)&&(this.events.emit("controls:change",{controls:this.controls}),s||this.pathTracing.resetAccumulation(),this.renderLoopManager.requestRender()),s&&this.animationService&&(this.animationService.update(e/1e3),this.pathTracing.suspendWhileAnimating());const o=this.pathTracing.beforeFrame();this.renderFrame().catch(c=>{console.error("[ViewerCore] Render frame error:",c)}),this.pathTracing.detectCompletion(o,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.renderRaster()));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()})}renderRaster(){return this.renderer.renderPostProcessed?this.renderer.renderPostProcessed(this.scene,this.camera):this.renderer.render(this.scene,this.camera)}updateOptions(e){var w,x,b,v,T,S,_,A,L,I,C;if(this.disposed)return;const t=(w=this.options.animations)==null?void 0:w.autoplay,n=(x=this.options.controls)==null?void 0:x.autoRotate,s=((b=this.options.pathTracing)==null?void 0:b.enabled)??!1;this.options=on(this.options,e),"backgroundColorEdge"in e&&(this.options.backgroundColorEdge=e.backgroundColorEdge);let r=!1;(e.backgroundColor!==void 0||e.backgroundColorEdge!==void 0)&&this.options.backgroundColor!==void 0&&this.applyBackgroundColor(this.options.backgroundColor);const a=(v=e.renderer)==null?void 0:v.toneMappingExposure;a!==void 0&&(this.renderer.setToneMappingExposure(a),r=!0);const c=(T=e.environment)==null?void 0:T.environmentIntensity;c!==void 0&&(this.scene.setEnvironmentIntensity(c),r=!0);const u=(S=e.controls)==null?void 0:S.autoRotate;u!==void 0&&u!==n&&(this.controls.autoRotate=u,u?(this.renderLoopManager.requireContinuous("turntable"),this.capture.notifyTurntableEnabled()):this.renderLoopManager.releaseContinuous("turntable"),r=!0);const d=(_=e.controls)==null?void 0:_.autoRotateSpeed;d!==void 0&&(this.controls.autoRotateSpeed=d,r=!0);const h=(A=e.animations)==null?void 0:A.autoplay;h!==void 0&&h!==t&&(h?this.modelManager.getCurrentModel()&&this.autoplayFromOptions(h):this.pauseAnimations(),r=!0);const f=(L=e.animations)==null?void 0:L.speed;f!==void 0&&((I=this.animationService)==null||I.setSpeed(f),r=!0);const m=(C=e.pathTracing)==null?void 0:C.enabled;m!==void 0&&m!==s&&(this.setPathTracingEnabled(m),r=!0),r&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}backgroundGradient(e,t){return t!==void 0?{topColor:String(e),bottomColor:String(t),radial:!0}:{topColor:String(e),bottomColor:String(e)}}applyBackgroundColor(e){var s;if((s=this.options.environment)!=null&&s.url||!this.sceneSetupService)return;const t=this.backgroundGradient(e,this.options.backgroundColorEdge),n=this.sceneSetupService.createGradientBackground(this.scene,t);if(!n.ok){console.warn("Failed to update background color:",n.error);return}this.renderLoopManager.requestRender()}async setEnvironmentMap(e){var s,r,o;if(this.disposed)return N.ok(void 0);if(!this.environmentService)return N.err(new Z("Environment service unavailable",K.INVALID_STATE));const t=await this.environmentService.loadEnvironmentMap(e);if(this.disposed)return N.ok(void 0);if(!t.ok)return N.err(t.error);const n=this.environmentService.applyToScene(this.scene,t.value,{backgroundBlurriness:(s=this.options.environment)==null?void 0:s.backgroundBlurriness,backgroundIntensity:(r=this.options.environment)==null?void 0:r.backgroundIntensity,environmentIntensity:(o=this.options.environment)==null?void 0:o.environmentIntensity,setBackground:!0});return n.ok?(this.options=on(this.options,{environment:{url:e}}),this.repaintAfterEnvironmentChange(),N.ok(void 0)):n}resetEnvironment(){if(this.disposed)return N.ok(void 0);if(!this.environmentService)return N.err(new Z("Environment service unavailable",K.INVALID_STATE));const e=this.environmentService.createStudioEnvironment();return e.ok?(this.environmentService.applyToScene(this.scene,e.value,{setBackground:!1}),this.options.environment&&(this.options.environment.url=void 0),this.restoreBackgroundColor(),this.repaintAfterEnvironmentChange(),N.ok(void 0)):N.err(e.error)}async setBackgroundImage(e){if(this.disposed)return N.ok(void 0);if(!this.environmentService)return N.err(new Z("Environment service unavailable",K.INVALID_STATE));const t=await this.environmentService.setBackgroundImage(this.scene,e);return this.disposed?N.ok(void 0):t.ok?(this.repaintAfterEnvironmentChange(),N.ok(void 0)):t}setBackgroundColor(e){if(this.disposed)return N.ok(void 0);if(!this.sceneSetupService)return N.err(new Z("Scene setup service unavailable",K.INVALID_STATE));const t=this.sceneSetupService.createGradientBackground(this.scene,this.backgroundGradient(e,void 0));return t.ok?(this.options=on(this.options,{backgroundColor:e}),this.options.backgroundColorEdge=void 0,this.repaintAfterEnvironmentChange(),N.ok(void 0)):t}restoreBackgroundColor(){const e=this.options.backgroundColor;e===void 0||!this.sceneSetupService||this.sceneSetupService.createGradientBackground(this.scene,this.backgroundGradient(e,this.options.backgroundColorEdge))}repaintAfterEnvironmentChange(){this.pathTracing.resetAccumulation(!0),this.reviveRenderLoop(),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();ei(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()}setPathTracingEnabled(e){e?this.pathTracing.enableRuntime().then(t=>{t&&!this.disposed&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}):(this.pathTracing.disableRuntime(),this.reviveRenderLoop(),this.renderLoopManager.requestRender())}getAnimationNames(){var e;return((e=this.animationService)==null?void 0:e.getClipNames())??[]}playAnimations(e){var n;if(!this.animationService)return e!==void 0?N.err(new Z(`Cannot play animation clip '${e}': the viewer was assembled without an animation service`,K.INVALID_STATE)):N.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()),N.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.pathTracing.resetAccumulation(!0),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,n;this.disposed=!0,this.pendingTimers.forEach(s=>clearTimeout(s)),this.pendingTimers.clear(),this.stopRenderLoop(),(e=this.controlsChangeUnsubscribe)==null||e.call(this),this.controlsChangeUnsubscribe=null,(t=this.selectionService)==null||t.dispose(),(n=this.animationService)==null||n.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 Dt{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 Dt(e)}static create(e=0,t=0,n=0){return new Dt(new y.Vector3(e,t,n))}}const Ir=0,ca=1,Lr=2,Gi=2,Ls=1.25,ji=1,Ve=32,De=Ve/4,Si=65535,la=Si<<16,fs=Math.pow(2,-24),bi=Symbol("SKIP_GENERATION"),Or={strategy:Ir,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[bi]:!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 Wi(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 Zi(i,e){e.set(i)}function Ki(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 jn(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 fn(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 Pe(i,e){return e[i+15]===Si}function He(i,e){return e[i+6]}function Xe(i,e){return e[i+14]}function Fe(i){return i+De}function Be(i,e){const t=e[i+6];return i+t*De}function Ss(i,e){return e[i+7]}function ha(i){return i}function Os(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,x=-1/0,b=-1/0;const v=i.offset||0;for(let T=(e-v)*6,S=(e+t-v)*6;T<S;T+=6){const _=i[T+0],A=i[T+1],L=_-A,I=_+A;L<r&&(r=L),I>c&&(c=I),_<h&&(h=_),_>w&&(w=_);const C=i[T+2],D=i[T+3],P=C-D,F=C+D;P<o&&(o=P),F>u&&(u=F),C<f&&(f=C),C>x&&(x=C);const k=i[T+4],G=i[T+5],z=k-G,Y=k+G;z<a&&(a=z),Y>d&&(d=Y),k<m&&(m=k),k>b&&(b=k)}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]=x,s[5]=b}const bt=32,ua=(i,e)=>i.candidate-e.candidate,Mt=new Array(bt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Wn=new Float32Array(6);function da(i,e,t,n,s,r){let o=-1,a=0;if(r===Ir)o=Wi(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ca)o=Wi(i),o!==-1&&(a=fa(t,n,s,o));else if(r===Lr){const c=fn(i);let u=Ls*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],v=(e[m+3]-w)/bt;if(s<bt/4){const T=[...Mt];T.length=s;let S=0;for(let A=h;A<f;A+=6,S++){const L=T[S];L.candidate=t[A+2*m],L.count=0;const{bounds:I,leftCacheBounds:C,rightCacheBounds:D}=L;for(let P=0;P<3;P++)D[P]=1/0,D[P+3]=-1/0,C[P]=1/0,C[P+3]=-1/0,I[P]=1/0,I[P+3]=-1/0;jn(A,t,I)}T.sort(ua);let _=s;for(let A=0;A<_;A++){const L=T[A];for(;A+1<_&&T[A+1].candidate===L.candidate;)T.splice(A+1,1),_--}for(let A=h;A<f;A+=6){const L=t[A+2*m];for(let I=0;I<_;I++){const C=T[I];L>=C.candidate?jn(A,t,C.rightCacheBounds):(jn(A,t,C.leftCacheBounds),C.count++)}}for(let A=0;A<_;A++){const L=T[A],I=L.count,C=s-L.count,D=L.leftCacheBounds,P=L.rightCacheBounds;let F=0;I!==0&&(F=fn(D)/c);let k=0;C!==0&&(k=fn(P)/c);const G=ji+Ls*(F*I+k*C);G<u&&(o=m,u=G,a=L.candidate)}}else{for(let _=0;_<bt;_++){const A=Mt[_];A.count=0,A.candidate=w+v+_*v;const L=A.bounds;for(let I=0;I<3;I++)L[I]=1/0,L[I+3]=-1/0}for(let _=h;_<f;_+=6){let I=~~((t[_+2*m]-w)/v);I>=bt&&(I=bt-1);const C=Mt[I];C.count++,jn(_,t,C.bounds)}const T=Mt[bt-1];Zi(T.bounds,T.rightCacheBounds);for(let _=bt-2;_>=0;_--){const A=Mt[_],L=Mt[_+1];Ki(A.bounds,L.rightCacheBounds,A.rightCacheBounds)}let S=0;for(let _=0;_<bt-1;_++){const A=Mt[_],L=A.count,I=A.bounds,D=Mt[_+1].rightCacheBounds;L!==0&&(S===0?Zi(I,Wn):Ki(I,Wn,Wn)),S+=L;let P=0,F=0;S!==0&&(P=fn(Wn)/c);const k=s-S;k!==0&&(F=fn(D)/c);const G=ji+Ls*(P*S+F*k);G<u&&(o=m,u=G,a=A.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 Ds{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,ps,ti,Nr;const ma=Math.pow(2,32);function ni(i){return"count"in i?1:1+ni(i.left)+ni(i.right)}function ga(i,e,t){return Dr=new Float32Array(t),ps=new Uint32Array(t),ti=new Uint16Array(t),Nr=new Uint8Array(t),si(i,e)}function si(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):(ps[t+6]=e.offset,ti[n+14]=e.count,ti[n+15]=Si,i+Ve);{const{left:o,right:a,splitAxis:c}=e,u=i+Ve;let d=si(u,o);const h=i/Ve,m=d/Ve-h;if(m>ma)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ps[t+6]=m,ps[t+7]=c,si(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 x=new Ds;return Os(e,t,n,x.boundingData,m),v(x,t,n,m),x;function b(T){d&&d((T-r.offset)/r.count)}function v(T,S,_,A=null,L=0){if(!w&&L>=o&&(w=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`)),_<=c||L>=o)return b(S+_),T.offset=S,T.count=_,T;const I=da(T.boundingData,A,e,S,_,u);if(I.axis===-1)return b(S+_),T.offset=S,T.count=_,T;const C=pa(h,f,e,S,_,I);if(C===S||C===S+_)b(S+_),T.offset=S,T.count=_;else{T.splitAxis=I.axis;const D=new Ds,P=S,F=C-S;T.left=D,Os(e,P,F,D.boundingData,m),v(D,P,F,m,L+1);const k=new Ds,G=C,z=_-F;T.right=k,Os(e,G,z,k.boundingData,m),v(k,G,z,m,L+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=ni(u),h=new t(Ve*d);return ga(0,u,h),h})}class _i{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 _e=new Ea;let Ot,sn;const Zt=[],Zn=new _i(()=>new p.Box3);function Ta(i,e,t,n,s,r){Ot=Zn.getPrimitive(),sn=Zn.getPrimitive(),Zt.push(Ot,sn),_e.setBuffer(i._roots[e]);const o=ii(0,i.geometry,t,n,s,r);_e.clearBuffer(),Zn.releasePrimitive(Ot),Zn.releasePrimitive(sn),Zt.pop(),Zt.pop();const a=Zt.length;return a>0&&(sn=Zt[a-1],Ot=Zt[a-2]),o}function ii(i,e,t,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:c,uint32Array:u}=_e;let d=i*2;if(Pe(d,c)){const f=He(i,u),m=Xe(d,c);return Ae(i,a,Ot),n(f,m,!1,o,r+i/De,Ot)}else{let P=function(k){const{uint16Array:G,uint32Array:z}=_e;let Y=k*2;for(;!Pe(Y,G);)k=Fe(k),Y=k*2;return He(k,z)},F=function(k){const{uint16Array:G,uint32Array:z}=_e;let Y=k*2;for(;!Pe(Y,G);)k=Be(k,z),Y=k*2;return He(k,z)+Xe(Y,G)};const f=Fe(i),m=Be(i,u);let w=f,x=m,b,v,T,S;if(s&&(T=Ot,S=sn,Ae(w,a,T),Ae(x,a,S),b=s(T),v=s(S),v<b)){w=m,x=f;const k=b;b=v,v=k,T=S}T||(T=Ot,Ae(w,a,T));const _=Pe(w*2,c),A=t(T,_,b,o+1,r+w/De);let L;if(A===Gi){const k=P(w),z=F(w)-k;L=n(k,z,!0,o+1,r+w/De,T)}else L=A&&ii(w,e,t,n,s,r,o+1);if(L)return!0;S=sn,Ae(x,a,S);const I=Pe(x*2,c),C=t(S,I,v,o+1,r+x/De);let D;if(C===Gi){const k=P(x),z=F(x)-k;D=n(k,z,!0,o+1,r+x/De,S)}else D=C&&ii(x,e,t,n,s,r,o+1);return!!D}}const xn=new _e.constructor,gs=new _e.constructor,It=new _i(()=>new p.Box3),Kt=new p.Box3,Xt=new p.Box3,Ns=new p.Box3,ks=new p.Box3;let Fs=!1;function Sa(i,e,t,n){if(Fs)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Fs=!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++){xn.setBuffer(s[d]),c=0;const f=It.getPrimitive();Ae(0,xn.float32Array,f),f.applyMatrix4(u);for(let m=0,w=r.length;m<w&&(gs.setBuffer(r[m]),o=ht(0,0,t,u,n,a,c,0,0,f),gs.clearBuffer(),c+=r[m].byteLength/Ve,!o);m++);if(It.releasePrimitive(f),xn.clearBuffer(),a+=s[d].byteLength/Ve,o)break}return Fs=!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=gs,f=xn):(h=xn,f=gs);const m=h.float32Array,w=h.uint32Array,x=h.uint16Array,b=f.float32Array,v=f.uint32Array,T=f.uint16Array,S=i*2,_=e*2,A=Pe(S,x),L=Pe(_,T);let I=!1;if(L&&A)d?I=s(He(e,v),Xe(e*2,T),He(i,w),Xe(i*2,x),c,o+e/De,a,r+i/De):I=s(He(i,w),Xe(i*2,x),He(e,v),Xe(e*2,T),a,r+i/De,c,o+e/De);else if(L){const C=It.getPrimitive();Ae(e,b,C),C.applyMatrix4(t);const D=Fe(i),P=Be(i,w);Ae(D,m,Kt),Ae(P,m,Xt);const F=C.intersectsBox(Kt),k=C.intersectsBox(Xt);I=F&&ht(e,D,n,t,s,o,r,c,a+1,C,!d)||k&&ht(e,P,n,t,s,o,r,c,a+1,C,!d),It.releasePrimitive(C)}else{const C=Fe(e),D=Be(e,v);Ae(C,b,Ns),Ae(D,b,ks);const P=u.intersectsBox(Ns),F=u.intersectsBox(ks);if(P&&F)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(P)if(A)I=ht(i,C,t,n,s,r,o,a,c+1,u,d);else{const k=It.getPrimitive();k.copy(Ns).applyMatrix4(t);const G=Fe(i),z=Be(i,w);Ae(G,m,Kt),Ae(z,m,Xt);const Y=k.intersectsBox(Kt),re=k.intersectsBox(Xt);I=Y&&ht(C,G,n,t,s,o,r,c,a+1,k,!d)||re&&ht(C,z,n,t,s,o,r,c,a+1,k,!d),It.releasePrimitive(k)}else if(F)if(A)I=ht(i,D,t,n,s,r,o,a,c+1,u,d);else{const k=It.getPrimitive();k.copy(ks).applyMatrix4(t);const G=Fe(i),z=Be(i,w);Ae(G,m,Kt),Ae(z,m,Xt);const Y=k.intersectsBox(Kt),re=k.intersectsBox(Xt);I=Y&&ht(D,G,n,t,s,o,r,c,a+1,k,!d)||re&&ht(D,z,n,t,s,o,r,c,a+1,k,!d),It.releasePrimitive(k)}}return I}const Xi=new p.Box3,Yt=new Float32Array(6);class ba{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,Yt,0);const[m,w,x,b,v,T]=Yt;m<r&&(r=m),b>c&&(c=b),w<o&&(o=w),v>u&&(u=v),x<a&&(a=x),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,Yt,0);const[a,c,u,d,h,f]=Yt,m=(a+d)/2,w=(c+h)/2,x=(u+f)/2,b=(d-a)/2,v=(h-c)/2,T=(f-u)/2,S=(r-s)*6;n[S+0]=m,n[S+1]=b+(Math.abs(m)+b)*fs,n[S+2]=w,n[S+3]=v+(Math.abs(w)+v)*fs,n[S+4]=x,n[S+5]=T+(Math.abs(x)+T)*fs}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/Ve;for(let u=0;u<c;u++){const d=De*u,h=2*d;Pe(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=Pe(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=Fe(a),f=Be(a,s),m=Ss(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/Ve;for(let u=c-1;u>=0;u--){const d=u*De,h=d*2;if(Pe(h,o)){const m=He(d,r),w=Xe(h,o);this.writePrimitiveRangeBounds(m,w,Yt,0),a.set(Yt,d)}else{const m=Fe(d),w=Be(d,r);for(let x=0;x<3;x++){const b=a[m+x],v=a[m+x+3],T=a[w+x],S=a[w+x+3];a[d+x]=b<T?b:T,a[d+x+3]=v>S?v:S}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{Ae(0,new Float32Array(n),Xi),e.union(Xi)}),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,x,b)=>h(f,m,w,x,b)?!0:a(f,m,this,r,w,x,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/Ve}return c}bvhcast(e,t,n){let{intersectsRanges:s}=n;return Sa(this,e,t,s)}}function _a(){return typeof SharedArrayBuffer<"u"}function bs(i){return i.index?i.index.count:i.attributes.position.count}function _s(i){return bs(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=bs(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 va(i,e){return i.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Yi(i,e,t){const n=Aa(i,e,t),s=va(i,t);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,c=bs(i)/t,u=[];for(const f of s){const{offset:m,count:w}=f,x=m,b=isFinite(w)?w:c-m,v=m+b;x<a&&v>o&&(u.push({pos:Math.max(o,x),isStart:!0}),u.push({pos:Math.min(a,v),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 Ma(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 Ra extends ba{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&&!_a())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[bi]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=Yi(t,e.range,n),r=Ma(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}]:Yi(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class xt{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}}xt.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),b=c.dot(c)*m-f*f;let v,T;b!==0?v=(h*f-w*m)/b:v=0,T=(h+v*f)/m,o.x=v,o.y=T}})(),xi=(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}}}})(),Pa=(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 x=o.getPlane(t);if(Math.abs(x.distanceToPoint(c))<=a){const v=x.projectPoint(c,e);if(o.containsPoint(v))return!0}return!1}})(),Ia=["x","y","z"],_t=1e-15,qi=_t*_t;function nt(i){return Math.abs(i)<_t}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 xt),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 Pa(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 x=u.length(),b=h.length(),v=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,x<_t?b<_t||v<_t?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):b<_t?v<_t?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):v<_t&&(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]),xi(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 xt,t=new xt,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(S,_,A,L){const I=n;!S.isDegenerateIntoPoint&&!S.isDegenerateIntoSegment?I.copy(S.plane.normal):I.copy(_.plane.normal);const C=S.satBounds,D=S.satAxes;for(let k=1;k<4;k++){const G=C[k],z=D[k];if(e.setFromPoints(z,_.points),G.isSeparated(e)||(o.copy(I).cross(z),e.setFromPoints(o,S.points),t.setFromPoints(o,_.points),e.isSeparated(t)))return!1}const P=_.satBounds,F=_.satAxes;for(let k=1;k<4;k++){const G=P[k],z=F[k];if(e.setFromPoints(z,S.points),G.isSeparated(e)||(o.crossVectors(I,z),e.setFromPoints(o,S.points),t.setFromPoints(o,_.points),e.isSeparated(t)))return!1}return A&&(L||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),A.start.set(0,0,0),A.end.set(0,0,0)),!0}function m(S,_,A,L,I,C,D,P,F,k,G){let z=D/(D-P);k.x=L+(I-L)*z,G.start.subVectors(_,S).multiplyScalar(z).add(S),z=D/(D-F),k.y=L+(C-L)*z,G.end.subVectors(A,S).multiplyScalar(z).add(S)}function w(S,_,A,L,I,C,D,P,F,k,G){if(I>0)m(S.c,S.a,S.b,L,_,A,F,D,P,k,G);else if(C>0)m(S.b,S.a,S.c,A,_,L,P,D,F,k,G);else if(P*F>0||D!=0)m(S.a,S.b,S.c,_,A,L,D,P,F,k,G);else if(P!=0)m(S.b,S.a,S.c,A,_,L,P,D,F,k,G);else if(F!=0)m(S.c,S.a,S.b,L,_,A,F,D,P,k,G);else return!0;return!1}function x(S,_,A,L){const I=_.degenerateSegment,C=S.plane.distanceToPoint(I.start),D=S.plane.distanceToPoint(I.end);return nt(C)?nt(D)?f(S,_,A,L):(A&&(A.start.copy(I.start),A.end.copy(I.start)),S.containsPoint(I.start)):nt(D)?(A&&(A.start.copy(I.end),A.end.copy(I.end)),S.containsPoint(I.end)):S.plane.intersectLine(I,n)!=null?(A&&(A.start.copy(n),A.end.copy(n)),S.containsPoint(n)):!1}function b(S,_,A){const L=_.a;return nt(S.plane.distanceToPoint(L))&&S.containsPoint(L)?(A&&(A.start.copy(L),A.end.copy(L)),!0):!1}function v(S,_,A){const L=S.degenerateSegment,I=_.a;return L.closestPointToPoint(I,!0,n),I.distanceToSquared(n)<qi?(A&&(A.start.copy(I),A.end.copy(I)),!0):!1}function T(S,_,A,L){if(S.isDegenerateIntoSegment)if(_.isDegenerateIntoSegment){const I=S.degenerateSegment,C=_.degenerateSegment,D=s,P=r;I.delta(D),C.delta(P);const F=n.subVectors(C.start,I.start),k=D.x*P.y-D.y*P.x;if(nt(k))return!1;const G=(F.x*P.y-F.y*P.x)/k,z=-(D.x*F.y-D.y*F.x)/k;if(G<0||G>1||z<0||z>1)return!1;const Y=I.start.z+D.z*G,re=C.start.z+P.z*z;return nt(Y-re)?(A&&(A.start.copy(I.start).addScaledVector(D,G),A.end.copy(I.start).addScaledVector(D,G)),!0):!1}else return _.isDegenerateIntoPoint?v(S,_,A):x(_,S,A,L);else{if(S.isDegenerateIntoPoint)return _.isDegenerateIntoPoint?_.a.distanceToSquared(S.a)<qi?(A&&(A.start.copy(S.a),A.end.copy(S.a)),!0):!1:_.isDegenerateIntoSegment?v(_,S,A):b(_,S,A);if(_.isDegenerateIntoPoint)return b(S,_,A);if(_.isDegenerateIntoSegment)return x(S,_,A,L)}}return function(_,A=null,L=!1){this.needsUpdate&&this.update(),_.isExtendedTriangle?_.needsUpdate&&_.update():(i.copy(_),i.update(),_=i);const I=T(this,_,A,L);if(I!==void 0)return I;const C=this.plane,D=_.plane;let P=D.distanceToPoint(this.a),F=D.distanceToPoint(this.b),k=D.distanceToPoint(this.c);nt(P)&&(P=0),nt(F)&&(F=0),nt(k)&&(k=0);const G=P*F,z=P*k;if(G>0&&z>0)return!1;let Y=C.distanceToPoint(_.a),re=C.distanceToPoint(_.b),Ne=C.distanceToPoint(_.c);nt(Y)&&(Y=0),nt(re)&&(re=0),nt(Ne)&&(Ne=0);const ot=Y*re,Re=Y*Ne;if(ot>0&&Re>0)return!1;s.copy(C.normal),r.copy(D.normal);const ze=s.cross(r);let Ge=0,ve=Math.abs(ze.x);const ye=Math.abs(ze.y);ye>ve&&(ve=ye,Ge=1),Math.abs(ze.z)>ve&&(Ge=2);const je=Ia[Ge],At=this.a[je],ge=this.b[je],at=this.c[je],ct=_.a[je],ln=_.b[je],Gt=_.c[je];if(w(this,At,ge,at,G,z,P,F,k,d,a))return f(this,_,A,L);if(w(_,ct,ln,Gt,ot,Re,Y,re,Ne,h,c))return f(this,_,A,L);if(d.y<d.x){const St=d.y;d.y=d.x,d.x=St,u.copy(a.start),a.start.copy(a.end),a.end.copy(u)}if(h.y<h.x){const St=h.y;h.y=h.x,h.x=St,u.copy(c.start),c.start.copy(c.end),c.end.copy(u)}return d.y<h.x||h.y<d.x?!1:(A&&(h.x>d.x?A.start.copy(c.start):A.start.copy(a.start),h.y<d.y?A.end.copy(c.end):A.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 x=this[m];o.closestPointToPoint(x,i),f=x.distanceToSquared(i),f<d&&(d=f,a&&a.copy(x),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 x=t[w],b=t[(w+1)%3];s.set(o[x],o[b]),xi(n,s,i,e);const v=i.distanceToSquared(e);v<d&&(d=v,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 xt),this.alignedSatBounds=new Array(3).fill().map(()=>new xt),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 xt;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 xt,n=new xt,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 x=d[w];if(s.crossVectors(m,x),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 b=0;b<8;b++){const v=m[b];s.copy(v).clamp(h,f);const T=v.distanceToSquared(s);if(T<w&&(w=T,c&&c.copy(v),u&&u.copy(s),T<d))return Math.sqrt(T)}let x=0;for(let b=0;b<3;b++)for(let v=0;v<=1;v++)for(let T=0;T<=1;T++){const S=(b+1)%3,_=(b+2)%3,A=v<<S|T<<_,L=1<<b|v<<S|T<<_,I=m[A],C=m[L];e[x].set(I,C);const P=i[b],F=i[S],k=i[_],G=t[x],z=G.start,Y=G.end;z[P]=h[P],z[F]=v?h[F]:f[F],z[k]=T?h[k]:f[F],Y[P]=f[P],Y[F]=v?h[F]:f[F],Y[k]=T?h[k]:f[F],x++}for(let b=0;b<=1;b++)for(let v=0;v<=1;v++)for(let T=0;T<=1;T++){s.x=b?f.x:h.x,s.y=v?f.y:h.y,s.z=T?f.z:h.z,this.closestPointToPoint(s,n);const S=s.distanceToSquared(n);if(S<w&&(w=S,c&&c.copy(n),u&&u.copy(s),S<d))return Math.sqrt(S)}for(let b=0;b<12;b++){const v=e[b];for(let T=0;T<12;T++){const S=t[T];xi(v,S,n,s);const _=n.distanceToSquared(s);if(_<w&&(w=_,c&&c.copy(n),u&&u.copy(s),_<d))return Math.sqrt(_)}}return Math.sqrt(w)}})();class La extends _i{constructor(){super(()=>new dt)}}const rt=new La,pn=new p.Vector3,Bs=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=>(pn.copy(e).clamp(d.min,d.max),pn.distanceToSquared(e)),intersectsBounds:(d,h,f)=>f<a&&f<o,intersectsTriangle:(d,h)=>{d.closestPointToPoint(e,pn);const f=e.distanceToSquared(pn);return f<a&&(Bs.copy(pn),a=f,c=h),f<r}}),a===1/0)return null;const u=Math.sqrt(a);return t.point?t.point.copy(Bs):t.point=Bs.clone(),t.distance=u,t.faceIndex=c,t}const Kn=parseInt(p.REVISION)>=169,Da=parseInt(p.REVISION)<=161,Ft=new p.Vector3,Bt=new p.Vector3,zt=new p.Vector3,Xn=new p.Vector2,Yn=new p.Vector2,qn=new p.Vector2,$i=new p.Vector3,Qi=new p.Vector3,Ji=new p.Vector3,mn=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 er(i,e,t,n,s,r,o,a,c,u,d){Ft.fromBufferAttribute(e,r),Bt.fromBufferAttribute(e,o),zt.fromBufferAttribute(e,a);const h=Na(i,Ft,Bt,zt,mn,c,u,d);if(h){if(n){Xn.fromBufferAttribute(n,r),Yn.fromBufferAttribute(n,o),qn.fromBufferAttribute(n,a),h.uv=new p.Vector2;const m=p.Triangle.getInterpolation(mn,Ft,Bt,zt,Xn,Yn,qn,h.uv);Kn||(h.uv=m)}if(s){Xn.fromBufferAttribute(s,r),Yn.fromBufferAttribute(s,o),qn.fromBufferAttribute(s,a),h.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(mn,Ft,Bt,zt,Xn,Yn,qn,h.uv1);Kn||(h.uv1=m),Da&&(h.uv2=h.uv1)}if(t){$i.fromBufferAttribute(t,r),Qi.fromBufferAttribute(t,o),Ji.fromBufferAttribute(t,a),h.normal=new p.Vector3;const m=p.Triangle.getInterpolation(mn,Ft,Bt,zt,$i,Qi,Ji,h.normal);h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1),Kn||(h.normal=m)}const f={a:r,b:o,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(Ft,Bt,zt,f.normal),h.face=f,h.faceIndex=r,Kn){const m=new p.Vector3;p.Triangle.getBarycoord(mn,Ft,Bt,zt,m),h.barycoord=m}}return h}function tr(i){return i&&i.isMaterial?i.side:i}function xs(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:x,uv1:b}=i.attributes;if(Array.isArray(e)){const v=n*3;for(let T=0,S=f.length;T<S;T++){const{start:_,count:A,materialIndex:L}=f[T];if(v>=_&&v<_+A){const I=tr(e[L]),C=er(t,m,w,x,b,c,u,d,I,r,o);if(C)if(C.faceIndex=n,C.face.materialIndex=L,s)s.push(C);else return C}}}else{const v=tr(e),T=er(t,m,w,x,b,c,u,d,v,r,o);if(T)if(T.faceIndex=n,T.face.materialIndex=0,s)s.push(T);else return T}return null}function Ie(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++)xs(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=xs(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,Ie(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 x=f*2;if(Pe(x,a)){const b=He(f,o),v=Xe(x,a);let T=1/0,S=1/0,_=1/0,A=-1/0,L=-1/0,I=-1/0;for(let C=3*b,D=3*(b+v);C<D;C++){let P=n[C];const F=s.getX(P),k=s.getY(P),G=s.getZ(P);F<T&&(T=F),F>A&&(A=F),k<S&&(S=k),k>L&&(L=k),G<_&&(_=G),G>I&&(I=G)}return c[f+0]!==T||c[f+1]!==S||c[f+2]!==_||c[f+3]!==A||c[f+4]!==L||c[f+5]!==I?(c[f+0]=T,c[f+1]=S,c[f+2]=_,c[f+3]=A,c[f+4]=L,c[f+5]=I,!0):!1}else{const b=Fe(f),v=Be(f,o);let T=w,S=!1,_=!1;if(e){if(!T){const P=b/De+m/Ve,F=v/De+m/Ve;S=e.has(P),_=e.has(F),T=!S&&!_}}else S=!0,_=!0;const A=T||S,L=T||_;let I=!1;A&&(I=h(b,m,T));let C=!1;L&&(C=h(v,m,T));const D=I||C;if(D)for(let P=0;P<3;P++){const F=b+P,k=v+P,G=c[F],z=c[F+3],Y=c[k],re=c[k+3];c[f+P]=G<Y?G:Y,c[f+P+3]=z>re?z:re}return D}}}function Nt(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,x=t.origin.y,b=t.origin.z;let v=e[i],T=e[i+3],S=e[i+1],_=e[i+3+1],A=e[i+2],L=e[i+3+2];return h>=0?(r=(v-w)*h,o=(T-w)*h):(r=(T-w)*h,o=(v-w)*h),f>=0?(a=(S-x)*f,c=(_-x)*f):(a=(_-x)*f,c=(S-x)*f),r>c||a>o||((a>r||isNaN(r))&&(r=a),(c<o||isNaN(o))&&(o=c),m>=0?(u=(A-b)*m,d=(L-b)*m):(u=(L-b)*m,d=(A-b)*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;xs(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=xs(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),Ie(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){_e.setBuffer(i._roots[e]),ri(0,i,t,n,s,r,o),_e.clearBuffer()}function ri(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=_e,d=i*2;if(Pe(d,c)){const f=He(i,u),m=Xe(d,c);ka(e,t,n,f,m,s,r,o)}else{const f=Fe(i);Nt(f,a,n,r,o)&&ri(f,e,t,n,s,r,o);const m=Be(i,u);Nt(m,a,n,r,o)&&ri(m,e,t,n,s,r,o)}}const ja=["x","y","z"];function Wa(i,e,t,n,s,r){_e.setBuffer(i._roots[e]);const o=oi(0,i,t,n,s,r);return _e.clearBuffer(),o}function oi(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=_e;let u=i*2;if(Pe(u,a)){const h=He(i,c),f=Xe(u,a);return Fa(e,t,n,h,f,s,r)}else{const h=Ss(i,c),f=ja[h],w=n.direction[f]>=0;let x,b;w?(x=Fe(i),b=Be(i,c)):(x=Be(i,c),b=Fe(i));const T=Nt(x,o,n,s,r)?oi(x,e,t,n,s,r):null;if(T){const A=T.point[f];if(w?A<=o[b+h]:A>=o[b+h+3])return T}const _=Nt(b,o,n,s,r)?oi(b,e,t,n,s,r):null;return T&&_?T.distance<=_.distance?T:_:T||_||null}}const $n=new p.Box3,qt=new dt,$t=new dt,gn=new p.Matrix4,nr=new Ye,Qn=new Ye;function Za(i,e,t,n){_e.setBuffer(i._roots[e]);const s=ai(0,i,t,n);return _e.clearBuffer(),s}function ai(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_e;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),nr.set(t.boundingBox.min,t.boundingBox.max,n),s=nr),Pe(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,x=He(i,a),b=Xe(c,o);if(gn.copy(n).invert(),t.boundsTree)return Ae(i,r,Qn),Qn.matrix.copy(gn),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 S=x*3,_=(b+x)*3;S<_;S+=3)if(Ie($t,S,h,f),$t.needsUpdate=!0,T.intersectsTriangle($t))return!0;return!1}});{const v=_s(t);for(let T=x*3,S=(b+x)*3;T<S;T+=3){Ie(qt,T,h,f),qt.a.applyMatrix4(gn),qt.b.applyMatrix4(gn),qt.c.applyMatrix4(gn),qt.needsUpdate=!0;for(let _=0,A=v*3;_<A;_+=3)if(Ie($t,_,m,w),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const d=Fe(i),h=Be(i,a);return Ae(d,r,$n),!!(s.intersectsBox($n)&&ai(d,e,t,n,s)||(Ae(h,r,$n),s.intersectsBox($n)&&ai(h,e,t,n,s)))}}const Jn=new p.Matrix4,zs=new Ye,yn=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(),zs.set(e.boundingBox.min,e.boundingBox.max,t),zs.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,x=Xa,b=null,v=null;s&&(b=Ya,v=qa);let T=1/0,S=null,_=null;return Jn.copy(t).invert(),yn.matrix.copy(Jn),i.shapecast({boundsTraverseOrder:A=>zs.distanceToBox(A),intersectsBounds:(A,L,I)=>I<T&&I<o?(L&&(yn.min.copy(A.min),yn.max.copy(A.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(A,L)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>yn.distanceToBox(C),intersectsBounds:(C,D,P)=>P<T&&P<o,intersectsRange:(C,D)=>{for(let P=C,F=C+D;P<F;P++){Ie(m,3*P,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let k=A,G=A+L;k<G;k++){Ie(f,3*k,u,c),f.needsUpdate=!0;const z=f.distanceToTriangle(m,w,b);if(z<T&&(x.copy(w),v&&v.copy(b),T=z,S=k,_=P),z<r)return!0}}}});{const I=_s(e);for(let C=0,D=I;C<D;C++){Ie(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let P=A,F=A+L;P<F;P++){Ie(f,3*P,u,c),f.needsUpdate=!0;const k=f.distanceToTriangle(m,w,b);if(k<T&&(x.copy(w),v&&v.copy(b),T=k,S=P,_=C),k<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(x):n.point=x.clone(),n.distance=T,n.faceIndex=S,s&&(s.point?s.point.copy(v):s.point=v.clone(),s.point.applyMatrix4(Jn),x.applyMatrix4(Jn),s.distance=x.sub(s.point).length(),s.faceIndex=_),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 x=f*2;if(Pe(x,a)){const b=He(f,o),v=Xe(x,a);let T=1/0,S=1/0,_=1/0,A=-1/0,L=-1/0,I=-1/0;for(let C=b,D=b+v;C<D;C++){const P=3*i.resolveTriangleIndex(C);for(let F=0;F<3;F++){let k=P+F;k=n?n[k]:k;const G=s.getX(k),z=s.getY(k),Y=s.getZ(k);G<T&&(T=G),G>A&&(A=G),z<S&&(S=z),z>L&&(L=z),Y<_&&(_=Y),Y>I&&(I=Y)}}return c[f+0]!==T||c[f+1]!==S||c[f+2]!==_||c[f+3]!==A||c[f+4]!==L||c[f+5]!==I?(c[f+0]=T,c[f+1]=S,c[f+2]=_,c[f+3]=A,c[f+4]=L,c[f+5]=I,!0):!1}else{const b=Fe(f),v=Be(f,o);let T=w,S=!1,_=!1;if(e){if(!T){const P=b/De+m/Ve,F=v/De+m/Ve;S=e.has(P),_=e.has(F),T=!S&&!_}}else S=!0,_=!0;const A=T||S,L=T||_;let I=!1;A&&(I=h(b,m,T));let C=!1;L&&(C=h(v,m,T));const D=I||C;if(D)for(let P=0;P<3;P++){const F=b+P,k=v+P,G=c[F],z=c[F+3],Y=c[k],re=c[k+3];c[f+P]=G<Y?G:Y,c[f+P+3]=z>re?z:re}return D}}}function Ja(i,e,t,n,s,r,o){_e.setBuffer(i._roots[e]),ci(0,i,t,n,s,r,o),_e.clearBuffer()}function ci(i,e,t,n,s,r,o){const{float32Array:a,uint16Array:c,uint32Array:u}=_e,d=i*2;if(Pe(d,c)){const f=He(i,u),m=Xe(d,c);Ua(e,t,n,f,m,s,r,o)}else{const f=Fe(i);Nt(f,a,n,r,o)&&ci(f,e,t,n,s,r,o);const m=Be(i,u);Nt(m,a,n,r,o)&&ci(m,e,t,n,s,r,o)}}const ec=["x","y","z"];function tc(i,e,t,n,s,r){_e.setBuffer(i._roots[e]);const o=li(0,i,t,n,s,r);return _e.clearBuffer(),o}function li(i,e,t,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:c}=_e;let u=i*2;if(Pe(u,a)){const h=He(i,c),f=Xe(u,a);return Va(e,t,n,h,f,s,r)}else{const h=Ss(i,c),f=ec[h],w=n.direction[f]>=0;let x,b;w?(x=Fe(i),b=Be(i,c)):(x=Be(i,c),b=Fe(i));const T=Nt(x,o,n,s,r)?li(x,e,t,n,s,r):null;if(T){const A=T.point[f];if(w?A<=o[b+h]:A>=o[b+h+3])return T}const _=Nt(b,o,n,s,r)?li(b,e,t,n,s,r):null;return T&&_?T.distance<=_.distance?T:_:T||_||null}}const es=new p.Box3,Qt=new dt,Jt=new dt,wn=new p.Matrix4,sr=new Ye,ts=new Ye;function nc(i,e,t,n){_e.setBuffer(i._roots[e]);const s=hi(0,i,t,n);return _e.clearBuffer(),s}function hi(i,e,t,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_e;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),sr.set(t.boundingBox.min,t.boundingBox.max,n),s=sr),Pe(c,o)){const d=e.geometry,h=d.index,f=d.attributes.position,m=t.index,w=t.attributes.position,x=He(i,a),b=Xe(c,o);if(wn.copy(n).invert(),t.boundsTree)return Ae(i,r,ts),ts.matrix.copy(wn),ts.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:T=>ts.intersectsBox(T),intersectsTriangle:T=>{T.a.applyMatrix4(n),T.b.applyMatrix4(n),T.c.applyMatrix4(n),T.needsUpdate=!0;for(let S=x,_=b+x;S<_;S++)if(Ie(Jt,3*e.resolveTriangleIndex(S),h,f),Jt.needsUpdate=!0,T.intersectsTriangle(Jt))return!0;return!1}});{const v=_s(t);for(let T=x,S=b+x;T<S;T++){const _=e.resolveTriangleIndex(T);Ie(Qt,3*_,h,f),Qt.a.applyMatrix4(wn),Qt.b.applyMatrix4(wn),Qt.c.applyMatrix4(wn),Qt.needsUpdate=!0;for(let A=0,L=v*3;A<L;A+=3)if(Ie(Jt,A,m,w),Jt.needsUpdate=!0,Qt.intersectsTriangle(Jt))return!0}}}else{const d=Fe(i),h=Be(i,a);return Ae(d,r,es),!!(s.intersectsBox(es)&&hi(d,e,t,n,s)||(Ae(h,r,es),s.intersectsBox(es)&&hi(h,e,t,n,s)))}}const ns=new p.Matrix4,Us=new Ye,En=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(),Us.set(e.boundingBox.min,e.boundingBox.max,t),Us.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,x=ic,b=null,v=null;s&&(b=rc,v=oc);let T=1/0,S=null,_=null;return ns.copy(t).invert(),En.matrix.copy(ns),i.shapecast({boundsTraverseOrder:A=>Us.distanceToBox(A),intersectsBounds:(A,L,I)=>I<T&&I<o?(L&&(En.min.copy(A.min),En.max.copy(A.max),En.needsUpdate=!0),!0):!1,intersectsRange:(A,L)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:C=>En.distanceToBox(C),intersectsBounds:(C,D,P)=>P<T&&P<o,intersectsRange:(C,D)=>{for(let P=C,F=C+D;P<F;P++){const k=I.resolveTriangleIndex(P);Ie(m,3*k,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let G=A,z=A+L;G<z;G++){const Y=i.resolveTriangleIndex(G);Ie(f,3*Y,u,c),f.needsUpdate=!0;const re=f.distanceToTriangle(m,w,b);if(re<T&&(x.copy(w),v&&v.copy(b),T=re,S=G,_=P),re<r)return!0}}}})}else{const I=_s(e);for(let C=0,D=I;C<D;C++){Ie(m,3*C,h,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let P=A,F=A+L;P<F;P++){const k=i.resolveTriangleIndex(P);Ie(f,3*k,u,c),f.needsUpdate=!0;const G=f.distanceToTriangle(m,w,b);if(G<T&&(x.copy(w),v&&v.copy(b),T=G,S=P,_=C),G<r)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),T===1/0?null:(n.point?n.point.copy(x):n.point=x.clone(),n.distance=T,n.faceIndex=S,s&&(s.point?s.point.copy(v):s.point=v.clone(),s.point.applyMatrix4(ns),x.applyMatrix4(ns),s.distance=x.sub(s.point).length(),s.faceIndex=_),n)}function ir(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 ss=new Ye,is=new p.Ray,rr=new p.Vector3,or=new p.Matrix4,ar=new p.Vector3,Vs=["getX","getY","getZ"];class Mn extends Ra{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 Mn(t,{...n,[bi]:!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,x=h.byteLength/Ve;w<x;w++){const b=De*w,v=2*b;Pe(v,m)||(f[b+6]=f[b+6]/De-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[Vs[m]](d),x=o[Vs[m]](h),b=o[Vs[m]](f);let v=w;x<v&&(v=x),b<v&&(v=b);let T=w;x>T&&(T=x),b>T&&(T=b),t[n+m]=v,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,x=e+t;w<x;w++){const v=(r?r[w]:w)*3,T=(w-m)*6;let S=v+0,_=v+1,A=v+2;a&&(S=a[S],_=a[_],A=a[A]),c||(S=S*h+d,_=_*h+d,A=A*h+d);for(let L=0;L<3;L++){let I,C,D;c?(I=o[f[L]](S),C=o[f[L]](_),D=o[f[L]](A)):(I=u[S+L],C=u[_+L],D=u[A+L]);let P=I;C<P&&(P=C),D<P&&(P=D);let F=I;C>F&&(F=C),D>F&&(F=D);const k=(F-P)/2,G=L*2;n[T+G+0]=P+k,n[T+G+1]=k+(Math.abs(P)+k)*fs}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;or.copy(e.matrixWorld).invert(),is.copy(t.ray).applyMatrix4(or),ar.setFromMatrixScale(e.matrixWorld),rr.copy(is.direction).multiply(ar);const r=rr.length(),o=t.near/r,a=t.far/r;if(t.firstHitOnly===!0){let c=this.raycastFirst(is,s,o,a);c=ir(c,e,t),c&&n.push(c)}else{const c=this.raycast(is,s,o,a);for(let u=0,d=c.length;u<d;u++){const h=ir(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 x=this.resolveTriangleIndex(w);Ie(o,x*3,a,c)}:w=>{Ie(o,w*3,a,c)},d=rt.getPrimitive(),h=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?w=>{const x=e.resolveTriangleIndex(w);Ie(d,x*3,h,f)}:w=>{Ie(d,w*3,h,f)};if(r){if(!(e instanceof Mn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const w=(x,b,v,T,S,_,A,L)=>{for(let I=v,C=v+T;I<C;I++){m(I),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let D=x,P=x+b;D<P;D++)if(u(D),o.needsUpdate=!0,r(o,d,D,I,S,_,A,L))return!0}return!1};if(s){const x=s;s=function(b,v,T,S,_,A,L,I){return x(b,v,T,S,_,A,L,I)?!0:w(b,v,T,S,_,A,L,I)}}else s=w}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return ss.set(e.min,e.max,t),ss.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ss.intersectsBox(n),intersectsTriangle:n=>ss.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 nn={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},Ue=new p.Mesh,rs=[];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=nn.Mesh;else if(this instanceof p.LineSegments)n=nn.LineSegments;else if(this instanceof p.LineLoop)n=nn.LineLoop;else if(this instanceof p.Line)n=nn.Line;else if(this instanceof p.Points)n=nn.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;Ue.material=this.material,Ue.geometry=this.geometry;const o=Ue.geometry.boundsTree,a=Ue.geometry.drawRange;Ue.geometry.boundingSphere===null&&(Ue.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(Ue.geometry.boundsTree=t[d],this.getMatrixAt(c,Ue.matrixWorld).premultiply(r),!Ue.geometry.boundsTree){this.getBoundingBoxAt(d,Ue.geometry.boundingBox),this.getBoundingSphereAt(d,Ue.geometry.boundingSphere);const h=s[d];Ue.geometry.setDrawRange(h.start,h.count)}Ue.raycast(i,rs);for(let h=0,f=rs.length;h<f;h++){const m=rs[h];m.object=this,m.batchId=c,e.push(m)}rs.length=0}Ue.geometry.boundsTree=o,Ue.geometry.drawRange=a,Ue.material=null,Ue.geometry=null}else nn.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 Mn(n)),t.raycast=cc)})}function hc(i){i.boundsTree&&(i.boundsTree=void 0)}function cr(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof y.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 y.Texture&&n.value.dispose();i.dispose()}function As(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(cr):n&&cr(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 y.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof y.Texture&&(i.environment.dispose(),i.environment=null);const t=i;t.__originalEnvironmentTexture&&(t.__originalEnvironmentTexture=void 0)}for(const t of[...i.children])As(t),i.remove(t)}class Ke{constructor(e){this.object=e,this.positionAdapter=Dt.fromThreeVector(e.position),this.rotationAdapter=Dt.fromThreeVector(e.rotation),this.scaleAdapter=Dt.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 Ke?(this.object.add(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Child must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to add child object",K.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ke?(this.object.remove(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Child must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to remove child object",K.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Ke(t))})}clone(){return new Ke(this.object.clone())}dispose(){As(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new Ke(e)}static create(){return new Ke(new y.Object3D)}}class ui{constructor(e){this.scene=e||new y.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 Ke?(this.scene.add(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Object must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to add object to scene",K.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ke?(this.scene.remove(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Object must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to remove object from scene",K.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 Ke(t))})}get background(){return this.scene.background instanceof y.Color?new di(this.scene.background):this.scene.background instanceof y.Texture?new os(this.scene.background):null}set background(e){e instanceof di?this.scene.background=e.getThreeColor():e instanceof os?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new lr(this.scene.fog):null}set fog(e){e instanceof lr?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new os(this.scene.environment):null}set environment(e){e instanceof os?this.scene.environment=e.getThreeTexture():this.scene.environment=null}setEnvironmentIntensity(e){this.scene.environmentIntensity=e}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class di{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 os=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 lr{constructor(e){this.fog=e}get color(){return new di(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class fi extends Ke{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Dt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new y.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class Ai extends fi{constructor(e){const t=e||new y.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=30,t=1,n=.1,s=1e3){return new Ai(new y.PerspectiveCamera(e,t,n,s))}}function dc(i){return i.bloom||i.vignette||i.filmGrain}const fc={uniforms:{tDiffuse:{value:null},intensity:{value:.05}},vertexShader:`
2
- varying vec2 vUv;
3
- void main() {
4
- vUv = uv;
5
- gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
6
- }
7
- `,fragmentShader:`
8
- uniform sampler2D tDiffuse;
9
- uniform float intensity;
10
- varying vec2 vUv;
11
- float hash( vec2 p ) {
12
- return fract( sin( dot( p, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );
13
- }
14
- void main() {
15
- vec4 color = texture2D( tDiffuse, vUv );
16
- float grain = hash( floor( gl_FragCoord.xy ) ) - 0.5;
17
- gl_FragColor = vec4( color.rgb + grain * intensity, color.a );
18
- }
19
- `};class pc{constructor(e,t){this.modules=null,this.composer=null,this.renderPass=null,this.disposed=!1,this.loadFailed=!1,this.renderer=e,this.config=t,this.load()}async load(){try{const e=this.config.vignette||this.config.filmGrain,[t,n,s,r,o,a]=await Promise.all([Promise.resolve().then(()=>require("./EffectComposer-D2IQ0sek.cjs")),Promise.resolve().then(()=>require("./RenderPass-BVzyKWsC.cjs")),Promise.resolve().then(()=>require("./OutputPass-Dy4KNHYF.cjs")),this.config.bloom?Promise.resolve().then(()=>require("./UnrealBloomPass-Kx7djcld.cjs")):Promise.resolve(null),e?Promise.resolve().then(()=>require("./ShaderPass-BQRqK8zp.cjs")):Promise.resolve(null),this.config.vignette?Promise.resolve().then(()=>require("./VignetteShader-Drpo9YxI.cjs")):Promise.resolve(null)]);if(this.disposed)return;this.modules={EffectComposer:t.EffectComposer,RenderPass:n.RenderPass,OutputPass:s.OutputPass,UnrealBloomPass:r==null?void 0:r.UnrealBloomPass,ShaderPass:o==null?void 0:o.ShaderPass,VignetteShader:a==null?void 0:a.VignetteShader}}catch(e){this.loadFailed=!0,console.warn("Failed to load post-processing effects; falling back to the plain renderer:",e)}}isReady(){return this.modules!==null&&!this.disposed&&!this.loadFailed}render(e,t){const n=this.modules;if(n===null||this.disposed||this.loadFailed)return!1;const s=this.composer??this.build(n,e,t);return this.renderPass&&(this.renderPass.scene=e,this.renderPass.camera=t),s.render(),!0}build(e,t,n){const s=this.renderer.getDrawingBufferSize(new y.Vector2),r=new e.EffectComposer(this.renderer),o=Math.min(4,this.renderer.capabilities.maxSamples||0);o>0&&(r.renderTarget1.samples=o,r.renderTarget2.samples=o);const a=new e.RenderPass(t,n);if(this.renderPass=a,r.addPass(a),this.config.bloom&&e.UnrealBloomPass&&r.addPass(new e.UnrealBloomPass(new y.Vector2(s.x,s.y),.18,.25,1)),r.addPass(new e.OutputPass),this.config.vignette&&e.ShaderPass&&e.VignetteShader){const c=new e.ShaderPass(e.VignetteShader);c.uniforms.offset.value=1.15,c.uniforms.darkness.value=1.05,r.addPass(c)}return this.config.filmGrain&&e.ShaderPass&&r.addPass(new e.ShaderPass(fc)),this.composer=r,r}setSize(e,t){var n;(n=this.composer)==null||n.setSize(e,t)}setPixelRatio(e){var t,n;(n=(t=this.composer)==null?void 0:t.setPixelRatio)==null||n.call(t,e)}dispose(){var e,t;this.disposed=!0,(t=(e=this.composer)==null?void 0:e.dispose)==null||t.call(e),this.composer=null,this.renderPass=null,this.modules=null}}class mc{constructor(e){this.renderer=null,this._id=Pr(),this.postPipeline=null,this.canvas=e}get id(){return this._id}initialize(e){var t,n,s,r,o,a;try{if(this.renderer=new y.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 d={basic:y.BasicShadowMap,pcf:y.PCFShadowMap,pcfsoft:y.PCFSoftShadowMap,vsm:y.VSMShadowMap};this.renderer.shadowMap.type=d[e.shadowMap.type]}if(e.toneMapping){const d={none:y.NoToneMapping,linear:y.LinearToneMapping,reinhard:y.ReinhardToneMapping,cineon:y.CineonToneMapping,aces:y.ACESFilmicToneMapping,agx:y.AgXToneMapping,neutral:y.NeutralToneMapping};this.renderer.toneMapping=d[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}const c=dc({bloom:((t=e.postProcessing)==null?void 0:t.bloom)??!1,vignette:((n=e.postProcessing)==null?void 0:n.vignette)??!1,filmGrain:((s=e.postProcessing)==null?void 0:s.filmGrain)??!1}),u=e.pixelRatio??window.devicePixelRatio;if(this.renderer.setPixelRatio(c?Math.min(u,2):u),this.canvas){const{clientWidth:d,clientHeight:h}=this.canvas.parentElement||this.canvas;d&&h&&this.renderer.setSize(d,h)}return this.renderer.outputColorSpace=y.SRGBColorSpace,c&&(this.postPipeline=new pc(this.renderer,{bloom:((r=e.postProcessing)==null?void 0:r.bloom)??!1,vignette:((o=e.postProcessing)==null?void 0:o.vignette)??!1,filmGrain:((a=e.postProcessing)==null?void 0:a.filmGrain)??!1})),N.ok(void 0)}catch(c){return N.err(new Z("Failed to initialize renderer",K.RENDERER_INIT_FAILED,{originalError:c,options:e}))}}render(e,t){if(!this.renderer)return N.err(new Z("Renderer not initialized",K.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof ui))return N.err(new Z("Scene must be a ThreeSceneAdapter",K.INVALID_PARAMETER));if(!(t instanceof fi))return N.err(new Z("Camera must be a ThreeCameraAdapter",K.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),N.ok(void 0)}catch(n){return N.err(new Z("Failed to render frame",K.RENDER_FAILED,{originalError:n}))}}renderPostProcessed(e,t){if(!this.postPipeline||!this.renderer||!(e instanceof ui)||!(t instanceof fi))return this.render(e,t);try{return this.postPipeline.render(e.getThreeScene(),t.getThreeCamera())?N.ok(void 0):this.render(e,t)}catch(n){return N.err(new Z("Failed to render frame with post-processing",K.RENDER_FAILED,{originalError:n}))}}setSize(e,t){var n;if(this.renderer){this.renderer.setSize(e,t,!1),(n=this.postPipeline)==null||n.setSize(e,t);const s=this.renderer.domElement;s.style.width="100%",s.style.height="100%"}}setPixelRatio(e){var t;this.renderer&&(this.renderer.setPixelRatio(e),(t=this.postPipeline)==null||t.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(){var e;(e=this.postPipeline)==null||e.dispose(),this.postPipeline=null,this.renderer&&(this.renderer.dispose(),this.renderer=null)}isDisposed(){return this.renderer===null}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function hr(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 gc(i){const e=new Map,t=new Map,n=i.clone();return Br(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 Br(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)Br(i.children[n],e.children[n],t)}class yc extends p.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new bc(t)}),this.register(function(t){return new _c(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new Oc(t)}),this.register(function(t){return new Dc(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new vc(t)}),this.register(function(t){return new Mc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new Sc(t)}),this.register(function(t){return new Cc(t)}),this.register(function(t){return new xc(t)}),this.register(function(t){return new Ic(t)}),this.register(function(t){return new Pc(t)}),this.register(function(t){return new Ec(t)}),this.register(function(t){return new ur(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new ur(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Nc(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))===zr){try{o[le.KHR_BINARY_GLTF]=new kc(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 Yc(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 Tc;break;case le.KHR_DRACO_MESH_COMPRESSION:o[h]=new Fc(r,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:o[h]=new Bc;break;case le.KHR_MESH_QUANTIZATION:o[h]=new zc;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 wc(){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 Me(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 Ec{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),wt(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 Tc{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 Sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class bc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 _c{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class xc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Ac{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 vc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Mc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Rc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Cc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Pc{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Ic{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Me(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Me(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 Lc{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 Oc{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 Dc{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 ur{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 Nc{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 x=new p.Matrix4,b=new p.Vector3,v=new p.Quaternion,T=new p.Vector3(1,1,1),S=new p.InstancedMesh(w.geometry,w.material,f);for(let _=0;_<f;_++)c.TRANSLATION&&b.fromBufferAttribute(c.TRANSLATION,_),c.ROTATION&&v.fromBufferAttribute(c.ROTATION,_),c.SCALE&&T.fromBufferAttribute(c.SCALE,_),S.setMatrixAt(_,x.compose(b,v,T));for(const _ in c)if(_==="_COLOR_0"){const A=c[_];S.instanceColor=new p.InstancedBufferAttribute(A.array,A.itemSize,A.normalized)}else _!=="TRANSLATION"&&_!=="ROTATION"&&_!=="SCALE"&&w.geometry.setAttribute(_,c[_]);p.Object3D.prototype.copy.call(S,w),this.parser.assignFinalMaterial(S),m.push(S)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const zr="glTF",Tn=12,dr={JSON:1313821514,BIN:5130562};class kc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Tn),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!==zr)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-Tn,r=new DataView(e,Tn);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const c=r.getUint32(o,!0);if(o+=4,c===dr.JSON){const u=new Uint8Array(e,Tn+o,a);this.content=n.decode(u)}else if(c===dr.BIN){const u=Tn+o;this.body=e.slice(u,u+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Fc{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=pi[d]||d.toLowerCase();a[h]=o[d]}for(const d in e.attributes){const h=pi[d]||d.toLowerCase();if(o[d]!==void 0){const f=n.accessors[e.attributes[d]],m=an[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 x=m.attributes[w],b=c[w];b!==void 0&&(x.normalized=b)}h(m)},a,u,p.LinearSRGBColorSpace,f)})})}}class Bc{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 zc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Ur 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,x=w-u,b=-2*m+3*f,v=m-f,T=1-b,S=v-f+h;for(let _=0;_!==a;_++){const A=o[x+_+a],L=o[x+_+c]*d,I=o[w+_+a],C=o[w+_]*d;r[_]=T*A+S*L+b*I+v*C}return r}}const Uc=new p.Quaternion;class Vc extends Ur{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return Uc.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},an={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},fr={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},pr={33071:p.ClampToEdgeWrapping,33648:p.MirroredRepeatWrapping,10497:p.RepeatWrapping},Hs={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},pi={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"},Hc={CUBICSPLINE:void 0,LINEAR:p.InterpolateLinear,STEP:p.InterpolateDiscrete},Gs={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Gc(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 Ut(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 wt(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 jc(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 Wc(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 Zc(i){let e;const t=i.extensions&&i.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+js(t.attributes):e=i.indices+":"+js(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+js(i.targets[n]);return e}function js(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 mi(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 Kc(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 Xc=new p.Matrix4;class Yc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new wc,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 Ut(r,a,s),wt(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=Hs[s.type],a=an[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=Hs[s.type],u=an[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 x,b;if(m&&m!==h){const v=Math.floor(f/m),T="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+v+":"+s.count;let S=t.cache.get(T);S||(x=new u(a,v*m,s.count*m/d),S=new p.InterleavedBuffer(x,m/d),t.cache.add(T,S)),b=new p.InterleavedBufferAttribute(S,c,f%m/d,w)}else a===null?x=new u(s.count*c):x=new u(a,f,s.count*c),b=new p.BufferAttribute(x,c,w);if(s.sparse!==void 0){const v=Hs.SCALAR,T=an[s.sparse.indices.componentType],S=s.sparse.indices.byteOffset||0,_=s.sparse.values.byteOffset||0,A=new T(o[1],S,s.sparse.count*v),L=new u(o[2],_,s.sparse.count*c);a!==null&&(b=new p.BufferAttribute(b.array.slice(),b.itemSize,b.normalized)),b.normalized=!1;for(let I=0,C=A.length;I<C;I++){const D=A[I];if(b.setX(D,L[I*c]),c>=2&&b.setY(D,L[I*c+1]),c>=3&&b.setZ(D,L[I*c+2]),c>=4&&b.setW(D,L[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}b.normalized=w}return b})}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=fr[f.magFilter]||p.LinearFilter,d.minFilter=fr[f.minFilter]||p.LinearMipmapLinearFilter,d.wrapS=pr[f.wrapS]||p.RepeatWrapping,d.wrapT=pr[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(x){const b=new p.Texture(x);b.needsUpdate=!0,f(b)}),t.load(p.LoaderUtils.resolveURL(h,r.path),w,void 0,m)})}).then(function(h){return u===!0&&a.revokeObjectURL(c),wt(h,o),h.userData.mimeType=o.mimeType||Kc(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||Gs.OPAQUE;if(d===Gs.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Gs.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),wt(h,r),t.associations.set(h,{materials:e}),r.extensions&&Ut(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 mr(c,a,t)})}const o=[];for(let a=0,c=e.length;a<c;a++){const u=e[a],d=Zc(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=mr(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?Gc(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 x=d[m],b=o[m];let v;const T=u[m];if(b.mode===st.TRIANGLES||b.mode===st.TRIANGLE_STRIP||b.mode===st.TRIANGLE_FAN||b.mode===void 0)v=r.isSkinnedMesh===!0?new p.SkinnedMesh(x,T):new p.Mesh(x,T),v.isSkinnedMesh===!0&&v.normalizeSkinWeights(),b.mode===st.TRIANGLE_STRIP?v.geometry=hr(v.geometry,p.TriangleStripDrawMode):b.mode===st.TRIANGLE_FAN&&(v.geometry=hr(v.geometry,p.TriangleFanDrawMode));else if(b.mode===st.LINES)v=new p.LineSegments(x,T);else if(b.mode===st.LINE_STRIP)v=new p.Line(x,T);else if(b.mode===st.LINE_LOOP)v=new p.LineLoop(x,T);else if(b.mode===st.POINTS)v=new p.Points(x,T);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+b.mode);Object.keys(v.geometry.morphAttributes).length>0&&Wc(v,r),v.name=t.createUniqueName(r.name||"mesh_"+e),wt(v,r),b.extensions&&Ut(s,v,b),t.assignFinalMaterial(v),h.push(v)}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&&Ut(s,h[0],r),h[0];const f=new p.Group;r.extensions&&Ut(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)),wt(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],x=m.target,b=x.node,v=s.parameters!==void 0?s.parameters[w.input]:w.input,T=s.parameters!==void 0?s.parameters[w.output]:w.output;x.node!==void 0&&(o.push(this.getDependency("node",b)),a.push(this.getDependency("accessor",v)),c.push(this.getDependency("accessor",T)),u.push(w),d.push(x))}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],x=h[3],b=h[4],v=[];for(let S=0,_=f.length;S<_;S++){const A=f[S],L=m[S],I=w[S],C=x[S],D=b[S];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const P=n._createAnimationTracks(A,L,I,C,D);if(P)for(let F=0;F<P.length;F++)v.push(P[F])}const T=new p.AnimationClip(r,void 0,v);return wt(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,Xc)});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),wt(d,r),r.extensions&&Ut(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)),wt(r,n),n.extensions&&Ut(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(gc(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?Hc[s.interpolation]:p.InterpolateLinear,f=this._getArrayFromAccessor(n);for(let m=0,w=c.length;m<w;m++){const x=new d(c[m]+"."+Rt[r.path],t.array,f,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(x),o.push(x)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=mi(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?Vc:Ur;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function qc(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=mi(an[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 x=mi(an[f.componentType]);c.multiplyScalar(x)}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 mr(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=pi[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.`),wt(i,e),qc(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?jc(i,e.targets,t):i})}const $c=y.REVISION.replace(/\D/g,""),Vr=`https://cdn.jsdelivr.net/npm/three@0.${$c}/examples/jsm/libs`,Qc=`${Vr}/draco/`,Jc=`${Vr}/basis/`;class el{constructor(e={}){this.loadingManager=new y.LoadingManager,this.loader=new yc(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??Qc),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??Jc),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 Ke(s.scene),animations:this.convertAnimations(s.animations),cameras:(o=s.cameras)==null?void 0:o.map(a=>{const c=a instanceof y.PerspectiveCamera,u=a instanceof y.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(N.ok(r))},s=>{s.total>0&&(t==null||t(s.loaded,s.total))},s=>{n(N.err(new Z("Failed to load GLTF model",K.MODEL_LOAD_FAILED,{url:e,originalError:s})))})})}catch(n){return N.err(new Z("Failed to initiate model loading",K.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 y.VectorKeyframeTrack?"vector":e instanceof y.QuaternionKeyframeTrack?"quaternion":e instanceof y.NumberKeyframeTrack?"number":e instanceof y.BooleanKeyframeTrack?"boolean":"number"}}class gr{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 el(t);default:throw new Z(`Unsupported file format: ${n}`,K.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const yr={type:"change"},vi={type:"start"},Hr={type:"end"},as=new p.Ray,wr=new p.Plane,tl=Math.cos(70*p.MathUtils.DEG2RAD),Le=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},Ws=1e-6;class Gr 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=sl.bind(this),this._onPointerDown=nl.bind(this),this._onPointerUp=il.bind(this),this._onContextMenu=ul.bind(this),this._onMouseWheel=al.bind(this),this._onKeyDown=cl.bind(this),this._onTouchStart=ll.bind(this),this._onTouchMove=hl.bind(this),this._onMouseDown=rl.bind(this),this._onMouseMove=ol.bind(this),this._interceptControlDown=dl.bind(this),this._interceptControlUp=fl.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(yr),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;Le.copy(t).sub(this.target),Le.applyQuaternion(this._quat),this._spherical.setFromVector3(Le),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(Le.setFromSpherical(this._spherical),Le.applyQuaternion(this._quatInverse),t.copy(this.target).add(Le),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=Le.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=Le.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):(as.origin.copy(this.object.position),as.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(as.direction))<tl?this.object.lookAt(this.target):(wr.setFromNormalAndCoplanarPoint(this.object.up,this.target),as.intersectPlane(wr,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)>Ws||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Ws||this._lastTargetPosition.distanceToSquared(this.target)>Ws?(this.dispatchEvent(yr),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){Le.setFromMatrixColumn(t,0),Le.multiplyScalar(-e),this._panOffset.add(Le)}_panUp(e,t){this.screenSpacePanning===!0?Le.setFromMatrixColumn(t,1):(Le.setFromMatrixColumn(t,0),Le.crossVectors(this.object.up,Le)),Le.multiplyScalar(e),this._panOffset.add(Le)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Le.copy(s).sub(this.target);let r=Le.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 nl(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 sl(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function il(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(Hr),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 rl(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(vi)}function ol(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 al(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ee.NONE||(i.preventDefault(),this.dispatchEvent(vi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Hr))}function cl(i){this.enabled!==!1&&this._handleKeyDown(i)}function ll(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(vi)}function hl(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 ul(i){this.enabled!==!1&&i.preventDefault()}function dl(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function fl(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Zs=new p.Plane,cs=new p.Raycaster,en=new p.Vector2,Ks=new p.Vector3;class pl extends Gr{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;Zs.setFromNormalAndCoplanarPoint(this.object.up,this.target);const n=this.domElement.getBoundingClientRect();en.x=(e.clientX-n.left)/n.width*2-1,en.y=-((e.clientY-n.top)/n.height)*2+1,cs.setFromCamera(en,this.object),cs.ray.intersectPlane(Zs,this._panWorldStart)}_handleMouseMovePan(e){if(this.screenSpacePanning===!0){super._handleMouseMovePan(e);return}const n=this.domElement.getBoundingClientRect();en.x=(e.clientX-n.left)/n.width*2-1,en.y=-((e.clientY-n.top)/n.height)*2+1,cs.setFromCamera(en,this.object),cs.ray.intersectPlane(Zs,Ks)&&(Ks.sub(this._panWorldStart),this._panOffset.copy(Ks).negate(),this.update())}}class jr{constructor(e){this.controls=e,this.targetAdapter=Dt.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()}onChange(e){return this.controls.addEventListener("change",e),()=>this.controls.removeEventListener("change",e)}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 ml extends jr{constructor(e,t){super(new Gr(e,t))}get type(){return"orbit"}}class gl extends jr{constructor(e,t){const n=new pl(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const gi="contact-shadow-baked",Vt="contact-shadow-live",vs="softboxContactShadowHelper",Ms="softboxPathTracingFloor",Er=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(Vt);(a==null?void 0:a.geometry)instanceof y.CircleGeometry&&(o.halfExtent=Math.min(o.halfExtent,a.geometry.parameters.radius));const c=new y.WebGLRenderTarget(xe.ACCUMULATION_TEXTURE_SIZE,xe.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?y.HalfFloatType:y.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),u=new y.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(Vt);t&&(t.visible=!0)}evictBakedMesh(e){const t=e.getObjectByName(gi);t&&(e.remove(t),As(t))}measureBakeRegion(e){const t=new y.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new y.Vector3),s=t.getCenter(new y.Vector3),o=Math.max(Math.max(n.x,n.z)*1.4+n.y*.65,.05);return{center:s,halfExtent:o,objectHeight:n.y}}accumulateShadowPasses(e,t,n,s,r,o){const a=new y.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 y.Vector3):n.target.position);const h=new y.ShadowMaterial({transparent:!0,opacity:0,depthWrite:!1});h.blending=y.CustomBlending,h.blendEquation=y.AddEquation,h.blendSrc=y.OneFactor,h.blendDst=y.OneFactor;const f=new y.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(),x=e.autoClear,b=e.getClearColor(new y.Color),v=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 S=this.explicitPasses??this.measureAffordablePasses(e,a,m,n,d,r);h.opacity=1/S;for(const _ of this.sampleLightPositions(n,S))d.position.copy(_),e.render(a,m)}finally{e.autoClear=x,e.setClearColor(b,v),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 y.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===y.HalfFloatType?new Uint16Array(4):new Uint8Array(4);e.readRenderTargetPixels(t,0,0,1,1,n)}createBakeLight(e){const t=new y.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=6;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 y.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 y.Vector3):e.target.position.clone(),r=s.clone().sub(n),o=r.length(),a=r.normalize(),c=new y.Vector3().crossVectors(a,new y.Vector3(0,1,0));c.lengthSq()<1e-6&&c.set(1,0,0),c.normalize();const u=new y.Vector3().crossVectors(a,c),d=Math.round(t*xe.AMBIENT_RATIO),h=t-d,f=y.MathUtils.degToRad(xe.LIGHT_APERTURE_DEGREES),m=Math.tan(f/2)*o,w=[];for(let v=0;v<h;v++){const T=m*Math.sqrt((v+.5)/h),S=v*Er;w.push(n.clone().addScaledVector(c,T*Math.cos(S)).addScaledVector(u,T*Math.sin(S)))}const x=Math.sin(y.MathUtils.degToRad(xe.AMBIENT_MIN_ELEVATION_DEGREES)),b=.98;for(let v=0;v<d;v++){const T=Math.sqrt((v+.5)/d),S=x+(b-x)*T,_=Math.sqrt(1-S*S),A=v*Er;w.push(new y.Vector3(_*Math.cos(A),S,_*Math.sin(A)).multiplyScalar(o).add(s))}return w}installBakedMesh(e,t,n,s){this.evictBakedMesh(e);const r=new y.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>
20
- diffuseColor.a = pow(diffuseColor.a, 0.75);`)},r.customProgramCacheKey=()=>"contact-shadow-alpha-gamma",r.addEventListener("dispose",()=>n.dispose());const o=new y.Mesh(s,r);o.name=gi,o.userData[vs]=!0,o.rotation.x=-Math.PI/2;const a=y.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(Vt);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=13,xe.AMBIENT_MIN_ELEVATION_DEGREES=55,xe.ACCUMULATION_TEXTURE_SIZE=1024,xe.BAKE_SHADOW_MAP_SIZE=1024,xe.SHADOW_STRENGTH=.55,xe.BAKE_BUDGET_MS=100,xe.MIN_PASSES=24,xe.MAX_PASSES=96;let yi=xe;const cn=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function Tt(i){return cn(i,"getThreeObject")??(i instanceof y.Object3D?i:null)}function Pn(i){return cn(i,"getThreeCamera")??(i instanceof y.Camera?i:null)}function ft(i){return cn(i,"getThreeScene")??(i instanceof y.Scene?i:null)}function yl(i){return cn(i,"getThreeTexture")??(i instanceof y.Texture?i:null)}function Wr(i){return cn(i,"getThreeRenderer")??(i instanceof y.WebGLRenderer?i:null)}function Mi(i){return cn(i,"getThreeControls")}var Et=(i=>(i.SHADOW_FLOOR="shadow_floor",i.SQUARE_WIRE="square_wire",i.HEXAGONAL_WIRE="hexagonal_wire",i.HEXAGONAL_GLASS="hexagonal_glass",i.STONE_TILES="stone_tiles",i.CUSTOM="custom",i))(Et||{});class wl{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new y.Color(e.color||8947848),r=new y.Color(e.centerLineColor||e.color||4473924),o=new y.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 El{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new y.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 y.Color(e.color||8947848),o=e.opacity||.4,a=new y.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 x=c*(h+w/2),b=u*.75*w,v=[],T=Math.PI*2/6;for(let A=0;A<=6;A++){const L=A*T+Math.PI/6,I=x+s*Math.cos(L),C=b+s*Math.sin(L);v.push(new y.Vector3(I,0,C))}const S=new y.BufferGeometry().setFromPoints(v),_=new y.Line(S,a);t.add(_)}}return t}dispose(){}}const vn=class vn{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)}};vn.HEIGHT_RATIO=.075,vn.BEVEL_RATIO=.04,vn.GAP_FACTOR=1.05;let Ht=vn;class Tl{constructor(e,t,n,s={}){this.position=e,this.size=t,this.color=n,this.materialOptions=s,this.height=Ht.getHeight(this.size),this.bevel=Ht.getBevelSize(this.size)}createGeometry(){const e=new y.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 y.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 y.MeshPhysicalMaterial({color:new y.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 y.Color(16777215),envMapIntensity:1})}}function Sl(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 y.BufferGeometry;return u.setAttribute("position",new y.BufferAttribute(o,3)),u.setAttribute("normal",new y.BufferAttribute(a,3)),c&&u.setAttribute("uv",new y.BufferAttribute(c,2)),u}class bl{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var w,x,b,v,T,S,_;const t=new y.Group,n=((w=e.styleOptions)==null?void 0:w.hexRadius)??Math.floor(e.divisions/2),s=((x=e.styleOptions)==null?void 0:x.tileSize)||1,r=String(e.color||"#ffffff"),o=Ht.getGridSpacing(s),a=o.width,c=o.height,u=new Tl(new y.Vector3(0,0,0),s,r,{metalness:(b=e.styleOptions)==null?void 0:b.metalness,roughness:(v=e.styleOptions)==null?void 0:v.roughness,transmission:(T=e.styleOptions)==null?void 0:T.transmission,thickness:(S=e.styleOptions)==null?void 0:S.thickness,ior:(_=e.styleOptions)==null?void 0:_.ior}),d=u.createGeometry(),h=Ht.getYPosition(s),f=[];for(let A=-n;A<=n;A++){const L=Math.max(-n,-A-n),I=Math.min(n,-A+n);for(let C=L;C<=I;C++)f.push(new y.Vector3(a*(A+C/2),h,c*.75*C))}const m=new y.Mesh(Sl(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 y.Mesh(new y.CircleGeometry(Math.max(e,1),64),new y.ShadowMaterial({opacity:.35}));return t.name=Vt,t.userData[vs]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class _l{constructor(){this.name="Stone Tile Grid",this.textureLoader=new y.TextureLoader}createGrid(e){var m,w,x,b;const t=new y.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=((x=e.styleOptions)==null?void 0:x.randomHeight)||!1,h=((b=e.styleOptions)==null?void 0:b.randomRotation)||!1,f=this.createStoneMaterial(e);for(let v=0;v<s;v++)for(let T=0;T<s;T++){const S=(v-s/2)*r+r/2,_=(T-s/2)*r+r/2,A=d?c*(.8+Math.random()*.4):c,L=new y.Shape,I=a/2;L.moveTo(-I,-I),L.lineTo(I,-I),L.lineTo(I,I),L.lineTo(-I,I),L.closePath();const C={depth:A,bevelEnabled:!0,bevelSize:u,bevelThickness:u,bevelSegments:2},D=new y.ExtrudeGeometry(L,C);D.rotateX(-Math.PI/2);const P=new y.Mesh(D,f);P.position.set(S,-A/2,_),P.castShadow=!0,P.receiveShadow=!0,h&&(P.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(P)}return t}createStoneMaterial(e){var o,a,c,u,d;const t=new y.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=y.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=y.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=y.RepeatWrapping,h.repeat.set(1,1))}return new y.MeshStandardMaterial(r)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}class xl{constructor(){this.name="Shadow Floor"}createGrid(e){const t=new y.Group,n=Math.max(e.size||1,1)*1.5;return t.add(this.createShadowCatcher(n)),t.add(this.createPathTracingDome(n)),t}createShadowCatcher(e){const t=new y.Mesh(new y.CircleGeometry(Math.max(e,1),64),new y.ShadowMaterial({opacity:.28}));return t.name=Vt,t.userData[vs]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}createPathTracingDome(e){const t=Math.max(e,1),n=t*1.6,s=t*2,r=t*.5,o=n-r,a=[new y.Vector2(0,0),new y.Vector2(o,0)],c=16;for(let d=1;d<=c;d+=1){const h=d/c*(Math.PI/2);a.push(new y.Vector2(o+r*Math.sin(h),r*(1-Math.cos(h))))}a.push(new y.Vector2(n,s));const u=new y.Mesh(new y.LatheGeometry(a,96),new y.MeshStandardMaterial({color:"#f0f0f0",roughness:1,metalness:0,side:y.DoubleSide}));return u.userData[Ms]=!0,u.position.y=.001,u.receiveShadow=!0,u.visible=!1,u}dispose(){}}const Pi=class Pi{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(Et.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()}};Pi.gridStyles=new Map([[Et.SHADOW_FLOOR,new xl],[Et.SQUARE_WIRE,new wl],[Et.HEXAGONAL_WIRE,new El],[Et.HEXAGONAL_GLASS,new bl],[Et.STONE_TILES,new _l]]);let ys=Pi;function Al(i,e){try{const t=ft(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));if(e.grid){const n=t.userData,s=typeof e.grid=="object"?e.grid:null,r={enabled:!0,color:(s==null?void 0:s.colorGrid)||e.gridColor||"#AAAAAA",type:s!=null&&s.type?s.type:Et.HEXAGONAL_GLASS,opacity:s==null?void 0:s.opacity,styleOptions:s==null?void 0:s.styleOptions};if(t.userData={...n,gridOptions:r},s!=null&&s.size||s!=null&&s.divisions){const o=r.type||Et.HEXAGONAL_GLASS,a=s.size||10,c=s.divisions||10,u={size:a,divisions:c,color:r.color,opacity:r.opacity,styleOptions:{hexRadius:Math.floor(c/2),tileSize:1,...r.styleOptions}},d=ys.createGrid(o,u);d.userData.isGrid=!0,d.userData.isDefaultGrid=!0,t.add(d)}}if(e.axes){const n=e.axesSize||5,s=new y.AxesHelper(n);t.add(s)}return N.ok(void 0)}catch(t){return N.err(new Z("Failed to add helpers to scene",K.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function vl(i,e,t=1.2){var n;try{const s=ft(i);if(!s)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const r=s.userData,o=r==null?void 0:r.gridOptions;if(!(o!=null&&o.enabled))return N.ok(void 0);const a=[];s.traverse(D=>{var P,F,k;((P=D.userData)!=null&&P.isGrid||(F=D.userData)!=null&&F.isHexGrid||(k=D.userData)!=null&&k.isDefaultGrid)&&a.push(D)}),a.forEach(D=>{As(D),s.remove(D)});const c=Tt(e);if(!c)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const u=new y.Box3().setFromObject(c),d=u.getSize(new y.Vector3);if(u.isEmpty()||!Number.isFinite(d.x)||!Number.isFinite(d.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),N.ok(void 0);const h=(n=o.styleOptions)==null?void 0:n.tileSize,f=typeof h=="number"?h:1,w=Ht.getGridSpacing(f).width,x=Math.max(d.x,d.z)*t+d.y;let b=x<=w?0:Math.ceil((x/w-1)/2);const v=60;b>v&&(console.warn(`Dynamic grid would need ${b} rings to cover the object; capping at ${v}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),b=v),x<w*.8?b=0:b<3&&x>w*2&&(b=3);const T=o.type||Et.HEXAGONAL_GLASS,_={size:Math.max(d.x,d.z)*t,divisions:b*2+1,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:b,tileSize:f,...o.styleOptions}},A=ys.createGrid(T,_);A.userData.isGrid=!0,A.userData.isHexGrid=!0;const L=y.MathUtils.clamp(d.y*.0025,2e-4,.002),I=A.getObjectByName(Vt);I&&(I.position.y=L),A.traverse(D=>{var P;(P=D.userData)!=null&&P[Ms]&&(D.position.y=L)});const C=u.getCenter(new y.Vector3);return A.position.set(C.x,0,C.z),s.add(A),N.ok(void 0)}catch(s){return N.err(new Z("Failed to add dynamic grid",K.SCENE_OPERATION_FAILED,{originalError:s}))}}function Ml(i,e){try{const t=ft(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=Tt(e);if(!n)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const s=S=>{var A,L,I;let _=S;for(;_;){if((A=_.userData)!=null&&A.isGrid||(L=_.userData)!=null&&L.isHexGrid||(I=_.userData)!=null&&I.isDefaultGrid)return!0;_=_.parent}return!1};t.updateMatrixWorld(!0);const r=[];t.traverse(S=>{var _;(_=S.userData)!=null&&_[Ms]||S.isMesh&&s(S)&&r.push(S)});const o=[];if(n.traverse(S=>{S.isMesh&&o.push(S)}),r.length===0||o.length===0)return N.ok(void 0);let a=-1/0;const c=new y.Box3;for(const S of r)c.setFromObject(S),Number.isFinite(c.max.y)&&(a=Math.max(a,c.max.y));if(!Number.isFinite(a))return N.ok(void 0);const u=new y.Box3().setFromObject(n);if(u.isEmpty()||!Number.isFinite(u.min.x)||!Number.isFinite(u.max.x))return N.ok(void 0);const d=40,h=Math.max(1,u.max.y-u.min.y),f=u.max.y+h,m=u.min.y-h,w=new y.Raycaster,x=new y.Vector3(0,-1,0),b=new y.Vector3(0,1,0);let v=1/0;const T=(S,_,A,L)=>{w.set(new y.Vector3(S,_,A),L);for(const I of w.intersectObjects(o,!1))I.point.y<v&&(v=I.point.y)};for(let S=0;S<=d;S++)for(let _=0;_<=d;_++){const A=u.min.x+(u.max.x-u.min.x)*(S/d),L=u.min.z+(u.max.z-u.min.z)*(_/d);T(A,f,L,x),T(A,m,L,b)}if(Number.isFinite(v)){const S=v-a;Math.abs(S)>1e-4&&(n.position.y-=S)}return N.ok(void 0)}catch(t){return N.err(new Z("Failed to snap object to floor",K.SCENE_OPERATION_FAILED,{originalError:t}))}}const Zr=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};function Rl(i,e){try{const t=ft(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=Tt(e);if(!n)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const s=new y.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return N.ok(void 0);const r=s.getSize(new y.Vector3),o=s.getCenter(new y.Vector3),a=Zr(t);if(!a||!a.castShadow)return N.ok(void 0);if(a.parent===t&&a.target.parent===t){const m=a.position.clone().sub(a.target.position);a.target.position.copy(o),a.position.copy(o).add(m)}const h=Math.max(r.x,r.y,r.z,.1)*2,f=a.shadow.camera;return f.left=-h,f.right=h,f.top=h,f.bottom=-h,f.updateProjectionMatrix(),N.ok(void 0)}catch(t){return N.err(new Z("Failed to fit shadow camera to object",K.SCENE_OPERATION_FAILED,{originalError:t}))}}function Cl(i,e,t,n){try{const s=ft(i);if(!s)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const r=Tt(e);if(!r)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const o=Wr(t.getInternalRenderer());if(!o||!o.shadowMap.enabled)return N.ok(void 0);const a=Zr(s);return!a||!a.castShadow||n.bake({renderer:o,scene:s,object:r,light:a}),N.ok(void 0)}catch(s){return N.err(new Z("Failed to bake contact shadow",K.SCENE_OPERATION_FAILED,{originalError:s}))}}function Pl(i,e){try{const t=ft(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=t.getObjectByName(gi),s=t.getObjectByName(Vt);return e==="baked"&&!n||(n&&(n.visible=e==="baked"),s&&(s.visible=e==="live")),N.ok(void 0)}catch(t){return N.err(new Z("Failed to switch contact shadow mode",K.SCENE_OPERATION_FAILED,{originalError:t}))}}function Il(i,e){try{const t=Tt(i);if(!t)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const n=new y.Group;return n.name=$o,n.scale.setScalar(e),n.add(t),N.ok(new Ke(n))}catch(t){return N.err(new Z("Failed to apply the units scale to the model",K.SCENE_OPERATION_FAILED,{originalError:t}))}}function Ll(i,e){try{const t=ft(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));if(e.ambient){const n=new y.Color(e.ambient.color||"#404040"),s=e.ambient.intensity??Math.PI,r=new y.AmbientLight(n,s);t.add(r)}if(e.hemisphere){const n=new y.Color(e.hemisphere.skyColor||"#ffffbb"),s=new y.Color(e.hemisphere.groundColor||"#080820"),r=e.hemisphere.intensity??1,o=new y.HemisphereLight(n,s,r);t.add(o)}if(e.directional){const n=new y.Color(e.directional.color||"#ffffff"),s=e.directional.intensity??Math.PI,r=new y.DirectionalLight(n,s);if(e.directional.position){const o=e.directional.position;if(o instanceof y.Vector3)r.position.copy(o);else if(Array.isArray(o))r.position.set(o[0],o[1],o[2]);else if(typeof o=="object"&&"x"in o&&"y"in o&&"z"in o){const a=o;r.position.set(a.x,a.y,a.z)}}else r.position.set(6,6,6);if(e.directional.castShadow&&(r.castShadow=!0,e.directional.shadow)){const o=e.directional.shadow;if(o.mapSize&&(r.shadow.mapSize.width=o.mapSize.width,r.shadow.mapSize.height=o.mapSize.height),o.camera){const a=r.shadow.camera;o.camera.near!==void 0&&(a.near=o.camera.near),o.camera.far!==void 0&&(a.far=o.camera.far),o.camera.left!==void 0&&(a.left=o.camera.left),o.camera.right!==void 0&&(a.right=o.camera.right),o.camera.top!==void 0&&(a.top=o.camera.top),o.camera.bottom!==void 0&&(a.bottom=o.camera.bottom)}o.bias!==void 0&&(r.shadow.bias=o.bias),o.radius!==void 0&&(r.shadow.radius=o.radius)}r.target.position.set(0,0,0),t.add(r),t.add(r.target),r.shadow&&r.shadow.camera.updateProjectionMatrix()}return N.ok(void 0)}catch(t){return N.err(new Z("Failed to add lighting to scene",K.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function Ol(i,e){try{const t=ft(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=document.createElement("canvas");n.width=e.radial?512:2,n.height=512;const s=n.getContext("2d");if(!s)return N.err(new Z("Failed to create canvas context",K.SCENE_OPERATION_FAILED));const r=e.radial?s.createRadialGradient(256,205,0,256,256,380):s.createLinearGradient(0,0,0,n.height);r.addColorStop(0,e.topColor),r.addColorStop(1,e.bottomColor),s.fillStyle=r,s.fillRect(0,0,n.width,n.height);const o=new y.CanvasTexture(n);o.needsUpdate=!0;const a=t.background;return a instanceof y.Texture&&a!==t.environment&&a.dispose(),t.background=o,N.ok(void 0)}catch(t){return N.err(new Z("Failed to create gradient background",K.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function Dl(i,e,t){try{const n=Tt(i);if(!n)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const s=Pn(e);if(!(s instanceof y.PerspectiveCamera)&&!(s instanceof y.OrthographicCamera))return N.err(new Z("Camera must expose a perspective or orthographic Three.js camera",K.INVALID_PARAMETER));const r=Mi(t);if(!r)return N.err(new Z("Controls must expose the underlying Three.js controls",K.INVALID_PARAMETER));const o=new y.Box3().setFromObject(n),a=o.getCenter(new y.Vector3),c=o.getSize(new y.Vector3),u=Math.max(c.x,c.y,c.z);let d;"fov"in s?d=s.fov*(Math.PI/180):d=50*(Math.PI/180);let h=Math.abs(u/2/Math.tan(d/2));h*=1.65;const f=-Math.PI/4,m=Math.PI/8,w=a.x+h*Math.sin(f)*Math.cos(m),x=a.y+h*Math.sin(m),b=a.z+h*Math.cos(f)*Math.cos(m);return s.position.set(w,x,b),s.lookAt(a),s.updateProjectionMatrix(),r.target&&(r.target.copy(a),r.update()),N.ok(void 0)}catch(n){return N.err(new Z("Failed to fit camera to object",K.CAMERA_INIT_FAILED,{originalError:n}))}}class Nl{constructor(){this.contactShadowBaker=new yi}addHelpers(e,t){return Al(e,t)}addDynamicGrid(e,t,n=1.2){return vl(e,t,n)}snapObjectToFloor(e,t){return Ml(e,t)}fitShadowCameraToObject(e,t){return Rl(e,t)}bakeContactShadow(e,t,n){return Cl(e,t,n,this.contactShadowBaker)}setContactShadowMode(e,t){return Pl(e,t)}wrapInUnitsScaleGroup(e,t){return Il(e,t)}addLighting(e,t){return Ll(e,t)}createGradientBackground(e,t){return Ol(e,t)}fitCameraToObject(e,t,n){return Dl(e,t,n)}}class kl{constructor(){this.events=new Ts,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-CYLglFOT.cjs"));if(this.disposed)return N.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(N.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}canResume(){var e;return((e=this.inner)==null?void 0:e.canResume())??!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}}/*!
21
- fflate - fast JavaScript compression/decompression
22
- <https://101arrowz.github.io/fflate>
23
- Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
24
- version 0.8.2
25
- */var it=Uint8Array,rn=Uint16Array,Fl=Int32Array,Kr=new it([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xr=new it([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Bl=new it([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yr=function(i,e){for(var t=new rn(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new Fl(t[30]),n=1;n<30;++n)for(var r=t[n];r<t[n+1];++r)s[r]=r-t[n]<<5|n;return{b:t,r:s}},qr=Yr(Kr,2),$r=qr.b,zl=qr.r;$r[28]=258,zl[258]=28;var Ul=Yr(Xr,0),Vl=Ul.b,wi=new rn(32768);for(var be=0;be<32768;++be){var Ct=(be&43690)>>1|(be&21845)<<1;Ct=(Ct&52428)>>2|(Ct&13107)<<2,Ct=(Ct&61680)>>4|(Ct&3855)<<4,wi[be]=((Ct&65280)>>8|(Ct&255)<<8)>>1}var An=(function(i,e,t){for(var n=i.length,s=0,r=new rn(e);s<n;++s)i[s]&&++r[i[s]-1];var o=new rn(e);for(s=1;s<e;++s)o[s]=o[s-1]+r[s-1]<<1;var a;if(t){a=new rn(1<<e);var c=15-e;for(s=0;s<n;++s)if(i[s])for(var u=s<<4|i[s],d=e-i[s],h=o[i[s]-1]++<<d,f=h|(1<<d)-1;h<=f;++h)a[wi[h]>>c]=u}else for(a=new rn(n),s=0;s<n;++s)i[s]&&(a[s]=wi[o[i[s]-1]++]>>15-i[s]);return a}),In=new it(288);for(var be=0;be<144;++be)In[be]=8;for(var be=144;be<256;++be)In[be]=9;for(var be=256;be<280;++be)In[be]=7;for(var be=280;be<288;++be)In[be]=8;var Qr=new it(32);for(var be=0;be<32;++be)Qr[be]=5;var Hl=An(In,9,1),Gl=An(Qr,5,1),Xs=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},lt=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},Ys=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},jl=function(i){return(i+7)/8|0},Wl=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new it(i.subarray(e,t))},Zl=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ut=function(i,e,t){var n=new Error(e||Zl[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,ut),!t)throw n;return n},Kl=function(i,e,t,n){var s=i.length,r=0;if(!s||e.f&&!e.l)return t||new it(0);var o=!t,a=o||e.i!=2,c=e.i;o&&(t=new it(s*3));var u=function(Gt){var St=t.length;if(Gt>St){var Ln=new it(Math.max(St*2,Gt));Ln.set(t),t=Ln}},d=e.f||0,h=e.p||0,f=e.b||0,m=e.l,w=e.d,x=e.m,b=e.n,v=s*8;do{if(!m){d=lt(i,h,1);var T=lt(i,h+1,3);if(h+=3,T)if(T==1)m=Hl,w=Gl,x=9,b=5;else if(T==2){var L=lt(i,h,31)+257,I=lt(i,h+10,15)+4,C=L+lt(i,h+5,31)+1;h+=14;for(var D=new it(C),P=new it(19),F=0;F<I;++F)P[Bl[F]]=lt(i,h+F*3,7);h+=I*3;for(var k=Xs(P),G=(1<<k)-1,z=An(P,k,1),F=0;F<C;){var Y=z[lt(i,h,G)];h+=Y&15;var S=Y>>4;if(S<16)D[F++]=S;else{var re=0,Ne=0;for(S==16?(Ne=3+lt(i,h,3),h+=2,re=D[F-1]):S==17?(Ne=3+lt(i,h,7),h+=3):S==18&&(Ne=11+lt(i,h,127),h+=7);Ne--;)D[F++]=re}}var ot=D.subarray(0,L),Re=D.subarray(L);x=Xs(ot),b=Xs(Re),m=An(ot,x,1),w=An(Re,b,1)}else ut(1);else{var S=jl(h)+4,_=i[S-4]|i[S-3]<<8,A=S+_;if(A>s){c&&ut(0);break}a&&u(f+_),t.set(i.subarray(S,A),f),e.b=f+=_,e.p=h=A*8,e.f=d;continue}if(h>v){c&&ut(0);break}}a&&u(f+131072);for(var ze=(1<<x)-1,Ge=(1<<b)-1,ve=h;;ve=h){var re=m[Ys(i,h)&ze],ye=re>>4;if(h+=re&15,h>v){c&&ut(0);break}if(re||ut(2),ye<256)t[f++]=ye;else if(ye==256){ve=h,m=null;break}else{var pt=ye-254;if(ye>264){var F=ye-257,je=Kr[F];pt=lt(i,h,(1<<je)-1)+$r[F],h+=je}var At=w[Ys(i,h)&Ge],ge=At>>4;At||ut(3),h+=At&15;var Re=Vl[ge];if(ge>3){var je=Xr[ge];Re+=Ys(i,h)&(1<<je)-1,h+=je}if(h>v){c&&ut(0);break}a&&u(f+131072);var at=f+pt;if(f<Re){var ct=r-Re,ln=Math.min(Re,at);for(ct+f<0&&ut(3);f<ln;++f)t[f]=n[ct+f]}for(;f<at;++f)t[f]=t[f-Re]}}e.l=m,e.p=ve,e.b=f,e.f=d,m&&(d=1,e.m=x,e.d=w,e.n=b)}while(!d);return f!=t.length&&o?Wl(t,0,f):t.subarray(0,f)},Xl=new it(0),Yl=function(i,e){return((i[0]&15)!=8||i[0]>>4>7||(i[0]<<8|i[1])%31)&&ut(6,"invalid zlib data"),(i[1]>>5&1)==1&&ut(6,"invalid zlib data: "+(i[1]&32?"need":"unexpected")+" dictionary"),(i[1]>>3&4)+2};function Sn(i,e){return Kl(i.subarray(Yl(i),-4),{i:2},e,e)}var ql=typeof TextDecoder<"u"&&new TextDecoder,$l=0;try{ql.decode(Xl,{stream:!0}),$l=1}catch{}class Ql extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType,this.outputFormat=p.RGBAFormat,this.part=0}parse(e){const D=Math.pow(2.7182818,2.2);let P=null;function F(l,g){let E=0;for(let O=0;O<65536;++O)(O==0||l[O>>3]&1<<(O&7))&&(g[E++]=O);const R=E-1;for(;E<65536;)g[E++]=0;return R}function k(l){for(let g=0;g<16384;g++)l[g]={},l[g].len=0,l[g].lit=0,l[g].p=null}const G={l:0,c:0,lc:0};function z(l,g,E,R,O){for(;E<l;)g=g<<8|ki(R,O),E+=8;E-=l,G.l=g>>E&(1<<l)-1,G.c=g,G.lc=E}const Y=new Array(59);function re(l){for(let E=0;E<=58;++E)Y[E]=0;for(let E=0;E<65537;++E)Y[l[E]]+=1;let g=0;for(let E=58;E>0;--E){const R=g+Y[E]>>1;Y[E]=g,g=R}for(let E=0;E<65537;++E){const R=l[E];R>0&&(l[E]=R|Y[R]++<<6)}}function Ne(l,g,E,R,O,U){const M=g;let H=0,B=0;for(;R<=O;R++){if(M.value-g.value>E)return!1;z(6,H,B,l,M);const V=G.l;if(H=G.c,B=G.lc,U[R]=V,V==63){if(M.value-g.value>E)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");z(8,H,B,l,M);let j=G.l+6;if(H=G.c,B=G.lc,R+j>O+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)U[R++]=0;R--}else if(V>=59){let j=V-59+2;if(R+j>O+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)U[R++]=0;R--}}re(U)}function ot(l){return l&63}function Re(l){return l>>6}function ze(l,g,E,R){for(;g<=E;g++){const O=Re(l[g]),U=ot(l[g]);if(O>>U)throw new Error("THREE.EXRLoader: Invalid table entry");if(U>14){const M=R[O>>U-14];if(M.len)throw new Error("THREE.EXRLoader: Invalid table entry");if(M.lit++,M.p){const H=M.p;M.p=new Array(M.lit);for(let B=0;B<M.lit-1;++B)M.p[B]=H[B]}else M.p=new Array(1);M.p[M.lit-1]=g}else if(U){let M=0;for(let H=1<<14-U;H>0;H--){const B=R[(O<<14-U)+M];if(B.len||B.p)throw new Error("THREE.EXRLoader: Invalid table entry");B.len=U,B.lit=g,M++}}}return!0}const Ge={c:0,lc:0};function ve(l,g,E,R){l=l<<8|ki(E,R),g+=8,Ge.c=l,Ge.lc=g}const ye={c:0,lc:0};function pt(l,g,E,R,O,U,M,H,B){if(l==g){R<8&&(ve(E,R,O,U),E=Ge.c,R=Ge.lc),R-=8;let V=E>>R;if(V=new Uint8Array([V])[0],H.value+V>B)return!1;const j=M[H.value-1];for(;V-- >0;)M[H.value++]=j}else if(H.value<B)M[H.value++]=l;else return!1;ye.c=E,ye.lc=R}function je(l){return l&65535}function At(l){const g=je(l);return g>32767?g-65536:g}const ge={a:0,b:0};function at(l,g){const E=At(l),O=At(g),U=E+(O&1)+(O>>1),M=U,H=U-O;ge.a=M,ge.b=H}function ct(l,g){const E=je(l),R=je(g),O=E-(R>>1)&65535,U=R+O-32768&65535;ge.a=U,ge.b=O}function ln(l,g,E,R,O,U,M){const H=M<16384,B=E>O?O:E;let V=1,j,X;for(;V<=B;)V<<=1;for(V>>=1,j=V,V>>=1;V>=1;){X=0;const W=X+U*(O-j),$=U*V,ee=U*j,q=R*V,Q=R*j;let oe,he,ae,de;for(;X<=W;X+=ee){let ne=X;const te=X+R*(E-j);for(;ne<=te;ne+=Q){const ie=ne+q,we=ne+$,pe=we+q;H?(at(l[ne+g],l[we+g]),oe=ge.a,ae=ge.b,at(l[ie+g],l[pe+g]),he=ge.a,de=ge.b,at(oe,he),l[ne+g]=ge.a,l[ie+g]=ge.b,at(ae,de),l[we+g]=ge.a,l[pe+g]=ge.b):(ct(l[ne+g],l[we+g]),oe=ge.a,ae=ge.b,ct(l[ie+g],l[pe+g]),he=ge.a,de=ge.b,ct(oe,he),l[ne+g]=ge.a,l[ie+g]=ge.b,ct(ae,de),l[we+g]=ge.a,l[pe+g]=ge.b)}if(E&V){const ie=ne+$;H?at(l[ne+g],l[ie+g]):ct(l[ne+g],l[ie+g]),oe=ge.a,l[ie+g]=ge.b,l[ne+g]=oe}}if(O&V){let ne=X;const te=X+R*(E-j);for(;ne<=te;ne+=Q){const ie=ne+q;H?at(l[ne+g],l[ie+g]):ct(l[ne+g],l[ie+g]),oe=ge.a,l[ie+g]=ge.b,l[ne+g]=oe}}j=V,V>>=1}return X}function Gt(l,g,E,R,O,U,M,H,B){let V=0,j=0;const X=M,W=Math.trunc(R.value+(O+7)/8);for(;R.value<W;)for(ve(V,j,E,R),V=Ge.c,j=Ge.lc;j>=14;){const ee=V>>j-14&16383,q=g[ee];if(q.len)j-=q.len,pt(q.lit,U,V,j,E,R,H,B,X),V=ye.c,j=ye.lc;else{if(!q.p)throw new Error("THREE.EXRLoader: hufDecode issues");let Q;for(Q=0;Q<q.lit;Q++){const oe=ot(l[q.p[Q]]);for(;j<oe&&R.value<W;)ve(V,j,E,R),V=Ge.c,j=Ge.lc;if(j>=oe&&Re(l[q.p[Q]])==(V>>j-oe&(1<<oe)-1)){j-=oe,pt(q.p[Q],U,V,j,E,R,H,B,X),V=ye.c,j=ye.lc;break}}if(Q==q.lit)throw new Error("THREE.EXRLoader: hufDecode issues")}}const $=8-O&7;for(V>>=$,j-=$;j>0;){const ee=g[V<<14-j&16383];if(ee.len)j-=ee.len,pt(ee.lit,U,V,j,E,R,H,B,X),V=ye.c,j=ye.lc;else throw new Error("THREE.EXRLoader: hufDecode issues")}return!0}function St(l,g,E,R,O,U){const M={value:0},H=E.value,B=Je(g,E),V=Je(g,E);E.value+=4;const j=Je(g,E);if(E.value+=4,B<0||B>=65537||V<0||V>=65537)throw new Error("THREE.EXRLoader: Something wrong with HUF_ENCSIZE");const X=new Array(65537),W=new Array(16384);k(W);const $=R-(E.value-H);if(Ne(l,E,$,B,V,X),j>8*(R-(E.value-H)))throw new Error("THREE.EXRLoader: Something wrong with hufUncompress");ze(X,B,V,W),Gt(X,W,l,E,j,V,U,O,M)}function Ln(l,g,E){for(let R=0;R<E;++R)g[R]=l[g[R]]}function On(l){for(let g=1;g<l.length;g++){const E=l[g-1]+l[g]-128;l[g]=E}}function Dn(l,g){let E=0,R=Math.floor((l.length+1)/2),O=0;const U=l.length-1;for(;!(O>U||(g[O++]=l[E++],O>U));)g[O++]=l[R++]}function Rs(l){let g=l.byteLength;const E=new Array;let R=0;const O=new DataView(l);for(;g>0;){const U=O.getInt8(R++);if(U<0){const M=-U;g-=M+1;for(let H=0;H<M;H++)E.push(O.getUint8(R++))}else{const M=U;g-=2;const H=O.getUint8(R++);for(let B=0;B<M+1;B++)E.push(H)}}return E}function uo(l,g,E,R,O,U){let M=new DataView(U.buffer);const H=E[l.idx[0]].width,B=E[l.idx[0]].height,V=3,j=Math.floor(H/8),X=Math.ceil(H/8),W=Math.ceil(B/8),$=H-(X-1)*8,ee=B-(W-1)*8,q={value:0},Q=new Array(V),oe=new Array(V),he=new Array(V),ae=new Array(V),de=new Array(V);for(let te=0;te<V;++te)de[te]=g[l.idx[te]],Q[te]=te<1?0:Q[te-1]+X*W,oe[te]=new Float32Array(64),he[te]=new Uint16Array(64),ae[te]=new Uint16Array(X*64);for(let te=0;te<W;++te){let ie=8;te==W-1&&(ie=ee);let we=8;for(let ce=0;ce<X;++ce){ce==X-1&&(we=$);for(let ue=0;ue<V;++ue)he[ue].fill(0),he[ue][0]=O[Q[ue]++],Ii(q,R,he[ue]),Li(he[ue],oe[ue]),Oi(oe[ue]);po(oe);for(let ue=0;ue<V;++ue)Di(oe[ue],ae[ue],ce*64)}let pe=0;for(let ce=0;ce<V;++ce){const ue=E[l.idx[ce]].type;for(let Ce=8*te;Ce<8*te+ie;++Ce){pe=de[ce][Ce];for(let et=0;et<j;++et){const Se=et*64+(Ce&7)*8;M.setUint16(pe+0*ue,ae[ce][Se+0],!0),M.setUint16(pe+2*ue,ae[ce][Se+1],!0),M.setUint16(pe+4*ue,ae[ce][Se+2],!0),M.setUint16(pe+6*ue,ae[ce][Se+3],!0),M.setUint16(pe+8*ue,ae[ce][Se+4],!0),M.setUint16(pe+10*ue,ae[ce][Se+5],!0),M.setUint16(pe+12*ue,ae[ce][Se+6],!0),M.setUint16(pe+14*ue,ae[ce][Se+7],!0),pe+=16*ue}}if(j!=X)for(let Ce=8*te;Ce<8*te+ie;++Ce){const et=de[ce][Ce]+8*j*2*ue,Se=j*64+(Ce&7)*8;for(let mt=0;mt<we;++mt)M.setUint16(et+mt*2*ue,ae[ce][Se+mt],!0)}}}const ne=new Uint16Array(H);M=new DataView(U.buffer);for(let te=0;te<V;++te){E[l.idx[te]].decoded=!0;const ie=E[l.idx[te]].type;if(E[te].type==2)for(let we=0;we<B;++we){const pe=de[te][we];for(let ce=0;ce<H;++ce)ne[ce]=M.getUint16(pe+ce*2*ie,!0);for(let ce=0;ce<H;++ce)M.setFloat32(pe+ce*2*ie,J(ne[ce]),!0)}}}function fo(l,g,E,R,O,U){const M=new DataView(U.buffer),H=E[l],B=H.width,V=H.height,j=Math.ceil(B/8),X=Math.ceil(V/8),W=Math.floor(B/8),$=B-(j-1)*8,ee=V-(X-1)*8,q={value:0};let Q=0;const oe=new Float32Array(64),he=new Uint16Array(64),ae=new Uint16Array(j*64);for(let de=0;de<X;++de){let ne=8;de==X-1&&(ne=ee);for(let te=0;te<j;++te)he.fill(0),he[0]=O[Q++],Ii(q,R,he),Li(he,oe),Oi(oe),Di(oe,ae,te*64);for(let te=8*de;te<8*de+ne;++te){let ie=g[l][te];for(let we=0;we<W;++we){const pe=we*64+(te&7)*8;for(let ce=0;ce<8;++ce)M.setUint16(ie+ce*2*H.type,ae[pe+ce],!0);ie+=16*H.type}if(j!=W){const we=W*64+(te&7)*8;for(let pe=0;pe<$;++pe)M.setUint16(ie+pe*2*H.type,ae[we+pe],!0)}}}H.decoded=!0}function Ii(l,g,E){let R,O=1;for(;O<64;)R=g[l.value],R==65280?O=64:R>>8==255?O+=R&255:(E[O]=R,O++),l.value++}function Li(l,g){g[0]=J(l[0]),g[1]=J(l[1]),g[2]=J(l[5]),g[3]=J(l[6]),g[4]=J(l[14]),g[5]=J(l[15]),g[6]=J(l[27]),g[7]=J(l[28]),g[8]=J(l[2]),g[9]=J(l[4]),g[10]=J(l[7]),g[11]=J(l[13]),g[12]=J(l[16]),g[13]=J(l[26]),g[14]=J(l[29]),g[15]=J(l[42]),g[16]=J(l[3]),g[17]=J(l[8]),g[18]=J(l[12]),g[19]=J(l[17]),g[20]=J(l[25]),g[21]=J(l[30]),g[22]=J(l[41]),g[23]=J(l[43]),g[24]=J(l[9]),g[25]=J(l[11]),g[26]=J(l[18]),g[27]=J(l[24]),g[28]=J(l[31]),g[29]=J(l[40]),g[30]=J(l[44]),g[31]=J(l[53]),g[32]=J(l[10]),g[33]=J(l[19]),g[34]=J(l[23]),g[35]=J(l[32]),g[36]=J(l[39]),g[37]=J(l[45]),g[38]=J(l[52]),g[39]=J(l[54]),g[40]=J(l[20]),g[41]=J(l[22]),g[42]=J(l[33]),g[43]=J(l[38]),g[44]=J(l[46]),g[45]=J(l[51]),g[46]=J(l[55]),g[47]=J(l[60]),g[48]=J(l[21]),g[49]=J(l[34]),g[50]=J(l[37]),g[51]=J(l[47]),g[52]=J(l[50]),g[53]=J(l[56]),g[54]=J(l[59]),g[55]=J(l[61]),g[56]=J(l[35]),g[57]=J(l[36]),g[58]=J(l[48]),g[59]=J(l[49]),g[60]=J(l[57]),g[61]=J(l[58]),g[62]=J(l[62]),g[63]=J(l[63])}function Oi(l){const g=.5*Math.cos(.7853975),E=.5*Math.cos(3.14159/16),R=.5*Math.cos(3.14159/8),O=.5*Math.cos(3*3.14159/16),U=.5*Math.cos(5*3.14159/16),M=.5*Math.cos(3*3.14159/8),H=.5*Math.cos(7*3.14159/16),B=new Array(4),V=new Array(4),j=new Array(4),X=new Array(4);for(let W=0;W<8;++W){const $=W*8;B[0]=R*l[$+2],B[1]=M*l[$+2],B[2]=R*l[$+6],B[3]=M*l[$+6],V[0]=E*l[$+1]+O*l[$+3]+U*l[$+5]+H*l[$+7],V[1]=O*l[$+1]-H*l[$+3]-E*l[$+5]-U*l[$+7],V[2]=U*l[$+1]-E*l[$+3]+H*l[$+5]+O*l[$+7],V[3]=H*l[$+1]-U*l[$+3]+O*l[$+5]-E*l[$+7],j[0]=g*(l[$+0]+l[$+4]),j[3]=g*(l[$+0]-l[$+4]),j[1]=B[0]+B[3],j[2]=B[1]-B[2],X[0]=j[0]+j[1],X[1]=j[3]+j[2],X[2]=j[3]-j[2],X[3]=j[0]-j[1],l[$+0]=X[0]+V[0],l[$+1]=X[1]+V[1],l[$+2]=X[2]+V[2],l[$+3]=X[3]+V[3],l[$+4]=X[3]-V[3],l[$+5]=X[2]-V[2],l[$+6]=X[1]-V[1],l[$+7]=X[0]-V[0]}for(let W=0;W<8;++W)B[0]=R*l[16+W],B[1]=M*l[16+W],B[2]=R*l[48+W],B[3]=M*l[48+W],V[0]=E*l[8+W]+O*l[24+W]+U*l[40+W]+H*l[56+W],V[1]=O*l[8+W]-H*l[24+W]-E*l[40+W]-U*l[56+W],V[2]=U*l[8+W]-E*l[24+W]+H*l[40+W]+O*l[56+W],V[3]=H*l[8+W]-U*l[24+W]+O*l[40+W]-E*l[56+W],j[0]=g*(l[W]+l[32+W]),j[3]=g*(l[W]-l[32+W]),j[1]=B[0]+B[3],j[2]=B[1]-B[2],X[0]=j[0]+j[1],X[1]=j[3]+j[2],X[2]=j[3]-j[2],X[3]=j[0]-j[1],l[0+W]=X[0]+V[0],l[8+W]=X[1]+V[1],l[16+W]=X[2]+V[2],l[24+W]=X[3]+V[3],l[32+W]=X[3]-V[3],l[40+W]=X[2]-V[2],l[48+W]=X[1]-V[1],l[56+W]=X[0]-V[0]}function po(l){for(let g=0;g<64;++g){const E=l[0][g],R=l[1][g],O=l[2][g];l[0][g]=E+1.5747*O,l[1][g]=E-.1873*R-.4682*O,l[2][g]=E+1.8556*R}}function Di(l,g,E){for(let R=0;R<64;++R)g[E+R]=p.DataUtils.toHalfFloat(mo(l[R]))}function mo(l){return l<=1?Math.sign(l)*Math.pow(Math.abs(l),2.2):Math.sign(l)*Math.pow(D,Math.abs(l)-1)}function Nn(l){return new DataView(l.array.buffer,l.offset.value,l.size)}function go(l){const g=l.viewer.buffer.slice(l.offset.value,l.offset.value+l.size),E=new Uint8Array(Rs(g)),R=new Uint8Array(E.length);return On(E),Dn(E,R),new DataView(R.buffer)}function Cs(l){const g=l.array.slice(l.offset.value,l.offset.value+l.size),E=Sn(g),R=new Uint8Array(E.length);return On(E),Dn(E,R),new DataView(R.buffer)}function yo(l){const g=l.viewer,E={value:l.offset.value},R=new Uint16Array(l.columns*l.lines*(l.inputChannels.length*l.type)),O=new Uint8Array(8192);let U=0;const M=new Array(l.inputChannels.length);for(let ee=0,q=l.inputChannels.length;ee<q;ee++)M[ee]={},M[ee].start=U,M[ee].end=M[ee].start,M[ee].nx=l.columns,M[ee].ny=l.lines,M[ee].size=l.type,U+=M[ee].nx*M[ee].ny*M[ee].size;const H=hn(g,E),B=hn(g,E);if(B>=8192)throw new Error("THREE.EXRLoader: Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(H<=B)for(let ee=0;ee<B-H+1;ee++)O[ee+H]=vt(g,E);const V=new Uint16Array(65536),j=F(O,V),X=Je(g,E);St(l.array,g,E,X,R,U);for(let ee=0;ee<l.inputChannels.length;++ee){const q=M[ee];for(let Q=0;Q<M[ee].size;++Q)ln(R,q.start+Q,q.nx,q.size,q.ny,q.nx*q.size,j)}Ln(V,R,U);let W=0;const $=new Uint8Array(R.buffer.byteLength);for(let ee=0;ee<l.lines;ee++)for(let q=0;q<l.inputChannels.length;q++){const Q=M[q],oe=Q.nx*Q.size,he=new Uint8Array(R.buffer,Q.end*2,oe*2);$.set(he,W),W+=oe*2,Q.end+=oe}return new DataView($.buffer)}function wo(l){const g=l.array.slice(l.offset.value,l.offset.value+l.size),E=Sn(g),R=l.inputChannels.length*l.lines*l.columns*l.totalBytes,O=new ArrayBuffer(R),U=new DataView(O);let M=0,H=0;const B=new Array(4);for(let V=0;V<l.lines;V++)for(let j=0;j<l.inputChannels.length;j++){let X=0;switch(l.inputChannels[j].pixelType){case 1:B[0]=M,B[1]=B[0]+l.columns,M=B[1]+l.columns;for(let $=0;$<l.columns;++$){const ee=E[B[0]++]<<8|E[B[1]++];X+=ee,U.setUint16(H,X,!0),H+=2}break;case 2:B[0]=M,B[1]=B[0]+l.columns,B[2]=B[1]+l.columns,M=B[2]+l.columns;for(let $=0;$<l.columns;++$){const ee=E[B[0]++]<<24|E[B[1]++]<<16|E[B[2]++]<<8;X+=ee,U.setUint32(H,X,!0),H+=4}break}}return U}function Eo(l){const g=l.array;let E=l.offset.value;const R=l.columns,O=l.lines,U=l.inputChannels,M=l.totalBytes,H=Ze.compression==="B44A_COMPRESSION",B=new Uint8Array(O*R*M),V=new Uint16Array(16);let j=0;for(let X=0;X<U.length;X++){const W=U[X],$=W.pixelType*2,ee=Math.ceil(R/W.xSampling),q=Math.ceil(O/W.ySampling),Q=W.xSampling===1&&W.ySampling===1;if(W.pixelType!==1){for(let ae=0;ae<q;ae++)if(Q){const de=ae*R*M+j*R;for(let ne=0;ne<ee*$;ne++)B[de+ne]=g[E++]}else E+=ee*$;j+=$;continue}const oe=Math.ceil(ee/4),he=Math.ceil(q/4);for(let ae=0;ae<he;ae++)for(let de=0;de<oe;de++){if(H&&g[E+2]>=52){const ne=g[E]<<8|g[E+1],te=ne&32768?ne&32767:~ne&65535;V.fill(te),E+=3}else{const ne=g[E]<<8|g[E+1],te=g[E+2]>>2,ie=32<<te,we=ne+((g[E+2]<<4|g[E+3]>>4)&63)*(1<<te)-ie&65535,pe=we+((g[E+3]<<2|g[E+4]>>6)&63)*(1<<te)-ie&65535,ce=pe+(g[E+4]&63)*(1<<te)-ie&65535,ue=ne+(g[E+5]>>2&63)*(1<<te)-ie&65535,Ce=we+((g[E+5]<<4|g[E+6]>>4)&63)*(1<<te)-ie&65535,et=pe+((g[E+6]<<2|g[E+7]>>6)&63)*(1<<te)-ie&65535,Se=ce+(g[E+7]&63)*(1<<te)-ie&65535,mt=ue+(g[E+8]>>2&63)*(1<<te)-ie&65535,jt=Ce+((g[E+8]<<4|g[E+9]>>4)&63)*(1<<te)-ie&65535,un=et+((g[E+9]<<2|g[E+10]>>6)&63)*(1<<te)-ie&65535,gt=Se+(g[E+10]&63)*(1<<te)-ie&65535,kt=mt+(g[E+11]>>2&63)*(1<<te)-ie&65535,Un=jt+((g[E+11]<<4|g[E+12]>>4)&63)*(1<<te)-ie&65535,Vn=un+((g[E+12]<<2|g[E+13]>>6)&63)*(1<<te)-ie&65535,Hn=gt+(g[E+13]&63)*(1<<te)-ie&65535,dn=[ne,ue,mt,kt,we,Ce,jt,Un,pe,et,un,Vn,ce,Se,gt,Hn];for(let Wt=0;Wt<16;Wt++)V[Wt]=dn[Wt]&32768?dn[Wt]&32767:~dn[Wt]&65535;E+=14}if(W.pLinear){if(P===null){P=new Uint16Array(65536);for(let ne=0;ne<65536;ne++)if((ne&31744)===31744||ne>32768)P[ne]=0;else{const te=J(ne);P[ne]=te<=0?0:p.DataUtils.toHalfFloat(8*Math.log(te))}}for(let ne=0;ne<16;ne++)V[ne]=P[V[ne]]}for(let ne=0;ne<4;ne++){const te=ae*4+ne;if(!(te>=q))for(let ie=0;ie<4;ie++){const we=de*4+ie;if(we>=ee)continue;const pe=V[ne*4+ie];for(let ce=0;ce<W.ySampling;ce++){const ue=te*W.ySampling+ce;if(!(ue>=O))for(let Ce=0;Ce<W.xSampling;Ce++){const et=we*W.xSampling+Ce;if(et>=R)continue;const Se=ue*R*M+j*R+et*2;B[Se]=pe&255,B[Se+1]=pe>>8&255}}}}}j+=2}return new DataView(B.buffer)}function Ni(l){const g=l.viewer,E={value:l.offset.value},R=new Uint8Array(l.columns*l.lines*(l.inputChannels.length*l.type*2)),O={version:ke(g,E),unknownUncompressedSize:ke(g,E),unknownCompressedSize:ke(g,E),acCompressedSize:ke(g,E),dcCompressedSize:ke(g,E),rleCompressedSize:ke(g,E),rleUncompressedSize:ke(g,E),rleRawSize:ke(g,E),totalAcUncompressedCount:ke(g,E),totalDcUncompressedCount:ke(g,E),acCompression:ke(g,E)};if(O.version<2)throw new Error("THREE.EXRLoader: "+Ze.compression+" version "+O.version+" is unsupported");const U=new Array;let M=hn(g,E)-2;for(;M>0;){const q=kn(g.buffer,E),Q=vt(g,E),oe=Q>>2&3,he=(Q>>4)-1,ae=new Int8Array([he])[0],de=vt(g,E);U.push({name:q,index:ae,type:de,compression:oe}),M-=q.length+3}const H=Ze.channels,B=new Array(l.inputChannels.length);for(let q=0;q<l.inputChannels.length;++q){const Q=B[q]={},oe=H[q];Q.name=oe.name,Q.compression=0,Q.decoded=!1,Q.type=oe.pixelType,Q.pLinear=oe.pLinear,Q.width=l.columns,Q.height=l.lines}const V={idx:new Array(3)};for(let q=0;q<l.inputChannels.length;++q){const Q=B[q],oe=Q.name.lastIndexOf("."),he=oe>=0?Q.name.substring(oe+1):Q.name;for(let ae=0;ae<U.length;++ae){const de=U[ae];he===de.name&&Q.type===de.type&&(Q.compression=de.compression,de.index>=0&&(V.idx[de.index]=q),Q.offset=q)}}let j,X,W;if(O.acCompressedSize>0)switch(O.acCompression){case 0:j=new Uint16Array(O.totalAcUncompressedCount),St(l.array,g,E,O.acCompressedSize,j,O.totalAcUncompressedCount);break;case 1:const q=l.array.slice(E.value,E.value+O.totalAcUncompressedCount),Q=Sn(q);j=new Uint16Array(Q.buffer),E.value+=O.totalAcUncompressedCount;break}if(O.dcCompressedSize>0){const q={array:l.array,offset:E,size:O.dcCompressedSize};X=new Uint16Array(Cs(q).buffer),E.value+=O.dcCompressedSize}if(O.rleRawSize>0){const q=l.array.slice(E.value,E.value+O.rleCompressedSize),Q=Sn(q);W=Rs(Q.buffer),E.value+=O.rleCompressedSize}let $=0;const ee=new Array(B.length);for(let q=0;q<ee.length;++q)ee[q]=new Array;for(let q=0;q<l.lines;++q)for(let Q=0;Q<B.length;++Q)ee[Q].push($),$+=B[Q].width*l.type*2;V.idx[0]!==void 0&&B[V.idx[0]]&&uo(V,ee,B,j,X,R);for(let q=0;q<B.length;++q){const Q=B[q];if(!Q.decoded)switch(Q.compression){case 2:let oe=0,he=0;for(let ae=0;ae<l.lines;++ae){let de=ee[q][oe];for(let ne=0;ne<Q.width;++ne){for(let te=0;te<2*Q.type;++te)R[de++]=W[he+te*Q.width*Q.height];he++}oe++}break;case 1:fo(q,ee,B,j,X,R);break;default:throw new Error("THREE.EXRLoader: unsupported channel compression")}}return new DataView(R.buffer)}function kn(l,g){const E=new Uint8Array(l);let R=0;for(;E[g.value+R]!=0;)R+=1;const O=new TextDecoder().decode(E.slice(g.value,g.value+R));return g.value=g.value+R+1,O}function To(l,g,E){const R=new TextDecoder().decode(new Uint8Array(l).slice(g.value,g.value+E));return g.value=g.value+E,R}function So(l,g){const E=qe(l,g),R=Je(l,g);return[E,R]}function bo(l,g){const E=Je(l,g),R=Je(l,g);return[E,R]}function qe(l,g){const E=l.getInt32(g.value,!0);return g.value=g.value+4,E}function Je(l,g){const E=l.getUint32(g.value,!0);return g.value=g.value+4,E}function ki(l,g){const E=l[g.value];return g.value=g.value+1,E}function vt(l,g){const E=l.getUint8(g.value);return g.value=g.value+1,E}const ke=function(l,g){const E=Number(l.getBigInt64(g.value,!0));return g.value+=8,E};function We(l,g){const E=l.getFloat32(g.value,!0);return g.value+=4,E}function _o(l,g){return p.DataUtils.toHalfFloat(We(l,g))}function J(l){const g=(l&31744)>>10,E=l&1023;return(l>>15?-1:1)*(g?g===31?E?NaN:1/0:Math.pow(2,g-15)*(1+E/1024):6103515625e-14*(E/1024))}function hn(l,g){const E=l.getUint16(g.value,!0);return g.value+=2,E}function xo(l,g){return J(hn(l,g))}function Ao(l,g,E,R){const O=E.value,U=[];for(;E.value<O+R-1;){const M=kn(g,E),H=qe(l,E),B=vt(l,E);E.value+=3;const V=qe(l,E),j=qe(l,E);U.push({name:M,pixelType:H,pLinear:B,xSampling:V,ySampling:j})}return E.value+=1,U}function vo(l,g){const E=We(l,g),R=We(l,g),O=We(l,g),U=We(l,g),M=We(l,g),H=We(l,g),B=We(l,g),V=We(l,g);return{redX:E,redY:R,greenX:O,greenY:U,blueX:M,blueY:H,whiteX:B,whiteY:V}}function Mo(l,g){const E=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],R=vt(l,g);return E[R]}function Ro(l,g){const E=qe(l,g),R=qe(l,g),O=qe(l,g),U=qe(l,g);return{xMin:E,yMin:R,xMax:O,yMax:U}}function Co(l,g){const E=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],R=vt(l,g);return E[R]}function Po(l,g){const E=["ENVMAP_LATLONG","ENVMAP_CUBE"],R=vt(l,g);return E[R]}function Io(l,g){const E=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],R=["ROUND_DOWN","ROUND_UP"],O=Je(l,g),U=Je(l,g),M=vt(l,g);return{xSize:O,ySize:U,levelMode:E[M&15],roundingMode:R[M>>4]}}function Lo(l,g){const E=We(l,g),R=We(l,g);return[E,R]}function Oo(l,g){const E=We(l,g),R=We(l,g),O=We(l,g);return[E,R,O]}function Do(l,g,E,R,O){if(R==="string"||R==="stringvector"||R==="iccProfile")return To(g,E,O);if(R==="chlist")return Ao(l,g,E,O);if(R==="chromaticities")return vo(l,E);if(R==="compression")return Mo(l,E);if(R==="box2i")return Ro(l,E);if(R==="envmap")return Po(l,E);if(R==="tiledesc")return Io(l,E);if(R==="lineOrder")return Co(l,E);if(R==="float")return We(l,E);if(R==="v2f")return Lo(l,E);if(R==="v3f")return Oo(l,E);if(R==="int")return qe(l,E);if(R==="rational")return So(l,E);if(R==="timecode")return bo(l,E);if(R==="preview"||R==="deepImageState"||R==="idmanifest")return E.value+=O,"skipped";E.value+=O}function No(l,g){const E=Math.log2(l);return g=="ROUND_DOWN"?Math.floor(E):Math.ceil(E)}function ko(l,g,E){let R=0;switch(l.levelMode){case"ONE_LEVEL":R=1;break;case"MIPMAP_LEVELS":R=No(Math.max(g,E),l.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return R}function Fi(l,g,E,R){const O=new Array(l);for(let U=0;U<l;U++){const M=1<<U;let H=g/M|0;R=="ROUND_UP"&&H*M<g&&(H+=1);const B=Math.max(H,1);O[U]=(B+E-1)/E|0}return O}function Fo(){const l=this,g=l.offset,E={value:0};for(let R=0;R<l.tileCount;R++){const O=qe(l.viewer,g),U=qe(l.viewer,g);g.value+=8,l.size=Je(l.viewer,g);const M=O*l.blockWidth,H=U*l.blockHeight;l.columns=M+l.blockWidth>l.width?l.width-M:l.blockWidth,l.lines=H+l.blockHeight>l.height?l.height-H:l.blockHeight;const B=l.columns*l.totalBytes,j=l.size<l.lines*B?l.uncompress(l):Nn(l);g.value+=l.size;for(let X=0;X<l.lines;X++){const W=X*l.columns*l.totalBytes;for(let $=0;$<l.inputChannels.length;$++){const ee=Ze.channels[$].name,q=l.channelByteOffsets[ee]*l.columns,Q=l.decodeChannels[ee];if(Q===void 0)continue;E.value=W+q;const oe=(l.height-(1+H+X))*l.outLineWidth;for(let he=0;he<l.columns;he++){const ae=oe+(he+M)*l.outputChannels+Q;l.byteArray[ae]=l.getter(j,E)}}}}}function Bo(){const l=this,g=l.offset,E={value:0};for(let R=0;R<l.height/l.blockHeight;R++){const O=qe(l.viewer,g)-Ze.dataWindow.yMin;l.size=Je(l.viewer,g),l.lines=O+l.blockHeight>l.height?l.height-O:l.blockHeight;const U=l.columns*l.totalBytes,H=l.size<l.lines*U?l.uncompress(l):Nn(l);g.value+=l.size;for(let B=0;B<l.lines;B++){const V=O+B,j=B*U,X=(l.height-1-V)*l.outLineWidth;for(let W=0;W<l.inputChannels.length;W++){const $=Ze.channels[W].name,ee=l.channelByteOffsets[$]*l.columns,q=l.decodeChannels[$];if(q!==void 0){E.value=j+ee;for(let Q=0;Q<l.columns;Q++){const oe=X+Q*l.outputChannels+q;l.byteArray[oe]=l.getter(H,E)}}}}}}function zo(){const l=this,g=l.chunkOffsets,E={value:0};for(let R=0;R<g.length;R++){const O={value:g[R]};O.value+=4;const U=qe(l.viewer,O)-Ze.dataWindow.yMin;l.size=Je(l.viewer,O),l.lines=U+l.blockHeight>l.height?l.height-U:l.blockHeight;const M=l.columns*l.totalBytes,H=l.size<l.lines*M,B=l.offset;l.offset=O;const V=H?l.uncompress(l):Nn(l);l.offset=B;for(let j=0;j<l.lines;j++){const X=U+j,W=j*M,$=(l.height-1-X)*l.outLineWidth;for(let ee=0;ee<l.inputChannels.length;ee++){const q=Ze.channels[ee].name,Q=l.channelByteOffsets[q]*l.columns,oe=l.decodeChannels[q];if(oe!==void 0){E.value=W+Q;for(let he=0;he<l.columns;he++){const ae=$+he*l.outputChannels+oe;l.byteArray[ae]=l.getter(V,E)}}}}}}function Bi(l,g,E,R){if(E===0)return null;const O=l.slice(g,g+E);switch(R){case"NO_COMPRESSION":return new DataView(O.buffer,O.byteOffset,O.byteLength);case"RLE_COMPRESSION":{const U=new Uint8Array(Rs(O.buffer.slice(O.byteOffset,O.byteOffset+O.byteLength))),M=new Uint8Array(U.length);return On(U),Dn(U,M),new DataView(M.buffer)}case"ZIPS_COMPRESSION":{const U=Sn(O),M=new Uint8Array(U.length);return On(U),Dn(U,M),new DataView(M.buffer)}default:throw new Error("THREE.EXRLoader: "+R+" is unsupported for deep data")}}function Uo(){const l=this,g=l.chunkOffsets,E=l.width,R=l.height,O=l.deepChannels,U=Ze.compression,M=l.multiPart,H=l.decodeChannels,B=l.outputChannels,V=l.byteArray instanceof Uint16Array;let j=-1;for(let X=0;X<O.length;X++)if(O[X].name==="A"){j=X;break}for(let X=0;X<g.length;X++){const W={value:g[X]};M&&(W.value+=4);const $=qe(l.viewer,W)-Ze.dataWindow.yMin,ee=ke(l.viewer,W),q=ke(l.viewer,W);ke(l.viewer,W);const Q=Bi(l.array,W.value,ee,U);if(W.value+=ee,Q===null)continue;const oe=new Uint32Array(E);for(let ie=0;ie<E;ie++)oe[ie]=Q.getUint32(ie*4,!0);const he=oe[E-1];if(he===0){W.value+=q;continue}const ae=Bi(l.array,W.value,q,U),de=[];let ne=0;for(let ie=0;ie<O.length;ie++)de.push(ne),ne+=he*O[ie].bytesPerSample;const te=(R-1-$)*l.outLineWidth;for(let ie=0;ie<E;ie++){const we=ie===0?0:oe[ie-1],ce=oe[ie]-we;if(ce===0)continue;const ue=new Float32Array(B);let Ce=0;for(let Se=0;Se<ce;Se++){const mt=we+Se,jt=1-Ce;if(jt<=0)break;let un=1;if(j>=0){const gt=O[j].bytesPerSample,kt=de[j]+mt*gt;un=gt===2?J(ae.getUint16(kt,!0)):ae.getFloat32(kt,!0)}for(let gt=0;gt<O.length;gt++){const kt=O[gt],Un=H[kt.name];if(Un===void 0)continue;const Vn=kt.bytesPerSample,Hn=de[gt]+mt*Vn,dn=Vn===2?J(ae.getUint16(Hn,!0)):ae.getFloat32(Hn,!0);ue[Un]+=dn*jt}Ce+=un*jt}H.A!==void 0&&(ue[H.A]=Ce);const et=te+ie*B;for(let Se=0;Se<B;Se++)l.byteArray[et+Se]=V?p.DataUtils.toHalfFloat(ue[Se]):ue[Se]}}}function zi(l,g,E){const R={};let O=!1;for(;;){const U=kn(g,E);if(U==="")break;O=!0;const M=kn(g,E),H=Je(l,E),B=Do(l,g,E,M,H);B===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${M}'.`):R[U]=B}return O?R:null}function Vo(l,g,E){if(l.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");const R=l.getUint8(4),O=l.getUint8(5),U={singleTile:!!(O&2),longName:!!(O&4),deepFormat:!!(O&8),multiPart:!!(O&16)};E.value=8;const M=[];if(U.multiPart){for(;;){const H=zi(l,g,E);if(H===null)break;H.version=R,H.spec=U,M.push(H)}if(M.length===0)throw new Error("THREE.EXRLoader: No valid part headers found.")}else{const H=zi(l,g,E);H.version=R,H.spec=U,M.push(H)}return M}function Ho(l,g,E,R,O,U){const M={size:0,viewer:g,array:E,offset:R,width:l.dataWindow.xMax-l.dataWindow.xMin+1,height:l.dataWindow.yMax-l.dataWindow.yMin+1,inputChannels:l.channels,channelByteOffsets:{},shouldExpand:!1,yCbCr:!1,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:p.LinearSRGBColorSpace};switch(l.compression){case"NO_COMPRESSION":M.blockHeight=1,M.uncompress=Nn;break;case"RLE_COMPRESSION":M.blockHeight=1,M.uncompress=go;break;case"ZIPS_COMPRESSION":M.blockHeight=1,M.uncompress=Cs;break;case"ZIP_COMPRESSION":M.blockHeight=16,M.uncompress=Cs;break;case"PIZ_COMPRESSION":M.blockHeight=32,M.uncompress=yo;break;case"PXR24_COMPRESSION":M.blockHeight=16,M.uncompress=wo;break;case"B44_COMPRESSION":case"B44A_COMPRESSION":M.blockHeight=32,M.uncompress=Eo;break;case"DWAA_COMPRESSION":M.blockHeight=32,M.uncompress=Ni;break;case"DWAB_COMPRESSION":M.blockHeight=256,M.uncompress=Ni;break;default:throw new Error("THREE.EXRLoader: "+l.compression+" is unsupported")}const H={};for(const W of l.channels)switch(W.name){case"BY":case"RY":case"Y":case"R":case"G":case"B":case"A":H[W.name]=!0,M.type=W.pixelType}let B=!1,V=!1;if(H.Y&&H.RY&&H.BY)M.outputChannels=4,M.yCbCr=!0;else if(H.R&&H.G&&H.B)M.outputChannels=4;else if(H.Y)M.outputChannels=1;else throw new Error("THREE.EXRLoader: file contains unsupported data channels.");switch(M.outputChannels){case 4:U==p.RGBAFormat?(B=!H.A,M.format=p.RGBAFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=4,M.decodeChannels={R:0,G:1,B:2,A:3}):U==p.RGFormat?(M.format=p.RGFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=2,M.decodeChannels={R:0,G:1}):U==p.RedFormat?(M.format=p.RedFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=1,M.decodeChannels={R:0}):V=!0;break;case 1:U==p.RGBAFormat?(B=!0,M.format=p.RGBAFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=4,M.shouldExpand=!0,M.decodeChannels={Y:0}):U==p.RGFormat?(M.format=p.RGFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=2,M.shouldExpand=!0,M.decodeChannels={Y:0}):U==p.RedFormat?(M.format=p.RedFormat,M.colorSpace=p.LinearSRGBColorSpace,M.outputChannels=1,M.decodeChannels={Y:0}):V=!0;break;default:V=!0}if(V)throw new Error("THREE.EXRLoader: invalid output format for specified file.");if(M.yCbCr&&(M.format=p.RGBAFormat,M.outputChannels=4,M.decodeChannels={Y:0,RY:1,BY:2},B=!0),M.type==1)switch(O){case p.FloatType:M.getter=xo;break;case p.HalfFloatType:M.getter=hn;break}else if(M.type==2)switch(O){case p.FloatType:M.getter=We;break;case p.HalfFloatType:M.getter=_o}else throw new Error("THREE.EXRLoader: unsupported pixelType "+M.type+" for "+l.compression+".");M.columns=M.width;const j=M.width*M.height*M.outputChannels;switch(O){case p.FloatType:M.byteArray=new Float32Array(j),B&&M.byteArray.fill(1,0,j);break;case p.HalfFloatType:M.byteArray=new Uint16Array(j),B&&M.byteArray.fill(15360,0,j);break;default:console.error("THREE.EXRLoader: unsupported type: ",O);break}let X=0;for(const W of l.channels)M.decodeChannels[W.name]!==void 0&&(M.channelByteOffsets[W.name]=X),X+=W.pixelType*2;if(M.totalBytes=X,M.outLineWidth=M.width*M.outputChannels,l.spec.deepFormat){M.deepChannels=[];let W=0;for(const $ of l.channels){const ee=$.pixelType===0?4:$.pixelType*2;M.deepChannels.push({name:$.name,pixelType:$.pixelType,bytesPerSample:ee}),W+=ee}M.deepBytesPerSample=W,M.chunkOffsets=l._chunkOffsets,M.multiPart=l.spec.multiPart,M.decode=Uo.bind(M)}else if(l.spec.singleTile){M.blockHeight=l.tiles.ySize,M.blockWidth=l.tiles.xSize;const W=ko(l.tiles,M.width,M.height),$=Fi(W,M.width,l.tiles.xSize,l.tiles.roundingMode),ee=Fi(W,M.height,l.tiles.ySize,l.tiles.roundingMode);M.tileCount=$[0]*ee[0];for(let q=0;q<W;q++)for(let Q=0;Q<ee[q];Q++)for(let oe=0;oe<$[q];oe++)ke(g,R);M.decode=Fo.bind(M)}else if(l.spec.multiPart)M.blockWidth=M.width,M.chunkOffsets=l._chunkOffsets,M.decode=zo.bind(M);else{M.blockWidth=M.width;const W=Math.ceil(M.height/M.blockHeight);for(let $=0;$<W;$++)ke(g,R);M.decode=Bo.bind(M)}return M}const Fn={value:0},Bn=new DataView(e),Go=new Uint8Array(e),zn=Vo(Bn,e,Fn),Ui=Math.max(0,Math.min(this.part,zn.length-1)),Ze=zn[Ui];if(Ze.spec.multiPart||Ze.spec.deepFormat)for(let l=0;l<zn.length;l++){const g=zn[l].chunkCount;if(l===Ui){Ze._chunkOffsets=[];for(let E=0;E<g;E++)Ze._chunkOffsets.push(ke(Bn,Fn))}else for(let E=0;E<g;E++)ke(Bn,Fn)}const tt=Ho(Ze,Bn,Go,Fn,this.type,this.outputFormat);if(tt.decode(),tt.shouldExpand){const l=tt.byteArray;if(this.outputFormat==p.RGBAFormat)for(let g=0;g<l.length;g+=4)l[g+2]=l[g+1]=l[g];else if(this.outputFormat==p.RGFormat)for(let g=0;g<l.length;g+=2)l[g+1]=l[g]}if(tt.yCbCr){const l=tt.byteArray,g=tt.width*tt.height;if(this.type===p.HalfFloatType)for(let E=0;E<g;E++){const R=E*4,O=J(l[R]),U=J(l[R+1]),M=J(l[R+2]),H=(1+U)*O,B=(1+M)*O,V=(O-H*.2126-B*.0722)/.7152;l[R]=p.DataUtils.toHalfFloat(Math.max(0,H)),l[R+1]=p.DataUtils.toHalfFloat(Math.max(0,V)),l[R+2]=p.DataUtils.toHalfFloat(Math.max(0,B))}else for(let E=0;E<g;E++){const R=E*4,O=l[R],U=l[R+1],M=l[R+2],H=(1+U)*O,B=(1+M)*O;l[R]=Math.max(0,H),l[R+1]=Math.max(0,(O-H*.2126-B*.0722)/.7152),l[R+2]=Math.max(0,B)}}return{header:Ze,width:tt.width,height:tt.height,data:tt.byteArray,format:tt.format,colorSpace:tt.colorSpace,type:this.type,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!1}}setDataType(e){return this.type=e,this}setOutputFormat(e){return this.outputFormat=e,this}setPart(e){return this.part=e,this}}class Jl extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType}parse(e){const o=function(C,D){switch(C){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(D||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(D||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(D||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(D||""))}},h=function(C,D,P){D=D||1024;let k=C.pos,G=-1,z=0,Y="",re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(k,k+128)));for(;0>(G=re.indexOf(`
26
- `))&&z<D&&k<C.byteLength;)Y+=re,z+=re.length,k+=128,re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(k,k+128)));return-1<G?(C.pos+=z+G+1,Y+re.slice(0,G)):!1},f=function(C){const D=/^#\?(\S+)/,P=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,F=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,k=/^\s*FORMAT=(\S+)\s*$/,G=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,z={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let Y,re;for((C.pos>=C.byteLength||!(Y=h(C)))&&o(1,"no header found"),(re=Y.match(D))||o(3,"bad initial token"),z.valid|=1,z.programtype=re[1],z.string+=Y+`
27
- `;Y=h(C),Y!==!1;){if(z.string+=Y+`
28
- `,Y.charAt(0)==="#"){z.comments+=Y+`
29
- `;continue}if((re=Y.match(P))&&(z.gamma=parseFloat(re[1])),(re=Y.match(F))&&(z.exposure=parseFloat(re[1])),(re=Y.match(k))&&(z.valid|=2,z.format=re[1]),(re=Y.match(G))&&(z.valid|=4,z.height=parseInt(re[1],10),z.width=parseInt(re[2],10)),z.valid&2&&z.valid&4)break}return z.valid&2||o(3,"missing format specifier"),z.valid&4||o(3,"missing image size specifier"),z},m=function(C,D,P){const F=D;if(F<8||F>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);F!==(C[2]<<8|C[3])&&o(3,"wrong scanline width");const k=new Uint8Array(4*D*P);k.length||o(4,"unable to allocate buffer space");let G=0,z=0;const Y=4*F,re=new Uint8Array(4),Ne=new Uint8Array(Y);let ot=P;for(;ot>0&&z<C.byteLength;){z+4>C.byteLength&&o(1),re[0]=C[z++],re[1]=C[z++],re[2]=C[z++],re[3]=C[z++],(re[0]!=2||re[1]!=2||(re[2]<<8|re[3])!=F)&&o(3,"bad rgbe scanline format");let Re=0,ze;for(;Re<Y&&z<C.byteLength;){ze=C[z++];const ve=ze>128;if(ve&&(ze-=128),(ze===0||Re+ze>Y)&&o(3,"bad scanline data"),ve){const ye=C[z++];for(let pt=0;pt<ze;pt++)Ne[Re++]=ye}else Ne.set(C.subarray(z,z+ze),Re),Re+=ze,z+=ze}const Ge=F;for(let ve=0;ve<Ge;ve++){let ye=0;k[G]=Ne[ve+ye],ye+=F,k[G+1]=Ne[ve+ye],ye+=F,k[G+2]=Ne[ve+ye],ye+=F,k[G+3]=Ne[ve+ye],G+=4}ot--}return k},w=function(C,D,P,F){const k=C[D+3],G=Math.pow(2,k-128)/255;P[F+0]=C[D+0]*G,P[F+1]=C[D+1]*G,P[F+2]=C[D+2]*G,P[F+3]=1},x=function(C,D,P,F){const k=C[D+3],G=Math.pow(2,k-128)/255;P[F+0]=p.DataUtils.toHalfFloat(Math.min(C[D+0]*G,65504)),P[F+1]=p.DataUtils.toHalfFloat(Math.min(C[D+1]*G,65504)),P[F+2]=p.DataUtils.toHalfFloat(Math.min(C[D+2]*G,65504)),P[F+3]=p.DataUtils.toHalfFloat(1)},b=new Uint8Array(e);b.pos=0;const v=f(b),T=v.width,S=v.height,_=m(b.subarray(b.pos),T,S);let A,L,I;switch(this.type){case p.FloatType:I=_.length/4;const C=new Float32Array(I*4);for(let P=0;P<I;P++)w(_,P*4,C,P*4);A=C,L=p.FloatType;break;case p.HalfFloatType:I=_.length/4;const D=new Uint16Array(I*4);for(let P=0;P<I;P++)x(_,P*4,D,P*4);A=D,L=p.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:T,height:S,data:A,header:v.string,gamma:v.gamma,exposure:v.exposure,type:L,colorSpace:p.LinearSRGBColorSpace,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}class eh extends Jl{constructor(e){console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."),super(e)}}class th extends p.Scene{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;const e=new p.BoxGeometry;e.deleteAttribute("uv");const t=new p.MeshStandardMaterial({side:p.BackSide}),n=new p.MeshStandardMaterial,s=new p.PointLight(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const r=new p.Mesh(e,t);r.position.set(-.757,13.219,.717),r.scale.set(31.713,28.305,28.591),this.add(r);const o=new p.InstancedMesh(e,n,6),a=new p.Object3D;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),o.setMatrixAt(0,a.matrix),a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),a.updateMatrix(),o.setMatrixAt(1,a.matrix),a.position.set(6.167,.857,7.803),a.rotation.set(0,.561,0),a.scale.set(3.927,6.285,3.687),a.updateMatrix(),o.setMatrixAt(2,a.matrix),a.position.set(-2.017,.018,6.124),a.rotation.set(0,.333,0),a.scale.set(2.002,4.566,2.064),a.updateMatrix(),o.setMatrixAt(3,a.matrix),a.position.set(2.291,-.756,-2.621),a.rotation.set(0,-.286,0),a.scale.set(1.546,1.552,1.496),a.updateMatrix(),o.setMatrixAt(4,a.matrix),a.position.set(-2.193,-.369,-5.547),a.rotation.set(0,.516,0),a.scale.set(3.875,3.487,2.986),a.updateMatrix(),o.setMatrixAt(5,a.matrix),this.add(o);const c=new p.Mesh(e,tn(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const u=new p.Mesh(e,tn(50));u.position.set(-16.109,18.021,-8.207),u.scale.set(.1,2.425,2.751),this.add(u);const d=new p.Mesh(e,tn(17));d.position.set(14.904,12.198,-1.832),d.scale.set(.15,4.265,6.331),this.add(d);const h=new p.Mesh(e,tn(43));h.position.set(-.462,8.89,14.52),h.scale.set(4.38,5.441,.088),this.add(h);const f=new p.Mesh(e,tn(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,.1),this.add(f);const m=new p.Mesh(e,tn(100));m.position.set(0,20,0),m.scale.set(1,.1,1),this.add(m)}dispose(){const e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function tn(i){return new p.MeshLambertMaterial({color:0,emissive:16777215,emissiveIntensity:i})}class nh{constructor(){this.pmremGenerator=null,this.threeRenderer=null,this.loadedTextures=new Map,this.renderTargets=[],this.studioPmremTexture=null,this.studioCubeTarget=null,this.disposed=!1}async initialize(e){var t;try{const n=e.renderer;let s=n.renderer||((t=n.getThreeRenderer)==null?void 0:t.call(n));if(!s&&n.getDomElement){const r=n.getDomElement();if(r&&"parentElement"in r&&r.parentElement){const o=r.parentElement.renderer;o instanceof y.WebGLRenderer&&(s=o)}}return s?(this.threeRenderer=s,this.pmremGenerator=new y.PMREMGenerator(s),this.pmremGenerator.compileEquirectangularShader(),N.ok(void 0)):N.err(new Z("Could not access Three.js renderer",K.INITIALIZATION_FAILED))}catch(n){return N.err(new Z("Failed to initialize environment service",K.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return N.ok(new bn(n));const s=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let r;switch(s){case"hdr":r=new eh;break;case"exr":r=new Ql;break;case"jpg":case"jpeg":case"png":r=new y.TextureLoader;break;default:return N.err(new Z(`Unsupported environment map format: ${s}`,K.UNSUPPORTED_FORMAT,{url:e,extension:s}))}const o=await new Promise((a,c)=>{r.load(e,u=>{a(u)},void 0,u=>c(u))});if(this.disposed)return o.dispose(),N.err(new Z("Environment service was disposed during the load",K.INVALID_STATE,{url:e}));if(this.pmremGenerator){o.mapping=y.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(o);this.renderTargets.push(a);const c=a.texture;return this.loadedTextures.set(e,c),this.loadedTextures.set(e+"_original",o),N.ok(new bn(c))}return this.loadedTextures.set(e,o),N.ok(new bn(o))}catch(n){return N.err(new Z("Failed to load environment map",K.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{const s=ft(e);if(!s)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const r=yl(t);if(!r)return N.err(new Z("Texture must be ThreeTextureAdapter",K.INVALID_PARAMETER));if(s.environment=r,n&&(n.backgroundBlurriness!==void 0&&(s.backgroundBlurriness=n.backgroundBlurriness),n.backgroundIntensity!==void 0&&(s.backgroundIntensity=n.backgroundIntensity),n.environmentIntensity!==void 0&&(s.environmentIntensity=n.environmentIntensity)),r.mapping===y.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,u])=>c.endsWith("_original")&&u.mapping===y.EquirectangularReflectionMapping);a?s.__originalEnvironmentTexture=a[1]:r===this.studioPmremTexture&&this.studioCubeTarget&&(s.__originalEnvironmentTexture=this.studioCubeTarget.texture)}else r.mapping===y.EquirectangularReflectionMapping&&(s.__originalEnvironmentTexture=r);if((n==null?void 0:n.setBackground)??!0)if(r.mapping===y.EquirectangularReflectionMapping)s.background=r;else if(r.mapping===y.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,u])=>c.endsWith("_original")&&u.mapping===y.EquirectangularReflectionMapping);a?s.background=a[1]:s.background=r}else s.background=r;return N.ok(void 0)}catch(s){return N.err(new Z("Failed to apply environment to scene",K.SCENE_OPERATION_FAILED,{originalError:s}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new bn(t):null}async setBackgroundImage(e,t){try{const n=ft(e);if(!n)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const s=await this.loadBackgroundTexture(t);s.colorSpace=y.SRGBColorSpace,s.needsUpdate=!0;const r=n.background;return n.background=s,r instanceof y.Texture&&r!==n.environment&&r.dispose(),N.ok(void 0)}catch(n){return N.err(new Z("Failed to set background image",K.TEXTURE_LOAD_FAILED,{originalError:n}))}}loadBackgroundTexture(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement){const s=new y.Texture(e);return s.needsUpdate=!0,Promise.resolve(s)}const t=typeof File<"u"&&e instanceof File?URL.createObjectURL(e):null,n=t??e;return new Promise((s,r)=>{new y.TextureLoader().load(n,o=>{t&&URL.revokeObjectURL(t),s(o)},void 0,o=>{t&&URL.revokeObjectURL(t),r(o)})})}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return N.err(new Z("Environment service not initialized",K.INITIALIZATION_FAILED));const t=new th,n=this.pmremGenerator.fromScene(t);this.renderTargets.push(n);const s=n.texture;return this.captureStudioCubeOriginal(t,s),t.dispose(),N.ok(new bn(s))}catch(t){return N.err(new Z("Failed to create studio environment",K.TEXTURE_LOAD_FAILED,{originalError:t}))}}captureStudioCubeOriginal(e,t){var n;if(this.threeRenderer)try{const s=new y.WebGLCubeRenderTarget(256,{type:y.HalfFloatType}),r=new y.CubeCamera(.1,100,s),o=this.threeRenderer.toneMapping;this.threeRenderer.toneMapping=y.NoToneMapping;try{r.update(this.threeRenderer,e)}finally{this.threeRenderer.toneMapping=o}(n=this.studioCubeTarget)==null||n.dispose(),this.studioCubeTarget=s,this.studioPmremTexture=t}catch(s){console.warn("Failed to capture the studio environment for path tracing:",s)}}dispose(){var e;this.disposed=!0,this.loadedTextures.forEach(t=>t.dispose()),this.loadedTextures.clear(),this.renderTargets.forEach(t=>t.dispose()),this.renderTargets=[],(e=this.studioCubeTarget)==null||e.dispose(),this.studioCubeTarget=null,this.studioPmremTexture=null,this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null),this.threeRenderer=null}}class bn{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}}class sh{constructor(e){this.object=e,this.boundingBox=new y.Box3().setFromObject(this.object)}alignToFloor(){const e=this.calculateFloorOffset();this.applyOffset(e)}calculateFloorOffset(){const e=this.boundingBox.min.y,t=this.boundingBox.max.y-e,n=new y.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class ih{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof y.Object3D&&(t=e),t?(new sh(t).alignToFloor(),N.ok(void 0)):N.err(new Z("Could not get Three.js object for floor alignment",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to align object to floor",K.OPERATION_FAILED,{originalError:t}))}}}const Tr={touch:10,default:5};class rh{constructor(){this.raycaster=new y.Raycaster,this.activePointers=new Set,this.options=null,this.pending=null,this.detach=null}initialize(e){this.dispose(),this.options=e;const{canvas:t}=e,n=o=>{this.activePointers.add(o.pointerId);try{t.setPointerCapture(o.pointerId)}catch{}if(this.activePointers.size>1||o.button!==0){this.pending=null;return}this.pending={pointerId:o.pointerId,x:o.clientX,y:o.clientY,threshold:o.pointerType==="touch"?Tr.touch:Tr.default}},s=o=>{this.activePointers.delete(o.pointerId);const a=this.pending;!a||a.pointerId!==o.pointerId||(this.pending=null,Math.hypot(o.clientX-a.x,o.clientY-a.y)>a.threshold)||this.pick(o.clientX,o.clientY)},r=o=>{this.activePointers.delete(o.pointerId),this.pending=null};t.addEventListener("pointerdown",n),t.addEventListener("pointerup",s),t.addEventListener("pointercancel",r),this.detach=()=>{t.removeEventListener("pointerdown",n),t.removeEventListener("pointerup",s),t.removeEventListener("pointercancel",r)}}pick(e,t){if(!this.options)return;const{canvas:n,camera:s,getPickRoot:r,onPick:o}=this.options,a=r(),c=Tt(a),u=Pn(s);if(!c||!u){o(null);return}const d=n.getBoundingClientRect();if(d.width===0||d.height===0){o(null);return}const h=new y.Vector2((e-d.left)/d.width*2-1,-((t-d.top)/d.height)*2+1);(this.options.bvh??!0)&&Fr(c),this.raycaster.setFromCamera(h,u),this.raycaster.firstHitOnly=!0;const f=this.raycaster.intersectObject(c,!0)[0];if(!f){o(null);return}o({object:new Ke(f.object),point:{x:f.point.x,y:f.point.y,z:f.point.z}})}dispose(){var e;(e=this.detach)==null||e.call(this),this.detach=null,this.options=null,this.pending=null,this.activePointers.clear()}}const oh=.001,Sr={visible:!1};class ah{constructor(e){this.sources=e,this.anchor=new y.Vector3,this.projected=new y.Vector3,this.cameraPosition=new y.Vector3,this.toAnchor=new y.Vector3,this.raycaster=new y.Raycaster,this.lastCameraMatrix=new y.Matrix4,this.lastWidth=-1,this.lastHeight=-1,this.hasProjected=!1}invalidate(){this.hasProjected=!1}project(e,t){const n=Pn(this.sources.camera),s=this.sources.getCanvas();if(!n||!s)return null;const r=s.clientWidth||s.width,o=s.clientHeight||s.height;return this.hasProjected&&r===this.lastWidth&&o===this.lastHeight&&this.lastCameraMatrix.equals(n.matrixWorld)?null:(this.lastCameraMatrix.copy(n.matrixWorld),this.lastWidth=r,this.lastHeight=o,this.hasProjected=!0,this.anchor.set(e.x,e.y,e.z),n.getWorldPosition(this.cameraPosition),this.projected.copy(this.anchor).applyMatrix4(n.matrixWorldInverse),this.projected.z>=0||t&&this.isOccluded(n)?Sr:(this.projected.copy(this.anchor).project(n),{visible:!0,left:(this.projected.x+1)/2*r,top:(1-this.projected.y)/2*o}))}isOccluded(e){const t=Tt(this.sources.getModel());if(!t)return!1;this.toAnchor.copy(this.anchor).sub(this.cameraPosition);const n=this.toAnchor.length();this.raycaster.set(this.cameraPosition,this.toAnchor.normalize()),this.raycaster.camera=e,this.raycaster.firstHitOnly=!0;const s=this.raycaster.intersectObject(t,!0)[0];return!!(s&&s.distance<n-oh)}}class ch{createProjector(e){return new ah(e)}}class lh{constructor(){this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1,this.speed=1}attach(e){this.detach();const t=Tt(e);if(!t)return;const n=hh(t);n&&(this.clips=n.animations,this.mixer=new y.AnimationMixer(n),this.mixer.timeScale=this.speed)}getClipNames(){return this.clips.map(e=>e.name)}play(e){if(e!==void 0){if(this.clips.length===0)return N.err(new Z(`Cannot play animation clip '${e}': no animation clips are attached`,K.INVALID_STATE));if(!this.clips.some(s=>s.name===e)){const s=this.clips.map(r=>r.name);return N.err(new Z(`Unknown animation clip '${e}'. Available clips: ${s.join(", ")}`,K.INVALID_PARAMETER))}}if(!this.mixer)return N.ok(void 0);if(!this.playing&&this.activeActions.length>0&&e===void 0)return this.playing=!0,N.ok(void 0);const t=e?this.clips.filter(s=>s.name===e):this.clips;if(t.length===0)return N.ok(void 0);const n=this.mixer;return n.stopAllAction(),this.activeActions=t.map(s=>{const r=n.clipAction(s);return r.play(),r}),this.playing=!0,N.ok(void 0)}pause(){this.playing=!1}isPlaying(){return this.playing}setSpeed(e){this.speed=e,this.mixer&&(this.mixer.timeScale=e)}update(e){this.playing&&this.mixer&&this.mixer.update(e)}detach(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot())),this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1}}function hh(i){let e=null;return i.traverse(t=>{var n;!e&&(((n=t.animations)==null?void 0:n.length)??0)>0&&(e=t)}),e}var Rn=(i=>(i.MapControls="MapControls",i.OrbitControls="OrbitControls",i))(Rn||{});class uh{static convertRendererOptions(e){const t={antialias:e.antialias,alpha:e.alpha,premultipliedAlpha:e.premultipliedAlpha,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference,pixelRatio:e.pixelRatio};(e.shadowMapEnabled!==void 0||e.shadowMapType!==void 0)&&(t.shadowMap={enabled:e.shadowMapEnabled??!0,type:this.convertShadowMapType(e.shadowMapType)}),(e.toneMapping!==void 0||e.toneMappingExposure!==void 0)&&(t.toneMapping={type:this.convertToneMappingType(e.toneMapping),exposure:e.toneMappingExposure??1});const n=e.bloom,s=e.vignette,r=e.filmGrain;return(n||s||r)&&(t.postProcessing={bloom:n??!1,vignette:s??!1,filmGrain:r??!1}),t}static convertShadowMapType(e){if(typeof e=="number"){if(e===y.BasicShadowMap)return"basic";if(e===y.PCFShadowMap)return"pcf";if(e===y.PCFSoftShadowMap)return"pcfsoft";if(e===y.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===y.NoToneMapping)return"none";if(e===y.LinearToneMapping)return"linear";if(e===y.ReinhardToneMapping)return"reinhard";if(e===y.CineonToneMapping)return"cineon";if(e===y.ACESFilmicToneMapping)return"aces";if(e===y.AgXToneMapping)return"agx";if(e===y.NeutralToneMapping)return"neutral"}return typeof e=="string"?e:"neutral"}}class dh{static createViewer(e,t){var v;Mr(t.units);const n=new mc(e),s=new ui,r=this.createCamera(t),o=this.createControls(r.getThreeCamera(),e,t),a=new fh().createDefaultLoader({renderer:n.getThreeRenderer()??void 0,bvh:(v=t.selection)==null?void 0:v.bvh,...t.loaders}),c=new Nl,u=new nh,d=new kl,h=new ih,f=new rh,m=new ch,w=new lh,x=uh.convertRendererOptions(t.renderer||{});x.preserveDrawingBuffer=!0;const b={renderer:n,scene:s,camera:r,controls:o,modelLoader:a,options:t,rendererOptions:x,sceneSetupService:c,environmentService:u,pathTracingService:d,floorAlignmentService:h,selectionService:f,anchorProjectionService:m,animationService:w};return new aa(b)}static createCamera(e){const n=e.camera||{},s=n.fov||n.cameraFov||30,r=n.near||n.cameraNear||.1,o=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,u=Ai.create(s,1,r,o);return a&&u.position.set(a[0],a[1],a[2]),c&&u.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),u}static createControls(e,t,n){const s=n.controls||{},r=s.type||Rn.OrbitControls;let o;r===Rn.MapControls?o=new gl(e,t):o=new ml(e,t),o.enabled=s.enabled??!0,o.enableDamping=s.enableDamping??!0,o.dampingFactor=s.dampingFactor??.25,o.enableZoom=s.enableZoom??!0,o.enableRotate=s.enableRotate??!0,o.enablePan=s.enablePan??!0,o.autoRotate=s.autoRotate??!1,s.autoRotateSpeed!==void 0&&(o.autoRotateSpeed=s.autoRotateSpeed),s.minDistance!==void 0&&(o.minDistance=s.minDistance),s.maxDistance!==void 0&&(o.maxDistance=s.maxDistance),s.minPolarAngle!==void 0&&(o.minPolarAngle=s.minPolarAngle),s.maxPolarAngle!==void 0&&(o.maxPolarAngle=s.maxPolarAngle);const c=n.camera||{},u=c.target||c.cameraTarget;return u&&o.target&&(o.target.set(u[0],u[1],u[2]),o.update()),o}}class fh extends gr{createDefaultLoader(e={}){return gr.createLoader("model.glb",e)}}const ph=["toneMappingExposure"],mh=["environmentIntensity"],gh=["autoRotate","autoRotateSpeed"],yh=["enabled"];function Jr(i){var t,n,s,r,o,a,c,u,d,h,f;const e={backgroundColor:i.backgroundColor,backgroundColorEdge:i.backgroundColorEdge};return((t=i.renderer)==null?void 0:t.toneMappingExposure)!==void 0&&(e.renderer={toneMappingExposure:i.renderer.toneMappingExposure}),((n=i.environment)==null?void 0:n.environmentIntensity)!==void 0&&(e.environment={environmentIntensity:i.environment.environmentIntensity}),(((s=i.controls)==null?void 0:s.autoRotate)!==void 0||((r=i.controls)==null?void 0:r.autoRotateSpeed)!==void 0)&&(e.controls={autoRotate:(o=i.controls)==null?void 0:o.autoRotate,autoRotateSpeed:(a=i.controls)==null?void 0:a.autoRotateSpeed}),(((c=i.animations)==null?void 0:c.autoplay)!==void 0||((u=i.animations)==null?void 0:u.speed)!==void 0)&&(e.animations={autoplay:(d=i.animations)==null?void 0:d.autoplay,speed:(h=i.animations)==null?void 0:h.speed}),((f=i.pathTracing)==null?void 0:f.enabled)!==void 0&&(e.pathTracing={enabled:i.pathTracing.enabled}),e}const ws={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!1,units:"meters",floorAlignment:!0,pathTracing:{enabled:!1,maxSamples:1024,bounces:16,transmissiveBounces:4,renderScale:.8,lowResScale:.25,dynamicLowRes:!0},camera:{position:[60,60,60],target:[0,0,0],fov:30,near:.1,far:1e5,autoFitToObject:!0},environment:{backgroundIntensity:1,environmentIntensity:.5},lighting:{ambientLight:{color:"#4a4a4a",intensity:.5},hemisphereLight:{skyColor:"#fff6ec",groundColor:"#3c3630",intensity:.45},directionalLight:{color:"#fff8f2",intensity:1.9,position:[40,90,40],castShadow:!0,shadow:{mapSize:{width:4096,height:4096},camera:{near:.5,far:200,left:-50,right:50,top:50,bottom:-50},bias:-1e-4,radius:14}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:typeof window<"u"?window.devicePixelRatio:1,shadowMapType:1,toneMapping:7,toneMappingExposure:1.15},controls:{type:Rn.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0,maxPolarAngle:Math.PI/2},helpers:{grid:{type:"shadow_floor",size:20,divisions:20,colorGrid:"#a8a8a2",opacity:.5,styleOptions:{tileSize:.1173,metalness:0,roughness:.9,transmission:0}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}},Ri={studio:{backgroundColor:"#f0f0f7",renderer:{toneMappingExposure:1.15},environment:{environmentIntensity:.5}},product:{backgroundColor:"#ffffff",renderer:{toneMappingExposure:1.2},environment:{environmentIntensity:.55}},neutral:{backgroundColor:"#d9d9de",renderer:{toneMappingExposure:1.1},environment:{environmentIntensity:.45}},dark:{backgroundColor:"#242430",backgroundColorEdge:"#050507",renderer:{toneMappingExposure:1.3},environment:{environmentIntensity:.42}},outdoor:{backgroundColor:"#bcd4e6",renderer:{toneMappingExposure:1.2},environment:{environmentIntensity:.6}}};function eo(i){return i?Ri[i]:{}}function Ei(i,e){return on(on(i,eo(e.preset)),e)}const ls=(i,...e)=>{if(!i)return;const t={...i};for(const n of e)delete t[n];return Object.keys(t).length>0?t:void 0};function wh(i){const e=se.useMemo(()=>{var s;return JSON.stringify({pathTracing:ls(i.pathTracing,...yh),staticScene:i.staticScene,renderer:ls(i.renderer,...ph),camera:i.camera,controls:ls(i.controls,...gh),environment:ls(i.environment,...mh),lighting:i.lighting,helpers:i.helpers,rendering:i.rendering,replaceWithScreenshotOnComplete:i.replaceWithScreenshotOnComplete,loaders:i.loaders,units:i.units??"meters",selectionBvh:((s=i.selection)==null?void 0:s.bvh)!==!1})},[i.pathTracing,i.staticScene,i.renderer,i.camera,i.controls,i.environment,i.lighting,i.helpers,i.rendering,i.replaceWithScreenshotOnComplete,i.loaders,i.units,i.selection]),t=se.useMemo(()=>{const s=Ei(ws,i);return JSON.stringify(Jr(s))},[i.preset,i.backgroundColor,i.backgroundColorEdge,i.renderer,i.environment,i.controls,i.animations,i.pathTracing]);return{options:se.useMemo(()=>i,[e,t]),structuralKey:e,runtimeKey:t}}const Eh="200px";function Th(i,e){const[t,n]=se.useState(!e);return se.useEffect(()=>{if(t)return;if(!e){n(!0);return}const s=i.current;if(!s||typeof IntersectionObserver>"u"){n(!0);return}const r=new IntersectionObserver(o=>{o.some(a=>a.isIntersecting)&&n(!0)},{rootMargin:Eh});return r.observe(s),()=>r.disconnect()},[i,e,t]),t}function Sh(i,e){const t=se.useRef(null),n=se.useRef({width:0,height:0}),[s,r]=se.useState(!1),[o,a]=se.useState(null),{options:c,structuralKey:u,runtimeKey:d}=wh(e),h=Th(i,(e.loading??"eager")==="lazy");return se.useEffect(()=>{if(!h||!i.current||t.current)return;a(null);const f=Ei(ws,c);let m;try{m=dh.createViewer(i.current,f)}catch(x){console.error("Failed to create viewer:",x),a(x instanceof Error?x:new Error(String(x)));return}t.current=m,n.current={width:0,height:0};let w=!1;return m.initialize().then(x=>{w||(x.ok?r(!0):(console.error("Failed to initialize viewer:",x.error),a(x.error)))}),()=>{w=!0,m.dispose(),t.current=null,r(!1)}},[i,u,h]),se.useEffect(()=>{if(!t.current||!s)return;const f=Ei(ws,c);t.current.updateOptions(Jr(f))},[d,s]),se.useEffect(()=>{if(!t.current||!i.current)return;let f=null;const m=b=>{if(i.current&&t.current){const v=i.current.parentElement||i.current;let{clientWidth:T,clientHeight:S}=v;if(b&&b[0]){const{width:_,height:A}=b[0].contentRect;T=Math.floor(_),S=Math.floor(A)}if(n.current.width===T&&n.current.height===S)return;f!==null&&cancelAnimationFrame(f),f=requestAnimationFrame(()=>{t.current&&i.current&&(t.current.resize(T,S),n.current={width:T,height:S})})}};m();const w=()=>m();window.addEventListener("resize",w);let x=null;return typeof ResizeObserver<"u"&&i.current.parentElement&&(x=new ResizeObserver(m),x.observe(i.current.parentElement)),()=>{window.removeEventListener("resize",w),x==null||x.disconnect(),f!==null&&cancelAnimationFrame(f)}},[s,i]),{viewer:t.current,isInitialized:s,initError:o}}function to(i,e){const t=se.useRef(e);t.current=e,se.useEffect(()=>{if(!i)return;const n=i.getEvents(),s=[],r=o=>{const a=c=>{var u,d;(d=(u=t.current)[o])==null||d.call(u,c)};return n.on(o,a),()=>n.off(o,a)};return Object.keys(e).forEach(o=>{e[o]&&s.push(r(o))}),()=>{s.forEach(o=>o())}},[i])}function bh(i,e){const[t,n]=se.useState(null),s=se.useRef(new Set);se.useEffect(()=>{if(i!==void 0&&s.current.has(i)){s.current.delete(i),n(c=>c===i?null:c);return}s.current.clear(),n(null)},[i]);const r=!!(e!=null&&e.presets);se.useEffect(()=>{r||(s.current.clear(),n(null))},[r]);const o=e==null?void 0:e.onPresetChange,a=se.useCallback(c=>{n(c),o&&(s.current.add(c),o(c))},[o]);return{activePreset:t??i,pickerEnabled:r,selectPreset:a}}function _h(i,e,t,n,s){return se.useMemo(()=>{var u,d,h;const r=i.preset!==e,o=t===!0&&((u=i.pathTracing)==null?void 0:u.enabled)===void 0,a=n!==void 0&&((d=i.controls)==null?void 0:d.autoRotate)===void 0,c=s!==void 0&&((h=i.animations)==null?void 0:h.autoplay)===void 0;return!r&&!o&&!a&&!c?i:{...i,...r?{preset:e}:{},...o?{pathTracing:{...i.pathTracing,enabled:!0}}:{},...a?{controls:{...i.controls,autoRotate:n}}:{},...c?{animations:{...i.animations,autoplay:s}}:{}}},[i,e,t,n,s])}function xh(i,e,t){const n=se.useMemo(()=>{if(typeof t=="string")return t;if(t)return`object-${t.uuid||"no-uuid"}`},[t]),[s,r]=se.useState(()=>({status:t?"loading":"idle"}));return se.useEffect(()=>{r({status:t?"loading":"idle"})},[n]),se.useEffect(()=>{if(!i||!e||!t)return;let o=!0;const a=typeof t=="string"?t:new Ke(t);return i.loadModel(a).then(c=>{o&&(c.ok?r({status:"loaded"}):(r({status:"error",error:c.error.message}),console.error("Failed to load model:",c.error)))}),()=>{o=!1}},[i,e,n]),s}class qs{static toThreeObject(e){const t=Tt(e);if(t)return t;const n=new y.Object3D;return n.position.set(e.position.x,e.position.y,e.position.z),n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),n.scale.set(e.scale.x,e.scale.y,e.scale.z),n}static toThreeCamera(e){return Pn(e)??new y.PerspectiveCamera}static toThreeControls(e){return Mi(e)??e}static convertModelLoaded(e){return{model:this.toThreeObject(e.model),loadTime:e.loadTime}}static convertControlsChange(e){return{type:e.type,camera:e.camera?this.toThreeCamera(e.camera):void 0,controls:e.controls?this.toThreeControls(e.controls):void 0}}static convertObjectSelected(e){return{object:this.toThreeObject(e.object),point:e.point}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}function Ah(i){const e=se.useRef(new Ts),t=se.useMemo(()=>({"model:loading":n=>e.current.emit("model:loading",n),"model:progress":n=>e.current.emit("model:progress",n),"model:loaded":n=>e.current.emit("model:loaded",qs.convertModelLoaded(n)),"model:error":n=>e.current.emit("model:error",n),"render:complete":n=>e.current.emit("render:complete",n),"controls:change":n=>e.current.emit("controls:change",qs.convertControlsChange(n)),"object:selected":n=>e.current.emit("object:selected",qs.convertObjectSelected(n)),error:n=>e.current.emit("error",n)}),[]);return to(i,t),e.current}function vh(i,e,t){const n=se.useRef(t);n.current=t;const s=se.useMemo(()=>({"model:loaded":()=>{var o,a;return(a=(o=n.current).onLoad)==null?void 0:a.call(o)},"model:progress":o=>{var a,c;return(c=(a=n.current).onProgress)==null?void 0:c.call(a,Math.min(1,o.loaded/o.total))},"model:error":o=>{var a,c;return(c=(a=n.current).onError)==null?void 0:c.call(a,o.error)}}),[]);to(i,s);const r=se.useRef(null);se.useEffect(()=>{if(!e){r.current=null;return}const o=n.current.onError;o&&r.current!==e&&(r.current=e,o(e))})}const no=se.createContext(null);function Mh({viewer:i,canvasRef:e,children:t}){const n=se.useMemo(()=>({viewer:i,canvasRef:e}),[i,e]);return me.jsx(no.Provider,{value:n,children:t})}function so(){const i=se.useContext(no);if(!i)throw new Error("useViewerContext must be used within ViewerProvider");return i}function Rh(){const{canvasRef:i}=so();return me.jsx("canvas",{ref:i,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var i=document.createElement("style");i.appendChild(document.createTextNode(".gizmo-default{width:100px;height:100px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.custom-gizmo-style{width:360px;height:360px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.map-gizmo-style,.cad-gizmo-style{width:96px;height:96px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.example-container{position:relative;width:640px;height:360px;background-color:#3d5361;border-radius:6px;overflow:hidden}body{background-color:#f0f0f0;margin:0;padding:0}.content{display:flex;justify-content:center;align-items:center;flex-direction:column;height:100vh}.example-select{margin-bottom:24px}")),document.head.appendChild(i)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();const Ch=(i,e,t,n,s,r)=>{const o=performance.now(),a=()=>{const c=performance.now()-o,u=Math.min(c/s,1);i.position.lerpVectors(t,n,u),e==null||e.update(),r(),u<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},br={type:"change"},Ci={type:"start"},io={type:"end"},hs=new p.Ray,_r=new p.Plane,Ph=Math.cos(70*p.MathUtils.DEG2RAD),Oe=new p.Vector3,Qe=2*Math.PI,Te={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},$s=1e-6;class ro extends p.Controls{constructor(e,t=null){super(e,t),this.state=Te.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._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=Lh.bind(this),this._onPointerDown=Ih.bind(this),this._onPointerUp=Oh.bind(this),this._onContextMenu=Uh.bind(this),this._onMouseWheel=kh.bind(this),this._onKeyDown=Fh.bind(this),this._onTouchStart=Bh.bind(this),this._onTouchMove=zh.bind(this),this._onMouseDown=Dh.bind(this),this._onMouseMove=Nh.bind(this),this._interceptControlDown=Vh.bind(this),this._interceptControlUp=Hh.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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="auto"}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(br),this.update(),this.state=Te.NONE}update(e=null){const t=this.object.position;Oe.copy(t).sub(this.target),Oe.applyQuaternion(this._quat),this._spherical.setFromVector3(Oe),this.autoRotate&&this.state===Te.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+=Qe:n>Math.PI&&(n-=Qe),s<-Math.PI?s+=Qe:s>Math.PI&&(s-=Qe),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(Oe.setFromSpherical(this._spherical),Oe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Oe),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=Oe.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=Oe.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):(hs.origin.copy(this.object.position),hs.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(hs.direction))<Ph?this.object.lookAt(this.target):(_r.setFromNormalAndCoplanarPoint(this.object.up,this.target),hs.intersectPlane(_r,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)>$s||8*(1-this._lastQuaternion.dot(this.object.quaternion))>$s||this._lastTargetPosition.distanceToSquared(this.target)>$s?(this.dispatchEvent(br),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Qe/60*this.autoRotateSpeed*e:Qe/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){Oe.setFromMatrixColumn(t,0),Oe.multiplyScalar(-e),this._panOffset.add(Oe)}_panUp(e,t){this.screenSpacePanning===!0?Oe.setFromMatrixColumn(t,1):(Oe.setFromMatrixColumn(t,0),Oe.crossVectors(this.object.up,Oe)),Oe.multiplyScalar(e),this._panOffset.add(Oe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Oe.copy(s).sub(this.target);let r=Oe.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(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*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(Qe*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(-Qe*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(Qe*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(-Qe*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(Qe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Qe*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 Ih(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i)))}function Lh(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function Oh(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(io),this.state=Te.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function Dh(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=Te.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Te.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Te.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Te.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Te.PAN}break;default:this.state=Te.NONE}this.state!==Te.NONE&&this.dispatchEvent(Ci)}function Nh(i){switch(this.state){case Te.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Te.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Te.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function kh(i){this.enabled===!1||this.enableZoom===!1||this.state!==Te.NONE||(i.preventDefault(),this.dispatchEvent(Ci),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(io))}function Fh(i){this.enabled!==!1&&this._handleKeyDown(i)}function Bh(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=Te.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Te.TOUCH_PAN;break;default:this.state=Te.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=Te.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Te.TOUCH_DOLLY_ROTATE;break;default:this.state=Te.NONE}break;default:this.state=Te.NONE}this.state!==Te.NONE&&this.dispatchEvent(Ci)}function zh(i){switch(this._trackPointer(i),this.state){case Te.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Te.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Te.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Te.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Te.NONE}}function Uh(i){this.enabled!==!1&&i.preventDefault()}function Vh(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Hh(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Gh extends ro{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}}}const fe={CUBE_SIZE:1.8,EDGE_SECTION_SIZE:.35,FACE_THICKNESS:.35,CANVAS_SIZE:256,FONT_SIZE:"62px",TEXT_COLOR:"#000000",TEXT_ALIGN:"center",TEXT_BASELINE:"middle",FACE_COLOR:"#EFF3F2",EDGE_COLOR:"#EFF3F2",CORNER_COLOR:"#EFF3F2",LINE_COLOR:0};var Lt=(i=>(i.FRONT="FRONT",i.BACK="BACK",i.RIGHT="RIGHT",i.LEFT="LEFT",i.TOP="TOP",i.BOTTOM="BOTTOM",i))(Lt||{});new y.Vector3(0,1,0);const Cn="rotation-arrows-name",Ti="left-rotation-arrow-name",Es="right-rotation-arrow-name",jh="gizmo-group-name",Wh=[Es,Ti],ms={GIZMO_DISTANCE:8,DEFAULT_UP:new y.Vector3(0,1,0),FORWARD:new y.Vector3(0,0,-1)},Qs=i=>ms.FORWARD.clone().applyQuaternion(i),xr=(i,e,t=new y.Vector3)=>t.clone().add(i.multiplyScalar(-e));class Zh{constructor(e,t=Cn){this.gizmoScene=e,this.gizmoArrowsName=t}syncGizmoWithMain(e,t){e.quaternion.copy(t.quaternion),e.up.copy(t.up);const n=Qs(e.quaternion).normalize();e.position.copy(xr(n,ms.GIZMO_DISTANCE)),e.camera.updateMatrixWorld(!0);const s=this.gizmoScene.getObjectByName(this.gizmoArrowsName);s&&s.rotation.copy(e.camera.rotation)}syncMainWithGizmo(e,t,n){const s=n.target.clone(),r=e.position.distanceTo(s),o=e.camera instanceof y.PerspectiveCamera;n instanceof Gh&&!o?this.syncMapControls(e,t,s,r):this.syncOrbitControls(e,t,s,r),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,s){const r=e.position.y-n.y,o=Qs(t.quaternion);o.y=0,o.normalize();const a=n.clone();a.y+=r,a.add(o.multiplyScalar(-s)),e.position.copy(a),e.up.copy(ms.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,s){const r=Qs(t.quaternion),o=ms.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=xr(r,s,n);e.position.copy(a),e.up.copy(o),e.camera.lookAt(n)}}const oo=i=>new Zh(i),Ar=(i,e,t)=>{oo(t).syncGizmoWithMain({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up})},Kh=(i,e,t)=>{oo(e.userData.scene).syncMainWithGizmo({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up},t)},Xh=()=>{try{const i=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(i.getContext("webgl")||i.getContext("experimental-webgl")))}catch{return!1}},Yh=()=>Xh()?new y.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),qh=i=>{const e=new y.AmbientLight(16777215,1);i.add(e);const t=new y.DirectionalLight(16777215,1);t.position.set(5,10,5),i.add(t);const n=new y.DirectionalLight(16777215,1);n.position.set(-5,-10,5),i.add(n);const s=new y.PointLight(16777215,1,100);s.position.set(0,0,5),i.add(s),t.castShadow=!1,n.castShadow=!1,s.castShadow=!1};class $h{static createTextTexture(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=fe.CANVAS_SIZE,t.height=fe.CANVAS_SIZE,n&&(n.clearRect(0,0,t.width,t.height),n.font=`${fe.FONT_SIZE} Arial`,n.fillStyle=fe.TEXT_COLOR,n.textAlign=fe.TEXT_ALIGN,n.textBaseline=fe.TEXT_BASELINE,n.fillText(e,t.width/2,t.height/2));const s=new y.CanvasTexture(t);return s.needsUpdate=!0,s}}class us{static createWireframe([e,t,n]){const s=new y.BoxGeometry(e,t,n),r=new y.EdgesGeometry(s),o=new y.LineBasicMaterial({color:fe.LINE_COLOR}),a=new y.LineSegments(r,o);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const s=fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,r={x:fe.EDGE_SECTION_SIZE,y:fe.EDGE_SECTION_SIZE,z:fe.EDGE_SECTION_SIZE};r[t]=s;const o=new y.BoxGeometry(r.x,r.y,r.z),a=new y.MeshStandardMaterial({color:fe.EDGE_COLOR}),c=new y.Mesh(o,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new y.BoxGeometry(fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE),s=new y.MeshStandardMaterial({color:fe.CORNER_COLOR}),r=new y.Mesh(n,s);return r.position.copy(e),r.name=`Corner Cube ${t}`,r}static createFace(e,t,n){const s=new y.Group,r=new y.BoxGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.FACE_THICKNESS),o=new y.MeshStandardMaterial({color:fe.FACE_COLOR}),a=new y.Mesh(r,o);a.name=`Face Box ${n}`,s.add(a);const c=new y.PlaneGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE),u=new y.MeshStandardMaterial({map:$h.createTextTexture(n),transparent:!0,depthWrite:!1}),d=new y.Mesh(c,u);return d.position.set(0,0,fe.FACE_THICKNESS/2+.01),s.add(d),s.position.copy(e),s.rotation.copy(t),s}}const Qh=(i,e)=>{const t=document.createElement("canvas");t.width=64,t.height=64;const n=t.getContext("2d");n.fillStyle="rgba(0, 0, 0, 0)",n.fillRect(0,0,t.width,t.height),n.font="Bold 48px Arial",n.fillStyle=`#${e.toString(16).padStart(6,"0")}`,n.textAlign="center",n.textBaseline="middle",n.fillText(i,t.width/2,t.height/2);const s=new y.CanvasTexture(t),r=new y.SpriteMaterial({map:s}),o=new y.Sprite(r);return o.scale.set(.5,.5,.5),o};class Jh{constructor(e){this.hoveredObject=null,this.originalColor=null,this.config=e}get vectorToCube(){var e;return(e=this.hoveredObject)==null?void 0:e.userData.vectorToCube}getInitialRotation(){switch(this.config.initialFace){case Lt.BACK:return new y.Euler(0,Math.PI,0);case Lt.RIGHT:return new y.Euler(0,-Math.PI/2,0);case Lt.LEFT:return new y.Euler(0,Math.PI/2,0);case Lt.TOP:return new y.Euler(Math.PI/2,0,0);case Lt.BOTTOM:return new y.Euler(-Math.PI/2,0,0);case Lt.FRONT:default:return new y.Euler(0,0,0)}}createWireframe(){const e=fe.CUBE_SIZE+fe.EDGE_SECTION_SIZE,t=us.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,n){const s=us.createEdgeBox(e,t,n);return s.userData.gizmoCube=this,s}createCornerCube(e,t){const n=us.createCornerCube(e,t);return n.userData.gizmoCube=this,n}createFace(e,t,n){const s=us.createFace(e,t,n),r=s.getObjectByName(`Face Box ${n}`);return r.userData.gizmoCube=this,s}createEdges(e){const t=fe.CUBE_SIZE/2;[{axis:"x",pos:new y.Vector3(0,t,-t)},{axis:"x",pos:new y.Vector3(0,t,t)},{axis:"x",pos:new y.Vector3(0,-t,-t)},{axis:"x",pos:new y.Vector3(0,-t,t)},{axis:"y",pos:new y.Vector3(t,0,-t)},{axis:"y",pos:new y.Vector3(t,0,t)},{axis:"y",pos:new y.Vector3(-t,0,-t)},{axis:"y",pos:new y.Vector3(-t,0,t)},{axis:"z",pos:new y.Vector3(t,t,0)},{axis:"z",pos:new y.Vector3(t,-t,0)},{axis:"z",pos:new y.Vector3(-t,t,0)},{axis:"z",pos:new y.Vector3(-t,-t,0)}].forEach(({axis:n,pos:s},r)=>{const o=this.createEdgeBox(s,n,r+1);e.add(o)})}createCorners(e){const t=fe.CUBE_SIZE/2;[new y.Vector3(-t,-t,-t),new y.Vector3(-t,-t,t),new y.Vector3(-t,t,-t),new y.Vector3(-t,t,t),new y.Vector3(t,-t,-t),new y.Vector3(t,-t,t),new y.Vector3(t,t,-t),new y.Vector3(t,t,t)].forEach((n,s)=>{const r=this.createCornerCube(n,s+1);e.add(r)})}createFaces(e){const t=fe.CUBE_SIZE/2;[{pos:new y.Vector3(0,0,t),rotation:new y.Euler(0,0,0),label:"FRONT"},{pos:new y.Vector3(0,0,-t),rotation:new y.Euler(0,Math.PI,0),label:"BACK"},{pos:new y.Vector3(t,0,0),rotation:new y.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new y.Vector3(-t,0,0),rotation:new y.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new y.Vector3(0,t,0),rotation:new y.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new y.Vector3(0,-t,0),rotation:new y.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:s,label:r})=>{const o=this.createFace(n,s,r);e.add(o)})}createAxis(e){const{color:t,direction:n,length:s,origin:r,lineWidth:o,label:a}=e,c=new y.Group,u=o/2,d=new y.CylinderGeometry(u,u,s,32),h=new y.MeshBasicMaterial({color:t}),f=new y.Mesh(d,h);if(f.position.copy(r).add(n.clone().multiplyScalar(s/2)),!n.equals(new y.Vector3(0,1,0))){const w=new y.Vector3(0,1,0).cross(n).normalize(),x=Math.acos(new y.Vector3(0,1,0).dot(n));f.setRotationFromAxisAngle(w,x)}c.add(f);const m=Qh(a,t);return m.position.copy(r).add(n.clone().multiplyScalar(s+.1)),c.add(m),c}createCoordinateAxes(){const e=new y.Group,t=fe.CUBE_SIZE,n=fe.EDGE_SECTION_SIZE,s=-1.075,r=a=>{const c=new y.Vector3(1,1,1);return new y.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},o=t+1.25*n;return[{color:16711680,direction:new y.Vector3(1,0,0),length:o,origin:r(s),lineWidth:.04,label:"X"},{color:65280,direction:new y.Vector3(0,1,0),length:o,origin:r(s),lineWidth:.04,label:"Y"},{color:255,direction:new y.Vector3(0,0,1),length:o,origin:r(s),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new y.Group;e.name=jh;const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const n=this.createCoordinateAxes();e.add(n);const s=this.getInitialRotation();return e.setRotationFromEuler(s),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof y.Mesh){const t=e.material;this.hoveredObject=e,this.originalColor=t.color.clone(),t.color.set(11519973)}else this.hoveredObject=null,this.originalColor=null}handleClick(){if(this.hoveredObject){let e=new y.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new y.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class eu{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:s,options:r}=e;this.gizmoDiv=t.gizmoDiv,this.gizmoScene=t.gizmoScene,this.gizmoRenderer=t.gizmoRenderer,this.gizmoCamera=t.gizmoCamera,this.mainCamera=n.mainCamera,this.mainControls=n.mainControls,this.renderGizmo=n.renderGizmo,this.syncFunctions=s,this.options=r,this.gizmoControls=new ro(this.gizmoCamera,this.gizmoRenderer.domElement),this.initializeRenderer(),this.initializeScene(),this.initializeControls(),this.startAnimationLoop()}initializeRenderer(){var e;this.gizmoRenderer.setPixelRatio(window.devicePixelRatio),this.gizmoRenderer.setSize(this.gizmoDiv.clientWidth,this.gizmoDiv.clientHeight);const t=this.gizmoDiv.clientWidth/this.gizmoDiv.clientHeight;this.gizmoCamera.aspect=t,this.gizmoCamera.updateProjectionMatrix(),(e=this.options)!=null&&e.up&&this.gizmoCamera.up.copy(this.options.up),this.gizmoDiv.appendChild(this.gizmoRenderer.domElement)}initializeScene(){var e;const t=new Jh({initialFace:((e=this.options)==null?void 0:e.initialFace)??Lt.FRONT}).create();this.gizmoScene.add(t),qh(this.gizmoScene)}initializeControls(){this.onChangeMainControlsListener=()=>this.syncFunctions.syncGizmoCameraWithMain(this.gizmoCamera,this.mainCamera,this.gizmoScene),this.mainControls.addEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.enableZoom=!1,this.gizmoControls.enablePan=!1,this.gizmoControls.rotateSpeed=.5,this.gizmoControls.update(),this.onChangeGizmoControlsListener=()=>{const e=this.gizmoScene.getObjectByName(Cn);e==null||e.rotation.copy(this.gizmoCamera.rotation),this.syncFunctions.syncMainCameraWithGizmo(this.mainCamera,this.gizmoCamera,this.mainControls),this.renderGizmo()},this.gizmoControls.addEventListener("change",this.onChangeGizmoControlsListener)}startAnimationLoop(){const e=()=>{this.gizmoRenderer.render(this.gizmoScene,this.gizmoCamera)},t=()=>{this.animationId=requestAnimationFrame(t),e()};t()}dispose(){this.mainControls.removeEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.removeEventListener("change",this.onChangeGizmoControlsListener),this.gizmoScene.clear(),cancelAnimationFrame(this.animationId)}}const tu=(i,e)=>{let t;return function(...n){t||(i.apply(this,n),t=!0,setTimeout(()=>t=!1,e))}};function vr(i,e,t){if(!e)return;const n=e.domElement.getBoundingClientRect();t.x=(i.clientX-n.left)/n.width*2-1,t.y=-((i.clientY-n.top)/n.height)*2+1}const ao=(i,e,t,n)=>(n.setFromCamera(i,e),n.intersectObjects(t.children,!0)),co=i=>{var e;const t=["Wireframe",""];return((e=i.find(n=>!t.includes(n.object.name)))==null?void 0:e.object)||null};function nu(i,e,t,n){if(!e||!t)return null;const s=ao(i,e,t,n);return co(s)}function su(i,e){const t=i==null?void 0:i.userData.gizmoCube;if(i&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const iu={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},ru={size:.2,depth:.1,heightRatio:1.4,segments:1};class ou{constructor(e={}){this.config={...iu,...e},this.material=new y.MeshBasicMaterial({color:this.config.color})}create(){const e=new y.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=Cn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new y.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new y.CatmullRomCurve3(e.slice(t+this.config.tubeOffset))]}generateQuarterCirclePoints(){const e=Math.PI/2,t=e/2,n=e/4;return Array.from({length:this.config.numPoints+1},(s,r)=>{const o=r/this.config.numPoints,a=n+t*o,c=this.config.radius*Math.sin(a),u=this.config.radius*Math.cos(a);return new y.Vector3(c,u,0)})}createTubes([e,t]){const n=(s,r)=>{const o=new y.TubeGeometry(s,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new y.Mesh(o,this.material);return a.name=r,a};return[n(e,Ti),n(t,Es)]}createArrowHeads([e,t]){const{size:n,depth:s,heightRatio:r,segments:o}=ru,a=this.createArrowShape(n,r),c=new y.ExtrudeGeometry(a,{steps:o,depth:s,bevelEnabled:!1}).center(),u=(d,h,f)=>{const m=new y.Mesh(c,this.material);return m.position.copy(d),m.rotation.z=h,m.name=f,m};return[u(e.getPoint(0),this.calculateArrowRotation(e.getTangent(0))+Math.PI/2,Ti),u(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,Es)]}createArrowShape(e,t){return new y.Shape().moveTo(0,0).lineTo(e,-e*t).lineTo(-e,-e*t).lineTo(0,0)}calculateArrowRotation(e){return Math.atan2(e.y,e.x)}}const au=i=>{const e=i.rotation,t=.01,n=Math.PI,s=(Math.abs(e.x)%(2*n)+2*n)%(2*n),r=(Math.abs(e.y)%(2*n)+2*n)%(2*n),o=Math.abs(s-n/2)<t||Math.abs(s-3*n/2)<t||Math.abs(r-n/2)<t||Math.abs(r-3*n/2)<t,a=(Math.abs(s)<t||Math.abs(s-n)<t)&&(Math.abs(r)<t||Math.abs(r-n)<t);return!(o||a)},cu=25,lu=200;function hu({gizmoRenderer:i,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:s}){const r=se.useRef(null),o=se.useRef(null),a=se.useRef(new y.Raycaster).current,c=se.useRef(new y.Vector2).current,u=se.useCallback(()=>{const x=e.getObjectByName(Cn),b=au(t);if(x&&b){e.remove(x);return}if(x||b)return;const v=new ou().create();v.rotation.copy(t.rotation),e.add(v)},[e,t]),d=se.useCallback(()=>{const x=e.getObjectByName(Cn);x&&e.remove(x)},[e]),h=se.useCallback(tu(x=>{if(!s.current||!i)return;vr(x,i,c);const b=ao(c,t,e,a),v=co(b);v!=null&&v.userData.gizmoCube?v.userData.gizmoCube.highlightObject(v):e.traverse(T=>{T.userData.gizmoCube&&T.userData.gizmoCube.highlightObject(null)}),b.length>0?u():d()},1e3/cu),[s,i,t,e,a,c,u,d]),f=se.useCallback(x=>{r.current=Date.now(),o.current={x:x.clientX,y:x.clientY}},[]),m=se.useCallback(x=>{var b;const v=x.name===Es?1:-1,T=90*Math.PI/180,S=new y.Vector3(0,0,0),_=v*T,A=new y.Matrix4;A.makeRotationZ(_),t.up.applyMatrix4(A),t.lookAt(S),(b=s.current)==null||b.gizmoControls.update()},[t,s]),w=se.useCallback(x=>{if((r.current?Date.now()-r.current:0)<lu){vr(x,i,c);const b=nu(c,t,e,a);b!=null&&b.name&&Wh.includes(b.name)?m(b):su(b,n)}r.current=null,o.current=null},[m,n,i,t,e,a,c]);return{onMouseDown:f,onMouseMove:h,onMouseUp:w,onMouseLeave:d}}const uu=({camera:i,controls:e,className:t,render:n,options:s})=>{const r=se.useRef(null),o=se.useRef(new y.Scene).current,[a]=se.useState(()=>Yh()),c=30,u=1,d=.1,h=10,f=new y.PerspectiveCamera(c,u,d,h),m=se.useRef(f).current,w=se.useRef(null),x=se.useCallback(()=>{a&&(n(),a.render(o,m))},[n,a,o,m]),b=se.useCallback(A=>{if(!i||!e)return;const L=i.position.length(),I=A.clone().multiplyScalar(L),C=400,D=new y.Matrix4;D.lookAt(I,new y.Vector3(0,0,0),new y.Vector3(0,1,0));const P=new y.Quaternion;P.setFromRotationMatrix(D),i.quaternion.copy(P),Ch(i,e,i.position.clone(),I,C,x),i.up.set(0,1,0),i.lookAt(new y.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[i,e,x,o]),{onMouseDown:v,onMouseMove:T,onMouseUp:S,onMouseLeave:_}=hu({gizmoRenderer:a,gizmoScene:o,gizmoCamera:m,alignCameraWithVector:b,gizmoControlRef:w});return se.useEffect(()=>{const A=r.current;if(!A||!i||!e||!a)return;w.current&&w.current.dispose();const L={gizmoDiv:A,gizmoScene:o,gizmoRenderer:a,gizmoCamera:m},I={mainCamera:i,mainControls:e,renderGizmo:x},C={syncGizmoCameraWithMain:Ar,syncMainCameraWithGizmo:Kh};return w.current=new eu({gizmoParams:L,mainParams:I,syncFunctions:C,options:s}),A.addEventListener("mousedown",v),A.addEventListener("mousemove",T),A.addEventListener("mouseup",S),A.addEventListener("mouseleave",_),()=>{w.current&&(w.current.dispose(),w.current=null),A.removeEventListener("mousedown",v),A.removeEventListener("mousemove",T),A.removeEventListener("mouseup",S),A.removeEventListener("mouseleave",_)}},[i,e,x,T,v,S]),se.useEffect(()=>{i&&(Ar(m,i,o),x())},[i,x]),me.jsx("div",{className:t?`${t}`:"gizmo-default",ref:r})},ds=10,du=i=>({top:i.startsWith("top")?ds:"auto",bottom:i.startsWith("bottom")?ds:"auto",left:i.endsWith("left")?ds:"auto",right:i.endsWith("right")?ds:"auto"}),fu=({camera:i,controls:e,render:t,placement:n="top-right",size:s=128})=>{if(!i||!e)return null;const r=e;return me.jsx("div",{className:"viewer-gizmo-container",style:{position:"absolute",width:s,height:s,zIndex:1e3,...du(n)},children:me.jsx(uu,{camera:i,controls:r,render:t})})};class pu extends se.Component{constructor(e){super(e),this.reset=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ViewerErrorBoundary caught error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:me.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f0f0",color:"#333",fontFamily:"sans-serif",padding:"20px",textAlign:"center"},children:me.jsxs("div",{children:[me.jsx("h3",{children:"Error Loading 3D Viewer"}),me.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),me.jsx("button",{type:"button",onClick:this.reset,children:"Try again"})]})}):this.props.children}}function mu({status:i,label:e,color:t,backdrop:n}){const s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;return me.jsxs("div",{"data-testid":"viewer-loading-overlay",role:"status","aria-live":"polite","aria-busy":i==="loading",style:{position:"absolute",inset:0,zIndex:20,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,background:n,color:t,pointerEvents:"none",userSelect:"none",fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, sans-serif",fontSize:14},children:[i==="loading"?me.jsxs("svg",{width:"44",height:"44",viewBox:"0 0 44 44","aria-hidden":"true",children:[me.jsx("circle",{cx:"22",cy:"22",r:"18",fill:"none",stroke:t,strokeOpacity:"0.25",strokeWidth:"4"}),me.jsx("path",{d:"M22 4 a18 18 0 0 1 18 18",fill:"none",stroke:t,strokeWidth:"4",strokeLinecap:"round",children:!s&&me.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 22 22",to:"360 22 22",dur:"0.9s",repeatCount:"indefinite"})})]}):me.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[me.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),me.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),me.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),e&&me.jsx("div",{style:{opacity:.92,maxWidth:"80%",textAlign:"center"},children:e})]})}const gu='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',yu={background:"rgba(255,255,255,0.78)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(0,0,0,0.06)",boxShadow:"0 8px 30px rgba(0,0,0,0.10)"},wu=Object.keys(Ri);function Eu({active:i,onSelect:e}){return me.jsx("div",{"data-testid":"viewer-preset-picker",role:"group","aria-label":"Visual preset",style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:10,display:"flex",gap:2,padding:4,borderRadius:999,maxWidth:"calc(100% - 16px)",overflowX:"auto",...yu},children:wu.map(t=>me.jsx("button",{type:"button","aria-pressed":t===i,onClick:()=>e(t),style:{padding:"6px 14px",borderRadius:999,border:t===i?"1px solid #111318":"1px solid transparent",background:t===i?"#111318":"transparent",color:t===i?"#fff":"#3f3f4a",fontFamily:gu,fontSize:13,fontWeight:500,lineHeight:1,whiteSpace:"nowrap",flexShrink:0,cursor:"pointer",textTransform:"capitalize",transition:"background 120ms ease, color 120ms ease"},children:t},t))})}const _n={enabled:!0,label:"Loading…",color:"#ffffff",backdrop:"rgba(15,16,20,0.6)"};function Tu(i){return i===void 0||i===!0?_n:i===!1?{..._n,enabled:!1}:{enabled:i.enabled??!0,label:i.label??_n.label,errorLabel:i.errorLabel,color:i.color??_n.color,backdrop:i.backdrop??_n.backdrop}}const Pt=()=>new Z("Viewer is not ready yet",K.COMPONENT_NOT_MOUNTED),lo=se.forwardRef(({object:i,options:e={},preset:t,pathTraced:n,turntable:s,animations:r,children:o},a)=>{var k,G;const c=se.useRef(null),u=e.preset??t,{activePreset:d,pickerEnabled:h,selectPreset:f}=bh(u,e.ui),m=_h(e,d,n,s,r),{viewer:w,isInitialized:x,initError:b}=Sh(c,m),v=xh(w,x,i),T=Ah(w);vh(w,b,e);const S=w?Pn(w.getCamera()):null,_=w?Mi(w.getControls()):null,A=w?Wr(w.getRenderer()):null,L=se.useCallback(()=>{w==null||w.requestRender()},[w]),I=((k=e.helpers)==null?void 0:k.gizmo)!==void 0&&e.helpers.gizmo!==!1,C=typeof((G=e.helpers)==null?void 0:G.gizmo)=="object"?e.helpers.gizmo:{},D=se.useMemo(()=>Tu(e.loadingIndicator),[e.loadingIndicator]),P=v.status==="error"||!!b,F=D.enabled&&(v.status==="loading"||P);return se.useImperativeHandle(a,()=>({scene:w?ft(w.getScene()):null,camera:S,renderer:A,controls:_,events:T,loadModel:async z=>{if(!w)throw Pt();const Y=typeof z=="string"?z:new Ke(z),re=await w.loadModel(Y);if(!re.ok)throw re.error},captureStill:async z=>{if(!w)throw Pt();const Y=await w.captureStill(z);if(!Y.ok)throw Y.error;return Y.value},captureVideo:async z=>{if(!w)throw Pt();const Y=await w.captureVideo(z);if(!Y.ok)throw Y.error;return Y.value},getAnimationNames:()=>(w==null?void 0:w.getAnimationNames())??[],playAnimations:z=>{if(!w)throw Pt();const Y=w.playAnimations(z);if(!Y.ok)throw Y.error},pauseAnimations:()=>{w==null||w.pauseAnimations()},setEnvironmentMap:async z=>{if(!w)throw Pt();const Y=await w.setEnvironmentMap(z);if(!Y.ok)throw Y.error},resetEnvironment:()=>{if(!w)throw Pt();const z=w.resetEnvironment();if(!z.ok)throw z.error},setBackgroundImage:async z=>{if(!w)throw Pt();const Y=await w.setBackgroundImage(z);if(!Y.ok)throw Y.error},setBackgroundColor:z=>{if(!w)throw Pt();const Y=w.setBackgroundColor(z);if(!Y.ok)throw Y.error},dispose:()=>{w==null||w.dispose()}}),[w,S,A,_,T]),me.jsx(pu,{children:me.jsx(Mh,{viewer:w,canvasRef:c,children:me.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[me.jsx(Rh,{}),I&&x&&S&&_&&me.jsx(fu,{camera:S,controls:_,render:L,placement:C.placement,size:C.size}),F&&me.jsx(mu,{status:P?"error":"loading",label:P?D.errorLabel??(b==null?void 0:b.message)??v.error??"Failed to load model":D.label,color:D.color,backdrop:D.backdrop}),h&&me.jsx(Eu,{active:d??"studio",onSelect:f}),o]})})})});lo.displayName="SimpleViewer";const ho=se.forwardRef((i,e)=>me.jsx(lo,{ref:e,...i}));ho.displayName="SimpleViewer";const Su=()=>me.jsx("span",{"aria-hidden":"true",style:{display:"block",width:14,height:14,borderRadius:"50%",background:"rgba(17,19,24,0.9)",border:"2px solid rgba(255,255,255,0.95)",boxShadow:"0 2px 8px rgba(0,0,0,0.35)"}});function bu({position:i,occlude:e=!1,children:t}){const{viewer:n}=so(),s=se.useRef(null),[r,o,a]=i;se.useEffect(()=>{if(!n)return;const u=s.current;if(!u)return;const d=n.createAnchorProjector();if(!d)return;const h={x:r,y:o,z:a},f=()=>{const b=d.project(h,e);if(b){if(!b.visible){u.style.visibility="hidden";return}u.style.visibility="visible",u.style.left=`${b.left}px`,u.style.top=`${b.top}px`}},m=()=>{d.invalidate(),f()};f();const w=n.getEvents(),x=[w.on("render:complete",f),w.on("controls:change",f),w.on("model:loaded",m)];return window.addEventListener("resize",m),()=>{x.forEach(b=>b()),window.removeEventListener("resize",m)}},[n,r,o,a,e]);const c=t!=null&&t!==!1;return me.jsx("div",{ref:s,"data-testid":"viewer-hotspot",style:{position:"absolute",left:0,top:0,transform:"translate(-50%, -50%)",visibility:"hidden",zIndex:5,pointerEvents:c?"auto":"none"},children:c?t:me.jsx(Su,{})})}exports.BOUNDING_DATA_INDEX=ha;exports.BYTES_PER_NODE=Ve;exports.CONTACT_SHADOW_HELPER_FLAG=vs;exports.COUNT=Xe;exports.ControlType=Rn;exports.DEFAULT_PATH_TRACING_SAMPLES=Js;exports.ErrorCode=K;exports.Hotspot=bu;exports.IS_LEAF=Pe;exports.LEAFNODE_MASK_32=la;exports.MeshBVH=Mn;exports.OFFSET=He;exports.PATH_TRACING_FLOOR_FLAG=Ms;exports.Result=N;exports.SAH=Lr;exports.SPLIT_AXIS=Ss;exports.SimpleViewerWrapper=ho;exports.ThreeViewerError=Z;exports.TypedEventEmitter=Ts;exports.VIEWER_PRESETS=Ri;exports.defaultOptions=ws;exports.getIndexArray=kr;exports.getVertexCount=bs;exports.resolvePreset=eo;