threedviewer 2.6.0 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/simple-viewer.es.js +4945 -4548
- package/dist/simple-viewer.umd.js +101 -101
- package/package.json +6 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(Xe,Se){typeof exports=="object"&&typeof module<"u"?Se(exports,require("react/jsx-runtime"),require("react"),require("three")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","three"],Se):(Xe=typeof globalThis<"u"?globalThis:Xe||self,Se(Xe.SimpleViewer={},Xe.jsxRuntime,Xe.React,Xe.THREE))})(this,function(Xe,Se,ne,h){"use strict";function Ys(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const S=Ys(h);class H 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,H)}static fromError(e,t,n){if(e instanceof H)return e;const r=e instanceof Error?e.message:String(e),o={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new H(r,t,o)}}var te=(s=>(s.SCENE_INIT_FAILED="SCENE_INIT_FAILED",s.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",s.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",s.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",s.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",s.INITIALIZATION_FAILED="INITIALIZATION_FAILED",s.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",s.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",s.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",s.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",s.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",s.INVALID_CONFIGURATION="INVALID_CONFIGURATION",s.RENDER_ERROR="RENDER_ERROR",s.RENDER_FAILED="RENDER_FAILED",s.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",s.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",s.INVALID_STATE="INVALID_STATE",s.INVALID_PARAMETER="INVALID_PARAMETER",s.OPERATION_FAILED="OPERATION_FAILED",s.UNKNOWN="UNKNOWN",s))(te||{});const W={ok(s){return{ok:!0,value:s}},err(s){return{ok:!1,error:s}},wrap(s){try{return W.ok(s())}catch(e){return W.err(e instanceof H?e:new H(String(e),te.UNKNOWN,{originalError:e}))}}};class xn{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 r;(r=this.listeners.get(e))==null||r.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(r=>{try{r(t)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}})}once(e,t){const n=this.on(e,r=>{n(),t(r)});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)}}class Ks{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,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()}enableContinuousRendering(){this.continuousRenderingEnabled=!0,this.wakeUp()}disableContinuousRendering(){this.continuousRenderingEnabled=!1}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 r=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&r<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(r),this.lastRenderTime=n,this.needsRender=!1,this.enableIdleDetection&&!this.alwaysRender&&(this.wakeUp(),this.continuousRenderingEnabled||(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.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}class ii{static serialize(e,t,n,r){const o=t.position,i=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:o.x,y:o.y,z:o.z},cameraTarget:{x:i.x,y:i.y,z:i.z},controlsTarget:{x:i.x,y:i.y,z:i.z},rendererSize:{width:r.clientWidth,height:r.clientHeight}}}static async restore(e,t,n,r){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&&r&&await r(e.modelUrl)}}function st(s){return s!==null&&typeof s=="object"&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}class $e{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 $e({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new $e({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new $e({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new $e({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new $e({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new $e({...this.data,status:"rendering"})}updateRenderInfo(e){return new $e({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new $e({...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 Xs{constructor(){this.state=new $e,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)}})}}class $s{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,r){if(this.isShowingScreenshot)return;const o=this.renderer.getDomElement(),i=o.toDataURL("image/png"),a=document.createElement("img");a.src=i,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=o.parentElement;if(c){this.serializedSceneState=ii.serialize(n,e,t,o),o.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const f=()=>{this.restore()};a.addEventListener("mousedown",f),a.addEventListener("touchstart",f);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,this.screenshotElement&&this.screenshotElement.src?r==null||r():console.warn("[ScreenshotManager] Screenshot capture failed, keeping scene resources")}}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.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class Qs{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.autoFitToObject=e.autoFitToObject??!1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const n=performance.now();try{let r;if(typeof e=="string"){this.lastModelUrl=e;const a=await this.modelLoader.load(e);if(!a.ok)throw a.error;r=a.value.scene}else r=e;this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const o=this.scene.add(r);if(!o.ok)throw o.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(r);a.ok||console.warn("Failed to align model to floor:",a.error)}if(r.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=r,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,r,2);a.ok||console.warn("Failed to add dynamic grid:",a.error)}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(r,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const i=performance.now()-n;return t.emit("model:loaded",{model:r,loadTime:i}),W.ok(r)}catch(r){const o=r instanceof H?r:new H("Failed to load model",te.MODEL_LOAD_FAILED,{originalError:r,source:e});return t.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),W.err(o)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.traverse(t=>{var n,r,o;if("geometry"in t&&((n=t.geometry)!=null&&n.dispose)&&((o=(r=t.geometry)==null?void 0:r.dispose)==null||o.call(r)),"material"in t&&t.material){const i=t.material;Array.isArray(i)?i.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):i!=null&&i.dispose&&i.dispose()}}),e.dispose()}dispose(){this.disposeCurrentModel(),this.lastModelUrl=void 0}}class rr{static getMemoryInfo(){const e=performance;return e.memory?{jsHeapUsed:Math.round(e.memory.usedJSHeapSize/1048576),jsHeapTotal:Math.round(e.memory.totalJSHeapSize/1048576),jsHeapLimit:Math.round(e.memory.jsHeapSizeLimit/1048576)}:null}static formatBytes(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":e<1073741824?(e/1048576).toFixed(1)+" MB":(e/1073741824).toFixed(1)+" GB"}static logMemoryUsage(e="Memory"){const t=this.getMemoryInfo();t&&t.webglMemory}static startMonitoring(e=5e3,t="MemoryMonitor"){const n=setInterval(()=>{this.getMemoryInfo()},e);return()=>clearInterval(n)}}class Js{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){rr.logMemoryUsage("Before scene disposal"),!e&&this.pathTracingService,this.environmentService&&this.environmentService.dispose(),this.scene.traverse&&this.scene.traverse(t=>{var n,r,o,i;"geometry"in t&&t.geometry&&((r=(n=t.geometry).dispose)==null||r.call(n)),"material"in t&&t.material&&(Array.isArray(t.material)?t.material.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):(i=(o=t.material).dispose)==null||i.call(o))}),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection(),rr.logMemoryUsage("After scene disposal"),setTimeout(()=>{rr.logMemoryUsage("After GC delay")},2e3)}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}class Hs{constructor(e){var r;this.lastFrameTime=0,this.frameCount=0,this.pathTracingCompleteHandled=!1,this.disposed=!1,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.pathTracingService=e.pathTracingService,this.stateManager=new Xs,this.screenshotManager=new $s({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}}),this.modelManager=new Qs({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,autoFitToObject:(r=this.options.camera)==null?void 0:r.autoFitToObject}),this.resourceManager=new Js({scene:this.scene,pathTracingService:this.pathTracingService,environmentService:this.environmentService}),this.events=new xn;const t=this.options.rendering||{},n=this.options.staticScene!==!1;this.renderLoopManager=new Ks({enableIdleDetection:t.enableIdleDetection??n,idleDelay:t.idleDelay,targetFPS:t.targetFPS,enableFrameRateLimiting:t.enableFrameRateLimiting,alwaysRender:!1})}async initialize(){var e,t,n,r,o,i,a,c,f,d,u,l;try{const g=this.rendererOptions||{},y=this.renderer.initialize(g);if(!y.ok)return y;if(this.sceneSetupService){if(this.options.helpers){const b={grid:this.options.helpers.grid,axes:this.options.helpers.axes,gridColor:"#AAAAAA"},T=this.sceneSetupService.addHelpers(this.scene,b);T.ok||console.warn("Failed to add helpers:",T.error)}const m=this.options.lighting;if(m){const b={ambient:m.ambientLight?{color:String(m.ambientLight.color),intensity:m.ambientLight.intensity}:void 0,hemisphere:m.hemisphereLight?{skyColor:String(m.hemisphereLight.skyColor),groundColor:String(m.hemisphereLight.groundColor),intensity:m.hemisphereLight.intensity}:void 0,directional:m.directionalLight?{color:String(m.directionalLight.color),intensity:m.directionalLight.intensity,position:Array.isArray(m.directionalLight.position)?m.directionalLight.position:void 0,castShadow:m.directionalLight.castShadow,shadow:m.directionalLight.shadow}:void 0},T=this.sceneSetupService.addLighting(this.scene,b);T.ok||console.warn("Failed to add lighting:",T.error)}const x=(e=this.options.environment)==null?void 0:e.url;if(this.options.backgroundColor&&!x&&this.sceneSetupService){const b=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(this.options.backgroundColor),bottomColor:String(this.options.backgroundColor)});b.ok||console.warn("Failed to set background:",b.error)}}if(this.environmentService){const m=await this.environmentService.initialize({renderer:this.renderer,autoDispose:!0});m.ok||console.warn("Failed to initialize environment service:",m.error);const x=(t=this.options.environment)==null?void 0:t.url;if(x){const b=await this.environmentService.loadEnvironmentMap(x);b.ok?this.environmentService.applyToScene(this.scene,b.value,{backgroundBlurriness:(n=this.options.environment)==null?void 0:n.backgroundBlurriness,backgroundIntensity:(r=this.options.environment)==null?void 0:r.backgroundIntensity,environmentIntensity:(o=this.options.environment)==null?void 0:o.environmentIntensity}):console.warn("Failed to load environment map:",b.error)}else if((i=this.options.helpers)!=null&&i.studioEnvironment){const b=this.environmentService.createStudioEnvironment();if(b.ok){if(this.environmentService.applyToScene(this.scene,b.value,{backgroundBlurriness:(a=this.options.environment)==null?void 0:a.backgroundBlurriness,backgroundIntensity:(c=this.options.environment)==null?void 0:c.backgroundIntensity,environmentIntensity:(f=this.options.environment)==null?void 0:f.environmentIntensity}),(d=this.options.helpers)!=null&&d.darkStudioMode&&this.sceneSetupService){const T="#1a1a1f",M=this.sceneSetupService.createGradientBackground(this.scene,{topColor:T,bottomColor:T});M.ok||console.warn("Failed to set dark studio background:",M.error)}}else console.warn("Failed to create studio environment:",b.error)}}const w=((u=this.options.pathTracing)==null?void 0:u.enabled)??!1;if(this.pathTracingService&&w){const m=await this.pathTracingService.initialize({enabled:!0,renderer:this.renderer});m.ok?(this.options.pathTracing&&this.pathTracingService.updateSettings({samples:this.options.pathTracing.maxSamples??300,bounces:this.options.pathTracing.bounces,transmissiveBounces:this.options.pathTracing.transmissiveBounces,renderScale:this.options.pathTracing.renderScale,lowResScale:this.options.pathTracing.lowResScale,dynamicLowRes:this.options.pathTracing.dynamicLowRes,enablePathTracing:this.options.pathTracing.enabled??w}),this.pathTracingService.events.on("pathtracing:paused",x=>{this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),setTimeout(()=>{this.renderLoopManager.stop()},100)})):console.warn("Failed to initialize path tracing:",m.error)}if(this.stateManager.setInitialized(),this.startRenderLoop(),!this.options.staticScene)this.renderLoopManager.setAlwaysRender(!0);else{const m=((l=this.options.pathTracing)==null?void 0:l.enabled)??!1;this.pathTracingService&&m&&this.renderLoopManager.enableContinuousRendering()}return this.renderLoopManager.requestRender(),W.ok(void 0)}catch(g){const y=new H("Failed to initialize viewer",te.INITIALIZATION_FAILED,{originalError:g});return this.stateManager.setError(y),this.events.emit("error",{error:y}),W.err(y)}}async loadModel(e){var t;if(!this.stateManager.canLoad())return W.err(new H("Cannot load model in current state",te.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const n=await this.modelManager.loadModel(e,this.events);if(n.ok){this.stateManager.setLoaded(n.value),this.renderLoopManager.requestRender();const r=((t=this.options.pathTracing)==null?void 0:t.enabled)??!1;return this.pathTracingService&&r&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),W.ok(void 0)}else return this.stateManager.setError(n.error),n}catch(n){const r=n instanceof H?n:new H("Failed to load model",te.MODEL_LOAD_FAILED,{originalError:n,source:e});return this.stateManager.setError(r),W.err(r)}}startRenderLoop(){this.renderLoopManager.start(e=>{var f,d,u,l,g;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.renderer===null){this.renderLoopManager.stop();return}this.frameCount%60;const t=performance.now(),n=e>0?1e3/e:0;if(this.controls.update()){this.events.emit("controls:change",{controls:this.controls});const y=((f=this.options.pathTracing)==null?void 0:f.enabled)??!1;this.pathTracingService&&y&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),this.renderLoopManager.requestRender()}const o=((d=this.pathTracingService)==null?void 0:d.isEnabled())||!1,i=((u=this.pathTracingService)==null?void 0:u.getSampleCount())||0,a=((l=this.options.pathTracing)==null?void 0:l.maxSamples)??300;if(this.renderFrame().catch(y=>{console.error("[ViewerCore] Render frame error:",y)}),(((g=this.pathTracingService)==null?void 0:g.getSampleCount())||0)>=a&&!this.pathTracingCompleteHandled&&o){if(this.pathTracingCompleteHandled=!0,this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),this.events.emit("pathtracing:complete",{samples:i,totalTime:t-(this.pathTracingStartTime||0)}),this.options.replaceWithScreenshotOnComplete)setTimeout(()=>{this.replaceWithScreenshot(),setTimeout(()=>{this.renderLoopManager.stop()},200)},100);else if(this.renderLoopManager.requestRender(),setTimeout(()=>{this.renderLoopManager.stop()},100),st(this.renderer)){const y=this.renderer.getInternalRenderer();y&&(y.autoClear=!1)}}this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t}),this.lastFrameTime=t})}stopRenderLoop(){this.renderLoopManager.stop()}async renderFrame(){var f,d,u,l;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();let t;const n=((f=this.pathTracingService)==null?void 0:f.isEnabled())||!1,r=((d=this.pathTracingService)==null?void 0:d.getSampleCount())||0,o=((u=this.options.pathTracing)==null?void 0:u.maxSamples)??300;if(this.pathTracingService&&!this.pathTracingService.isPathTracerDisposed()&&(n||r>=o&&r>0)&&this.pathTracingService?(this.pathTracingService.getSampleCount()===0&&(this.pathTracingStartTime=performance.now()),t=await this.pathTracingService.render(this.scene,this.camera)):t=this.renderer.render(this.scene,this.camera),!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}const a=performance.now()-e,c=((l=this.pathTracingService)==null?void 0:l.getSampleCount())||0;this.events.emit("render:complete",{frame:this.frameCount,renderTime:a,samples:c})}resize(e,t){var o;const n=this.renderer.getDomElement();if(n.width===e&&n.height===t)return;const r=(o=this.pathTracingService)==null?void 0:o.isEnabled();this.pathTracingService&&this.pathTracingService.hasImageOverlay()&&(this.pathTracingService.removeImageOverlay(),this.pathTracingService.reset()),this.camera.type==="perspective"&&"aspect"in this.camera&&(this.camera.aspect=e/t),this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}r&&this.pathTracingService&&this.pathTracingService.setEnabled(!0),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){var t;const e=this.screenshotManager.getSerializedState();!this.pathTracingService&&((t=this.options.pathTracing)!=null&&t.enabled)&&console.warn("[ViewerCore] Cannot recreate path tracing service - feature disabled"),e&&await ii.restore(e,this.camera,this.controls,async n=>{const r=await this.loadModel(n);r.ok||console.error("[ViewerCore] Failed to reload model:",r.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){this.disposed=!0,this.stopRenderLoop(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.scene.clear(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),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 S.Vector3(e,t,n))}}class Fe{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 position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof Fe?(this.object.add(e.getThreeObject()),W.ok(void 0)):W.err(new H("Child must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return W.err(new H("Failed to add child object",te.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Fe?(this.object.remove(e.getThreeObject()),W.ok(void 0)):W.err(new H("Child must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return W.err(new H("Failed to remove child object",te.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Fe(t))})}clone(){return new Fe(this.object.clone())}dispose(){this.object.traverse(e=>{var t;e instanceof S.Mesh&&((t=e.geometry)==null||t.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>n.dispose()):e.material.dispose()))})}getThreeObject(){return this.object}static fromThreeObject(e){return new Fe(e)}static create(){return new Fe(new S.Object3D)}}class St{constructor(e){this.scene=e||new S.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 Fe?(this.scene.add(e.getThreeObject()),W.ok(void 0)):W.err(new H("Object must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return W.err(new H("Failed to add object to scene",te.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Fe?(this.scene.remove(e.getThreeObject()),W.ok(void 0)):W.err(new H("Object must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return W.err(new H("Failed to remove object from scene",te.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}traverse(e){this.scene.traverse(t=>{e(new Fe(t))})}get background(){return this.scene.background instanceof S.Color?new ir(this.scene.background):this.scene.background instanceof S.Texture?new bn(this.scene.background):null}set background(e){e instanceof ir?this.scene.background=e.getThreeColor():e instanceof bn?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new si(this.scene.fog):null}set fog(e){e instanceof si?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new bn(this.scene.environment):null}set environment(e){e instanceof bn?this.scene.environment=e.getThreeTexture():this.scene.environment=null}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class ir{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 bn=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 si{constructor(e){this.fog=e}get color(){return new ir(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class sr extends Fe{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof S.PerspectiveCamera||this.camera instanceof S.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 S.PerspectiveCamera||this.camera instanceof S.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new S.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class or extends sr{constructor(e){const t=e||new S.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=75,t=1,n=.1,r=1e3){return new or(new S.PerspectiveCamera(e,t,n,r))}}function eo(){const s="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?s[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}class to{constructor(e){this.renderer=null,this._id=eo(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new S.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:S.BasicShadowMap,pcf:S.PCFShadowMap,pcfsoft:S.PCFSoftShadowMap,vsm:S.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:S.NoToneMapping,linear:S.LinearToneMapping,reinhard:S.ReinhardToneMapping,cineon:S.CineonToneMapping,aces:S.ACESFilmicToneMapping};this.renderer.toneMapping=t[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}if(e.pixelRatio!==void 0?this.renderer.setPixelRatio(e.pixelRatio):this.renderer.setPixelRatio(window.devicePixelRatio),this.canvas){const{clientWidth:t,clientHeight:n}=this.canvas.parentElement||this.canvas;t&&n&&this.renderer.setSize(t,n)}return this.renderer.outputColorSpace=S.SRGBColorSpace,W.ok(void 0)}catch(t){return W.err(new H("Failed to initialize renderer",te.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return W.err(new H("Renderer not initialized",te.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof St))return W.err(new H("Scene must be a ThreeSceneAdapter",te.INVALID_PARAMETER));if(!(t instanceof sr))return W.err(new H("Camera must be a ThreeCameraAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene(),r=t.getThreeCamera();return this.renderer.__pathTracingActive||this.renderer.render(n,r),W.ok(void 0)}catch(n){return W.err(new H("Failed to render frame",te.RENDER_FAILED,{originalError:n}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const n=this.renderer.domElement;n.style.width="100%",n.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(e)}getDomElement(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.domElement}getContext(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.getContext()}get capabilities(){if(!this.renderer)return{maxTextureSize:0,maxCubemapSize:0,maxAttributes:0,maxVertexUniforms:0,maxFragmentUniforms:0,maxSamples:0,isWebGL2:!1};const e=this.renderer.capabilities;return{maxTextureSize:e.maxTextureSize,maxCubemapSize:e.maxCubemapSize,maxAttributes:e.maxAttributes,maxVertexUniforms:e.maxVertexUniforms,maxFragmentUniforms:e.maxFragmentUniforms,maxSamples:e.maxSamples||0,isWebGL2:e.isWebGL2}}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function oi(s,e){if(e===h.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===h.TriangleFanDrawMode||e===h.TriangleStripDrawMode){let t=s.getIndex();if(t===null){const i=[],a=s.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)i.push(c);s.setIndex(i),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,r=[];if(e===h.TriangleFanDrawMode)for(let i=1;i<=n;i++)r.push(t.getX(0)),r.push(t.getX(i)),r.push(t.getX(i+1));else for(let i=0;i<n;i++)i%2===0?(r.push(t.getX(i)),r.push(t.getX(i+1)),r.push(t.getX(i+2))):(r.push(t.getX(i+2)),r.push(t.getX(i+1)),r.push(t.getX(i)));r.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(r),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class no extends h.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ao(t)}),this.register(function(t){return new co(t)}),this.register(function(t){return new yo(t)}),this.register(function(t){return new xo(t)}),this.register(function(t){return new bo(t)}),this.register(function(t){return new uo(t)}),this.register(function(t){return new ho(t)}),this.register(function(t){return new fo(t)}),this.register(function(t){return new po(t)}),this.register(function(t){return new oo(t)}),this.register(function(t){return new mo(t)}),this.register(function(t){return new lo(t)}),this.register(function(t){return new vo(t)}),this.register(function(t){return new go(t)}),this.register(function(t){return new io(t)}),this.register(function(t){return new wo(t)}),this.register(function(t){return new _o(t)})}load(e,t,n,r){const o=this;let i;if(this.resourcePath!=="")i=this.resourcePath;else if(this.path!==""){const f=h.LoaderUtils.extractUrlBase(e);i=h.LoaderUtils.resolveURL(f,this.path)}else i=h.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(f){r?r(f):console.error(f),o.manager.itemError(e),o.manager.itemEnd(e)},c=new h.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(f){try{o.parse(f,i,function(d){t(d),o.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,r){let o;const i={},a={},c=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===ai){try{i[ie.KHR_BINARY_GLTF]=new To(e)}catch(u){r&&r(u);return}o=JSON.parse(i[ie.KHR_BINARY_GLTF].content)}else o=JSON.parse(c.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const f=new ko(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});f.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const u=this.pluginCallbacks[d](f);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,i[u.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const u=o.extensionsUsed[d],l=o.extensionsRequired||[];switch(u){case ie.KHR_MATERIALS_UNLIT:i[u]=new so;break;case ie.KHR_DRACO_MESH_COMPRESSION:i[u]=new So(o,this.dracoLoader);break;case ie.KHR_TEXTURE_TRANSFORM:i[u]=new Mo;break;case ie.KHR_MESH_QUANTIZATION:i[u]=new Ao;break;default:l.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}f.setExtensions(i),f.setPlugins(a),f.parse(n,r)}parseAsync(e,t){const n=this;return new Promise(function(r,o){n.parse(e,t,r,o)})}}function ro(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const ie={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",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class io{constructor(e){this.parser=e,this.name=ie.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let r=t.cache.get(n);if(r)return r;const o=t.json,c=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let f;const d=new h.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],h.LinearSRGBColorSpace);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":f=new h.DirectionalLight(d),f.target.position.set(0,0,-1),f.add(f.target);break;case"point":f=new h.PointLight(d),f.distance=u;break;case"spot":f=new h.SpotLight(d),f.distance=u,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,f.angle=c.spot.outerConeAngle,f.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,f.target.position.set(0,0,-1),f.add(f.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return f.position.set(0,0,0),ot(f,c),c.intensity!==void 0&&(f.intensity=c.intensity),f.name=t.createUniqueName(c.name||"light_"+e),r=Promise.resolve(f),t.cache.add(n,r),r}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],a=(o.extensions&&o.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class so{constructor(){this.name=ie.KHR_MATERIALS_UNLIT}getMaterialType(){return h.MeshBasicMaterial}extendParams(e,t,n){const r=[];e.color=new h.Color(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const i=o.baseColorFactor;e.color.setRGB(i[0],i[1],i[2],h.LinearSRGBColorSpace),e.opacity=i[3]}o.baseColorTexture!==void 0&&r.push(n.assignTexture(e,"map",o.baseColorTexture,h.SRGBColorSpace))}return Promise.all(r)}}class oo{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=r.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class ao{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(o.push(n.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){const a=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new h.Vector2(a,a)}return Promise.all(o)}}class co{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=r.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class lo{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(o)}}class uo{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new h.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const i=r.extensions[this.name];if(i.sheenColorFactor!==void 0){const a=i.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],h.LinearSRGBColorSpace)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&o.push(n.assignTexture(t,"sheenColorMap",i.sheenColorTexture,h.SRGBColorSpace)),i.sheenRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(o)}}class ho{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&o.push(n.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(o)}}class fo{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&o.push(n.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const a=i.attenuationColor||[1,1,1];return t.attenuationColor=new h.Color().setRGB(a[0],a[1],a[2],h.LinearSRGBColorSpace),Promise.all(o)}}class po{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=r.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class mo{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&o.push(n.assignTexture(t,"specularIntensityMap",i.specularTexture));const a=i.specularColorFactor||[1,1,1];return t.specularColor=new h.Color().setRGB(a[0],a[1],a[2],h.LinearSRGBColorSpace),i.specularColorTexture!==void 0&&o.push(n.assignTexture(t,"specularColorMap",i.specularColorTexture,h.SRGBColorSpace)),Promise.all(o)}}class go{constructor(e){this.parser=e,this.name=ie.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&o.push(n.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(o)}}class vo{constructor(e){this.parser=e,this.name=ie.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const o=[],i=r.extensions[this.name];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&o.push(n.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(o)}}class yo{constructor(e){this.parser=e,this.name=ie.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;const o=r.extensions[this.name],i=t.options.ktx2Loader;if(!i){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,o.source,i)}}class xo{constructor(e){this.parser=e,this.name=ie.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,r=n.json,o=r.textures[e];if(!o.extensions||!o.extensions[t])return null;const i=o.extensions[t],a=r.images[i.source];let c=n.textureLoader;if(a.uri){const f=n.options.manager.getHandler(a.uri);f!==null&&(c=f)}return n.loadTextureImage(e,i.source,c)}}class bo{constructor(e){this.parser=e,this.name=ie.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,r=n.json,o=r.textures[e];if(!o.extensions||!o.extensions[t])return null;const i=o.extensions[t],a=r.images[i.source];let c=n.textureLoader;if(a.uri){const f=n.options.manager.getHandler(a.uri);f!==null&&(c=f)}return n.loadTextureImage(e,i.source,c)}}class wo{constructor(e){this.name=ie.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const r=n.extensions[this.name],o=this.parser.getDependency("buffer",r.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.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 o.then(function(a){const c=r.byteOffset||0,f=r.byteLength||0,d=r.count,u=r.byteStride,l=new Uint8Array(a,c,f);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(d,u,l,r.mode,r.filter).then(function(g){return g.buffer}):i.ready.then(function(){const g=new ArrayBuffer(d*u);return i.decodeGltfBuffer(new Uint8Array(g),d,u,l,r.mode,r.filter),g})})}else return null}}class _o{constructor(e){this.name=ie.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 r=t.meshes[n.mesh];for(const f of r.primitives)if(f.mode!==Ve.TRIANGLES&&f.mode!==Ve.TRIANGLE_STRIP&&f.mode!==Ve.TRIANGLE_FAN&&f.mode!==void 0)return null;const i=n.extensions[this.name].attributes,a=[],c={};for(const f in i)a.push(this.parser.getDependency("accessor",i[f]).then(d=>(c[f]=d,c[f])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(f=>{const d=f.pop(),u=d.isGroup?d.children:[d],l=f[0].count,g=[];for(const y of u){const w=new h.Matrix4,m=new h.Vector3,x=new h.Quaternion,b=new h.Vector3(1,1,1),T=new h.InstancedMesh(y.geometry,y.material,l);for(let M=0;M<l;M++)c.TRANSLATION&&m.fromBufferAttribute(c.TRANSLATION,M),c.ROTATION&&x.fromBufferAttribute(c.ROTATION,M),c.SCALE&&b.fromBufferAttribute(c.SCALE,M),T.setMatrixAt(M,w.compose(m,x,b));for(const M in c)if(M==="_COLOR_0"){const A=c[M];T.instanceColor=new h.InstancedBufferAttribute(A.array,A.itemSize,A.normalized)}else M!=="TRANSLATION"&&M!=="ROTATION"&&M!=="SCALE"&&y.geometry.setAttribute(M,c[M]);h.Object3D.prototype.copy.call(T,y),this.parser.assignFinalMaterial(T),g.push(T)}return d.isGroup?(d.clear(),d.add(...g),d):g[0]}))}}const ai="glTF",en=12,ci={JSON:1313821514,BIN:5130562};class To{constructor(e){this.name=ie.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,en),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!==ai)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const r=this.header.length-en,o=new DataView(e,en);let i=0;for(;i<r;){const a=o.getUint32(i,!0);i+=4;const c=o.getUint32(i,!0);if(i+=4,c===ci.JSON){const f=new Uint8Array(e,en+i,a);this.content=n.decode(f)}else if(c===ci.BIN){const f=en+i;this.body=e.slice(f,f+a)}i+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class So{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=ie.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,r=this.dracoLoader,o=e.extensions[this.name].bufferView,i=e.extensions[this.name].attributes,a={},c={},f={};for(const d in i){const u=cr[d]||d.toLowerCase();a[u]=i[d]}for(const d in e.attributes){const u=cr[d]||d.toLowerCase();if(i[d]!==void 0){const l=n.accessors[e.attributes[d]],g=Rt[l.componentType];f[u]=g.name,c[u]=l.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(u,l){r.decodeDracoFile(d,function(g){for(const y in g.attributes){const w=g.attributes[y],m=c[y];m!==void 0&&(w.normalized=m)}u(g)},a,f,h.LinearSRGBColorSpace,l)})})}}class Mo{constructor(){this.name=ie.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 Ao{constructor(){this.name=ie.KHR_MESH_QUANTIZATION}}class li extends h.Interpolant{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,o=e*r*3+r;for(let i=0;i!==r;i++)t[i]=n[o+i];return t}interpolate_(e,t,n,r){const o=this.resultBuffer,i=this.sampleValues,a=this.valueSize,c=a*2,f=a*3,d=r-t,u=(n-t)/d,l=u*u,g=l*u,y=e*f,w=y-f,m=-2*g+3*l,x=g-l,b=1-m,T=x-l+u;for(let M=0;M!==a;M++){const A=i[w+M+a],I=i[w+M+c]*d,P=i[y+M+a],D=i[y+M]*d;o[M]=b*A+T*I+m*P+x*D}return o}}const Io=new h.Quaternion;class Co extends li{interpolate_(e,t,n,r){const o=super.interpolate_(e,t,n,r);return Io.fromArray(o).normalize().toArray(o),o}}const Ve={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Rt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},ui={9728:h.NearestFilter,9729:h.LinearFilter,9984:h.NearestMipmapNearestFilter,9985:h.LinearMipmapNearestFilter,9986:h.NearestMipmapLinearFilter,9987:h.LinearMipmapLinearFilter},hi={33071:h.ClampToEdgeWrapping,33648:h.MirroredRepeatWrapping,10497:h.RepeatWrapping},ar={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},cr={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"},pt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Po={CUBICSPLINE:void 0,LINEAR:h.InterpolateLinear,STEP:h.InterpolateDiscrete},lr={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Do(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new h.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:h.FrontSide})),s.DefaultMaterial}function Mt(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function ot(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Fo(s,e,t){let n=!1,r=!1,o=!1;for(let f=0,d=e.length;f<d;f++){const u=e[f];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(r=!0),u.COLOR_0!==void 0&&(o=!0),n&&r&&o)break}if(!n&&!r&&!o)return Promise.resolve(s);const i=[],a=[],c=[];for(let f=0,d=e.length;f<d;f++){const u=e[f];if(n){const l=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):s.attributes.position;i.push(l)}if(r){const l=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):s.attributes.normal;a.push(l)}if(o){const l=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):s.attributes.color;c.push(l)}}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c)]).then(function(f){const d=f[0],u=f[1],l=f[2];return n&&(s.morphAttributes.position=d),r&&(s.morphAttributes.normal=u),o&&(s.morphAttributes.color=l),s.morphTargetsRelative=!0,s})}function Ro(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,r=t.length;n<r;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Oo(s){let e;const t=s.extensions&&s.extensions[ie.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ur(t.attributes):e=s.indices+":"+ur(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,r=s.targets.length;n<r;n++)e+=":"+ur(s.targets[n]);return e}function ur(s){let e="";const t=Object.keys(s).sort();for(let n=0,r=t.length;n<r;n++)e+=t[n]+":"+s[t[n]]+";";return e}function hr(s){switch(s){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 Lo(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const No=new h.Matrix4;class ko{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new ro,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,r=-1,o=!1,i=-1;if(typeof navigator<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);r=n&&c?parseInt(c[1],10):-1,o=a.indexOf("Firefox")>-1,i=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&r<17||o&&i<98?this.textureLoader=new h.TextureLoader(this.options.manager):this.textureLoader=new h.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new h.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,r=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(i){return i._markDefs&&i._markDefs()}),Promise.all(this._invokeAll(function(i){return i.beforeRoot&&i.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(i){const a={scene:i[0][r.scene||0],scenes:i[0],animations:i[1],cameras:i[2],asset:r.asset,parser:n,userData:{}};return Mt(o,a,r),ot(a,r),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 r=0,o=t.length;r<o;r++){const i=t[r].joints;for(let a=0,c=i.length;a<c;a++)e[i[a]].isBone=!0}for(let r=0,o=e.length;r<o;r++){const i=e[r];i.mesh!==void 0&&(this._addNodeRef(this.meshCache,i.mesh),i.skin!==void 0&&(n[i.mesh].isSkinnedMesh=!0)),i.camera!==void 0&&this._addNodeRef(this.cameraCache,i.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 r=n.clone(),o=(i,a)=>{const c=this.associations.get(i);c!=null&&this.associations.set(a,c);for(const[f,d]of i.children.entries())o(d,a.children[f])};return o(n,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const r=e(t[n]);if(r)return r}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let r=0;r<t.length;r++){const o=e(t[r]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let r=this.cache.get(n);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":r=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":r=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!r)throw new Error("Unknown type: "+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,r=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(r.map(function(o,i){return n.getDependency(e,i)})),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[ie.KHR_BINARY_GLTF].body);const r=this.options;return new Promise(function(o,i){n.load(h.LoaderUtils.resolveURL(t.uri,r.path),o,void 0,function(){i(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 r=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+r)})}loadAccessor(e){const t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){const i=ar[r.type],a=Rt[r.componentType],c=r.normalized===!0,f=new a(r.count*i);return Promise.resolve(new h.BufferAttribute(f,i,c))}const o=[];return r.bufferView!==void 0?o.push(this.getDependency("bufferView",r.bufferView)):o.push(null),r.sparse!==void 0&&(o.push(this.getDependency("bufferView",r.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",r.sparse.values.bufferView))),Promise.all(o).then(function(i){const a=i[0],c=ar[r.type],f=Rt[r.componentType],d=f.BYTES_PER_ELEMENT,u=d*c,l=r.byteOffset||0,g=r.bufferView!==void 0?n.bufferViews[r.bufferView].byteStride:void 0,y=r.normalized===!0;let w,m;if(g&&g!==u){const x=Math.floor(l/g),b="InterleavedBuffer:"+r.bufferView+":"+r.componentType+":"+x+":"+r.count;let T=t.cache.get(b);T||(w=new f(a,x*g,r.count*g/d),T=new h.InterleavedBuffer(w,g/d),t.cache.add(b,T)),m=new h.InterleavedBufferAttribute(T,c,l%g/d,y)}else a===null?w=new f(r.count*c):w=new f(a,l,r.count*c),m=new h.BufferAttribute(w,c,y);if(r.sparse!==void 0){const x=ar.SCALAR,b=Rt[r.sparse.indices.componentType],T=r.sparse.indices.byteOffset||0,M=r.sparse.values.byteOffset||0,A=new b(i[1],T,r.sparse.count*x),I=new f(i[2],M,r.sparse.count*c);a!==null&&(m=new h.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let P=0,D=A.length;P<D;P++){const R=A[P];if(m.setX(R,I[P*c]),c>=2&&m.setY(R,I[P*c+1]),c>=3&&m.setZ(R,I[P*c+2]),c>=4&&m.setW(R,I[P*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=y}return m})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,i=t.images[o];let a=this.textureLoader;if(i.uri){const c=n.manager.getHandler(i.uri);c!==null&&(a=c)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,n){const r=this,o=this.json,i=o.textures[e],a=o.images[t],c=(a.uri||a.bufferView)+":"+i.sampler;if(this.textureCache[c])return this.textureCache[c];const f=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=i.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const l=(o.samplers||{})[i.sampler]||{};return d.magFilter=ui[l.magFilter]||h.LinearFilter,d.minFilter=ui[l.minFilter]||h.LinearMipmapLinearFilter,d.wrapS=hi[l.wrapS]||h.RepeatWrapping,d.wrapT=hi[l.wrapT]||h.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==h.NearestFilter&&d.minFilter!==h.LinearFilter,r.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=f,f}loadImageSource(e,t){const n=this,r=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const i=r.images[e],a=self.URL||self.webkitURL;let c=i.uri||"",f=!1;if(i.bufferView!==void 0)c=n.getDependency("bufferView",i.bufferView).then(function(u){f=!0;const l=new Blob([u],{type:i.mimeType});return c=a.createObjectURL(l),c});else if(i.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(c).then(function(u){return new Promise(function(l,g){let y=l;t.isImageBitmapLoader===!0&&(y=function(w){const m=new h.Texture(w);m.needsUpdate=!0,l(m)}),t.load(h.LoaderUtils.resolveURL(u,o.path),y,void 0,g)})}).then(function(u){return f===!0&&a.revokeObjectURL(c),ot(u,i),u.userData.mimeType=i.mimeType||Lo(i.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=d,d}assignTexture(e,t,n,r){const o=this;return this.getDependency("texture",n.index).then(function(i){if(!i)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(i=i.clone(),i.channel=n.texCoord),o.extensions[ie.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[ie.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=o.associations.get(i);i=o.extensions[ie.KHR_TEXTURE_TRANSFORM].extendTexture(i,a),o.associations.set(i,c)}}return r!==void 0&&(i.colorSpace=r),e[t]=i,i})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const r=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,i=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new h.PointsMaterial,h.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 h.LineBasicMaterial,h.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(r||o||i){let a="ClonedMaterial:"+n.uuid+":";r&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),i&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),o&&(c.vertexColors=!0),i&&(c.flatShading=!0),r&&(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 h.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,r=this.extensions,o=n.materials[e];let i;const a={},c=o.extensions||{},f=[];if(c[ie.KHR_MATERIALS_UNLIT]){const u=r[ie.KHR_MATERIALS_UNLIT];i=u.getMaterialType(),f.push(u.extendParams(a,o,t))}else{const u=o.pbrMetallicRoughness||{};if(a.color=new h.Color(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const l=u.baseColorFactor;a.color.setRGB(l[0],l[1],l[2],h.LinearSRGBColorSpace),a.opacity=l[3]}u.baseColorTexture!==void 0&&f.push(t.assignTexture(a,"map",u.baseColorTexture,h.SRGBColorSpace)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(f.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),f.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),i=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(e)}),f.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=h.DoubleSide);const d=o.alphaMode||lr.OPAQUE;if(d===lr.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===lr.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&i!==h.MeshBasicMaterial&&(f.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new h.Vector2(1,1),o.normalTexture.scale!==void 0)){const u=o.normalTexture.scale;a.normalScale.set(u,u)}if(o.occlusionTexture!==void 0&&i!==h.MeshBasicMaterial&&(f.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&i!==h.MeshBasicMaterial){const u=o.emissiveFactor;a.emissive=new h.Color().setRGB(u[0],u[1],u[2],h.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&i!==h.MeshBasicMaterial&&f.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,h.SRGBColorSpace)),Promise.all(f).then(function(){const u=new i(a);return o.name&&(u.name=o.name),ot(u,o),t.associations.set(u,{materials:e}),o.extensions&&Mt(r,u,o),u})}createUniqueName(e){const t=h.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,r=this.primitiveCache;function o(a){return n[ie.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return fi(c,a,t)})}const i=[];for(let a=0,c=e.length;a<c;a++){const f=e[a],d=Oo(f),u=r[d];if(u)i.push(u.promise);else{let l;f.extensions&&f.extensions[ie.KHR_DRACO_MESH_COMPRESSION]?l=o(f):l=fi(new h.BufferGeometry,f,t),r[d]={primitive:f,promise:l},i.push(l)}}return Promise.all(i)}loadMesh(e){const t=this,n=this.json,r=this.extensions,o=n.meshes[e],i=o.primitives,a=[];for(let c=0,f=i.length;c<f;c++){const d=i[c].material===void 0?Do(this.cache):this.getDependency("material",i[c].material);a.push(d)}return a.push(t.loadGeometries(i)),Promise.all(a).then(function(c){const f=c.slice(0,c.length-1),d=c[c.length-1],u=[];for(let g=0,y=d.length;g<y;g++){const w=d[g],m=i[g];let x;const b=f[g];if(m.mode===Ve.TRIANGLES||m.mode===Ve.TRIANGLE_STRIP||m.mode===Ve.TRIANGLE_FAN||m.mode===void 0)x=o.isSkinnedMesh===!0?new h.SkinnedMesh(w,b):new h.Mesh(w,b),x.isSkinnedMesh===!0&&x.normalizeSkinWeights(),m.mode===Ve.TRIANGLE_STRIP?x.geometry=oi(x.geometry,h.TriangleStripDrawMode):m.mode===Ve.TRIANGLE_FAN&&(x.geometry=oi(x.geometry,h.TriangleFanDrawMode));else if(m.mode===Ve.LINES)x=new h.LineSegments(w,b);else if(m.mode===Ve.LINE_STRIP)x=new h.Line(w,b);else if(m.mode===Ve.LINE_LOOP)x=new h.LineLoop(w,b);else if(m.mode===Ve.POINTS)x=new h.Points(w,b);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);Object.keys(x.geometry.morphAttributes).length>0&&Ro(x,o),x.name=t.createUniqueName(o.name||"mesh_"+e),ot(x,o),m.extensions&&Mt(r,x,m),t.assignFinalMaterial(x),u.push(x)}for(let g=0,y=u.length;g<y;g++)t.associations.set(u[g],{meshes:e,primitives:g});if(u.length===1)return o.extensions&&Mt(r,u[0],o),u[0];const l=new h.Group;o.extensions&&Mt(r,l,o),t.associations.set(l,{meshes:e});for(let g=0,y=u.length;g<y;g++)l.add(u[g]);return l})}loadCamera(e){let t;const n=this.json.cameras[e],r=n[n.type];if(!r){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new h.PerspectiveCamera(h.MathUtils.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type==="orthographic"&&(t=new h.OrthographicCamera(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),ot(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let r=0,o=t.joints.length;r<o;r++)n.push(this._loadNodeShallow(t.joints[r]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(r){const o=r.pop(),i=r,a=[],c=[];for(let f=0,d=i.length;f<d;f++){const u=i[f];if(u){a.push(u);const l=new h.Matrix4;o!==null&&l.fromArray(o.array,f*16),c.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[f])}return new h.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,r=t.animations[e],o=r.name?r.name:"animation_"+e,i=[],a=[],c=[],f=[],d=[];for(let u=0,l=r.channels.length;u<l;u++){const g=r.channels[u],y=r.samplers[g.sampler],w=g.target,m=w.node,x=r.parameters!==void 0?r.parameters[y.input]:y.input,b=r.parameters!==void 0?r.parameters[y.output]:y.output;w.node!==void 0&&(i.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",x)),c.push(this.getDependency("accessor",b)),f.push(y),d.push(w))}return Promise.all([Promise.all(i),Promise.all(a),Promise.all(c),Promise.all(f),Promise.all(d)]).then(function(u){const l=u[0],g=u[1],y=u[2],w=u[3],m=u[4],x=[];for(let b=0,T=l.length;b<T;b++){const M=l[b],A=g[b],I=y[b],P=w[b],D=m[b];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();const R=n._createAnimationTracks(M,A,I,P,D);if(R)for(let O=0;O<R.length;O++)x.push(R[O])}return new h.AnimationClip(o,void 0,x)})}createNodeMesh(e){const t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency("mesh",r.mesh).then(function(o){const i=n._getNodeRef(n.meshCache,r.mesh,o);return r.weights!==void 0&&i.traverse(function(a){if(a.isMesh)for(let c=0,f=r.weights.length;c<f;c++)a.morphTargetInfluences[c]=r.weights[c]}),i})}loadNode(e){const t=this.json,n=this,r=t.nodes[e],o=n._loadNodeShallow(e),i=[],a=r.children||[];for(let f=0,d=a.length;f<d;f++)i.push(n.getDependency("node",a[f]));const c=r.skin===void 0?Promise.resolve(null):n.getDependency("skin",r.skin);return Promise.all([o,Promise.all(i),c]).then(function(f){const d=f[0],u=f[1],l=f[2];l!==null&&d.traverse(function(g){g.isSkinnedMesh&&g.bind(l,No)});for(let g=0,y=u.length;g<y;g++)d.add(u[g]);return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],i=o.name?r.createUniqueName(o.name):"",a=[],c=r._invokeOne(function(f){return f.createNodeMesh&&f.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(r.getDependency("camera",o.camera).then(function(f){return r._getNodeRef(r.cameraCache,o.camera,f)})),r._invokeAll(function(f){return f.createNodeAttachment&&f.createNodeAttachment(e)}).forEach(function(f){a.push(f)}),this.nodeCache[e]=Promise.all(a).then(function(f){let d;if(o.isBone===!0?d=new h.Bone:f.length>1?d=new h.Group:f.length===1?d=f[0]:d=new h.Object3D,d!==f[0])for(let u=0,l=f.length;u<l;u++)d.add(f[u]);if(o.name&&(d.userData.name=o.name,d.name=i),ot(d,o),o.extensions&&Mt(n,d,o),o.matrix!==void 0){const u=new h.Matrix4;u.fromArray(o.matrix),d.applyMatrix4(u)}else o.translation!==void 0&&d.position.fromArray(o.translation),o.rotation!==void 0&&d.quaternion.fromArray(o.rotation),o.scale!==void 0&&d.scale.fromArray(o.scale);if(!r.associations.has(d))r.associations.set(d,{});else if(o.mesh!==void 0&&r.meshCache.refs[o.mesh]>1){const u=r.associations.get(d);r.associations.set(d,{...u})}return r.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],r=this,o=new h.Group;n.name&&(o.name=r.createUniqueName(n.name)),ot(o,n),n.extensions&&Mt(t,o,n);const i=n.nodes||[],a=[];for(let c=0,f=i.length;c<f;c++)a.push(r.getDependency("node",i[c]));return Promise.all(a).then(function(c){for(let d=0,u=c.length;d<u;d++)o.add(c[d]);const f=d=>{const u=new Map;for(const[l,g]of r.associations)(l instanceof h.Material||l instanceof h.Texture)&&u.set(l,g);return d.traverse(l=>{const g=r.associations.get(l);g!=null&&u.set(l,g)}),u};return r.associations=f(o),o})}_createAnimationTracks(e,t,n,r,o){const i=[],a=e.name?e.name:e.uuid,c=[];pt[o.path]===pt.weights?e.traverse(function(l){l.morphTargetInfluences&&c.push(l.name?l.name:l.uuid)}):c.push(a);let f;switch(pt[o.path]){case pt.weights:f=h.NumberKeyframeTrack;break;case pt.rotation:f=h.QuaternionKeyframeTrack;break;case pt.translation:case pt.scale:f=h.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:f=h.NumberKeyframeTrack;break;case 2:case 3:default:f=h.VectorKeyframeTrack;break}break}const d=r.interpolation!==void 0?Po[r.interpolation]:h.InterpolateLinear,u=this._getArrayFromAccessor(n);for(let l=0,g=c.length;l<g;l++){const y=new f(c[l]+"."+pt[o.path],t.array,u,d);r.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),i.push(y)}return i}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=hr(t.constructor),r=new Float32Array(t.length);for(let o=0,i=t.length;o<i;o++)r[o]=t[o]*n;t=r}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const r=this instanceof h.QuaternionKeyframeTrack?Co:li;return new r(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function zo(s,e,t){const n=e.attributes,r=new h.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,f=a.max;if(c!==void 0&&f!==void 0){if(r.set(new h.Vector3(c[0],c[1],c[2]),new h.Vector3(f[0],f[1],f[2])),a.normalized){const d=hr(Rt[a.componentType]);r.min.multiplyScalar(d),r.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const a=new h.Vector3,c=new h.Vector3;for(let f=0,d=o.length;f<d;f++){const u=o[f];if(u.POSITION!==void 0){const l=t.json.accessors[u.POSITION],g=l.min,y=l.max;if(g!==void 0&&y!==void 0){if(c.setX(Math.max(Math.abs(g[0]),Math.abs(y[0]))),c.setY(Math.max(Math.abs(g[1]),Math.abs(y[1]))),c.setZ(Math.max(Math.abs(g[2]),Math.abs(y[2]))),l.normalized){const w=hr(Rt[l.componentType]);c.multiplyScalar(w)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(a)}s.boundingBox=r;const i=new h.Sphere;r.getCenter(i.center),i.radius=r.min.distanceTo(r.max)/2,s.boundingSphere=i}function fi(s,e,t){const n=e.attributes,r=[];function o(i,a){return t.getDependency("accessor",i).then(function(c){s.setAttribute(a,c)})}for(const i in n){const a=cr[i]||i.toLowerCase();a in s.attributes||r.push(o(n[i],a))}if(e.indices!==void 0&&!s.index){const i=t.getDependency("accessor",e.indices).then(function(a){s.setIndex(a)});r.push(i)}return h.ColorManagement.workingColorSpace!==h.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${h.ColorManagement.workingColorSpace}" not supported.`),ot(s,e),zo(s,e,t),Promise.all(r).then(function(){return e.targets!==void 0?Fo(s,e.targets,t):s})}class Bo{constructor(){this.loadingManager=new S.LoadingManager,this.loader=new no(this.loadingManager)}async load(e){try{return new Promise(t=>{this.loader.load(e,n=>{var o;const r={scene:new Fe(n.scene),animations:this.convertAnimations(n.animations),cameras:(o=n.cameras)==null?void 0:o.map(i=>{const a=i instanceof S.PerspectiveCamera,c=i instanceof S.OrthographicCamera;return{name:i.name,type:i.type,fov:a?i.fov:void 0,aspect:a?i.aspect:void 0,near:a||c?i.near:.1,far:a||c?i.far:1e3}}),userData:n.userData};t(W.ok(r))},n=>{n.total>0},n=>{t(W.err(new H("Failed to load GLTF model",te.MODEL_LOAD_FAILED,{url:e,originalError:n})))})})}catch(t){return W.err(new H("Failed to initiate model loading",te.MODEL_LOAD_FAILED,{url:e,originalError:t}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}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 S.VectorKeyframeTrack?"vector":e instanceof S.QuaternionKeyframeTrack?"quaternion":e instanceof S.NumberKeyframeTrack?"number":e instanceof S.BooleanKeyframeTrack?"boolean":"number"}}class di{static createLoader(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();switch(t){case"gltf":case"glb":return new Bo;default:throw new H(`Unsupported file format: ${t}`,te.UNSUPPORTED_FORMAT,{url:e,extension:t})}}}const pi={type:"change"},fr={type:"start"},mi={type:"end"},wn=new h.Ray,gi=new h.Plane,Uo=Math.cos(70*h.MathUtils.DEG2RAD),Me=new h.Vector3,Le=2*Math.PI,ce={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},dr=1e-6;class vi extends h.Controls{constructor(e,t=null){super(e,t),this.state=ce.NONE,this.target=new h.Vector3,this.cursor=new h.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:h.MOUSE.ROTATE,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.PAN},this.touches={ONE:h.TOUCH.ROTATE,TWO:h.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 h.Vector3,this._lastQuaternion=new h.Quaternion,this._lastTargetPosition=new h.Vector3,this._quat=new h.Quaternion().setFromUnitVectors(e.up,new h.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new h.Spherical,this._sphericalDelta=new h.Spherical,this._scale=1,this._panOffset=new h.Vector3,this._rotateStart=new h.Vector2,this._rotateEnd=new h.Vector2,this._rotateDelta=new h.Vector2,this._panStart=new h.Vector2,this._panEnd=new h.Vector2,this._panDelta=new h.Vector2,this._dollyStart=new h.Vector2,this._dollyEnd=new h.Vector2,this._dollyDelta=new h.Vector2,this._dollyDirection=new h.Vector3,this._mouse=new h.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Go.bind(this),this._onPointerDown=Eo.bind(this),this._onPointerUp=Vo.bind(this),this._onContextMenu=Xo.bind(this),this._onMouseWheel=qo.bind(this),this._onKeyDown=Zo.bind(this),this._onTouchStart=Yo.bind(this),this._onTouchMove=Ko.bind(this),this._onMouseDown=Wo.bind(this),this._onMouseMove=jo.bind(this),this._interceptControlDown=$o.bind(this),this._interceptControlUp=Qo.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(pi),this.update(),this.state=ce.NONE}update(e=null){const t=this.object.position;Me.copy(t).sub(this.target),Me.applyQuaternion(this._quat),this._spherical.setFromVector3(Me),this.autoRotate&&this.state===ce.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,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=Le:n>Math.PI&&(n-=Le),r<-Math.PI?r+=Le:r>Math.PI&&(r-=Le),n<=r?this._spherical.theta=Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+r)/2?Math.max(n,this._spherical.theta):Math.min(r,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 o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=i!=this._spherical.radius}if(Me.setFromSpherical(this._spherical),Me.applyQuaternion(this._quatInverse),t.copy(this.target).add(Me),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 i=null;if(this.object.isPerspectiveCamera){const a=Me.length();i=this._clampDistance(a*this._scale);const c=a-i;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new h.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(),o=c!==this.object.zoom;const f=new h.Vector3(this._mouse.x,this._mouse.y,0);f.unproject(this.object),this.object.position.sub(f).add(a),this.object.updateMatrixWorld(),i=Me.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(wn.origin.copy(this.object.position),wn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(wn.direction))<Uo?this.object.lookAt(this.target):(gi.setFromNormalAndCoplanarPoint(this.object.up,this.target),wn.intersectPlane(gi,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>dr||8*(1-this._lastQuaternion.dot(this.object.quaternion))>dr||this._lastTargetPosition.distanceToSquared(this.target)>dr?(this.dispatchEvent(pi),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Le/60*this.autoRotateSpeed*e:Le/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){Me.setFromMatrixColumn(t,0),Me.multiplyScalar(-e),this._panOffset.add(Me)}_panUp(e,t){this.screenSpacePanning===!0?Me.setFromMatrixColumn(t,1):(Me.setFromMatrixColumn(t,0),Me.crossVectors(this.object.up,Me)),Me.multiplyScalar(e),this._panOffset.add(Me)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;Me.copy(r).sub(this.target);let o=Me.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/n.clientHeight,this.object.matrix),this._panUp(2*t*o/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(),r=e-n.left,o=t-n.top,i=n.width,a=n.height;this._mouse.x=r/i*2-1,this._mouse.y=-(o/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(Le*this._rotateDelta.x/t.clientHeight),this._rotateUp(Le*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(Le*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(-Le*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(Le*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(-Le*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),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_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),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,o=Math.sqrt(n*n+r*r);this._dollyStart.set(0,o)}_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),r=.5*(e.pageX+n.x),o=.5*(e.pageY+n.y);this._rotateEnd.set(r,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Le*this._rotateDelta.x/t.clientHeight),this._rotateUp(Le*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),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}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,r=e.pageY-t.y,o=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,o),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 i=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(i,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 h.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 Eo(s){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(s.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(s)&&(this._addPointer(s),s.pointerType==="touch"?this._onTouchStart(s):this._onMouseDown(s)))}function Go(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function Vo(s){switch(this._removePointer(s),this._pointers.length){case 0:this.domElement.releasePointerCapture(s.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(mi),this.state=ce.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 Wo(s){let e;switch(s.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 h.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(s),this.state=ce.DOLLY;break;case h.MOUSE.ROTATE:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=ce.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=ce.ROTATE}break;case h.MOUSE.PAN:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=ce.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=ce.PAN}break;default:this.state=ce.NONE}this.state!==ce.NONE&&this.dispatchEvent(fr)}function jo(s){switch(this.state){case ce.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(s);break;case ce.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(s);break;case ce.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(s);break}}function qo(s){this.enabled===!1||this.enableZoom===!1||this.state!==ce.NONE||(s.preventDefault(),this.dispatchEvent(fr),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(mi))}function Zo(s){this.enabled!==!1&&this._handleKeyDown(s)}function Yo(s){switch(this._trackPointer(s),this._pointers.length){case 1:switch(this.touches.ONE){case h.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(s),this.state=ce.TOUCH_ROTATE;break;case h.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(s),this.state=ce.TOUCH_PAN;break;default:this.state=ce.NONE}break;case 2:switch(this.touches.TWO){case h.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(s),this.state=ce.TOUCH_DOLLY_PAN;break;case h.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(s),this.state=ce.TOUCH_DOLLY_ROTATE;break;default:this.state=ce.NONE}break;default:this.state=ce.NONE}this.state!==ce.NONE&&this.dispatchEvent(fr)}function Ko(s){switch(this._trackPointer(s),this.state){case ce.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(s),this.update();break;case ce.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(s),this.update();break;case ce.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(s),this.update();break;case ce.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(s),this.update();break;default:this.state=ce.NONE}}function Xo(s){this.enabled!==!1&&s.preventDefault()}function $o(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Qo(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Jo extends vi{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:h.MOUSE.PAN,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.ROTATE},this.touches={ONE:h.TOUCH.PAN,TWO:h.TOUCH.DOLLY_ROTATE}}}class yi{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()}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}getThreeControls(){return this.controls}}class xi extends yi{constructor(e,t){const n=new vi(e,t);super(n),this.orbitControls=n}get type(){return"orbit"}get autoRotate(){return this.orbitControls.autoRotate}set autoRotate(e){this.orbitControls.autoRotate=e}get autoRotateSpeed(){return this.orbitControls.autoRotateSpeed}set autoRotateSpeed(e){this.orbitControls.autoRotateSpeed=e}}class bi extends yi{constructor(e,t){const n=new Jo(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const pn=class pn{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.getHeight(e)+this.getBevelSize(e))}};pn.HEIGHT_RATIO=.075,pn.BEVEL_RATIO=.25,pn.GAP_FACTOR=1.05;let At=pn;var at=(s=>(s.SQUARE_WIRE="square_wire",s.HEXAGONAL_WIRE="hexagonal_wire",s.HEXAGONAL_GLASS="hexagonal_glass",s.STONE_TILES="stone_tiles",s.CUSTOM="custom",s))(at||{});class Ho{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,r=new S.Color(e.color||8947848),o=new S.Color(e.centerLineColor||e.color||4473924),i=new S.GridHelper(t,n,o,r);if(e.opacity!==void 0&&e.opacity<1){const a=i.material;a.transparent=!0,a.opacity=e.opacity}return i}dispose(){}}class ea{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new S.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)||Math.floor(e.divisions/2),r=e.size/(n*2),o=new S.Color(e.color||8947848),i=e.opacity||.4,a=new S.LineBasicMaterial({color:o,transparent:!0,opacity:i}),c=r*Math.sqrt(3),f=r*2;for(let u=-n;u<=n;u++){const l=Math.max(-n,-u-n),g=Math.min(n,-u+n);for(let y=l;y<=g;y++){const w=c*(u+y/2),m=f*.75*y,x=[],b=Math.PI*2/6;for(let A=0;A<=6;A++){const I=A*b+Math.PI/6,P=w+r*Math.cos(I),D=m+r*Math.sin(I);x.push(new S.Vector3(P,0,D))}const T=new S.BufferGeometry().setFromPoints(x),M=new S.Line(T,a);t.add(M)}}return t}dispose(){}}class ta{constructor(e,t,n){this.position=e,this.size=t,this.color=n,this.height=At.getHeight(this.size),this.bevel=At.getBevelSize(this.size)}createMesh(){const e=new S.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let f=0;f<6;f++){const d=t*Math.cos(f*n),u=t*Math.sin(f*n);f===0?e.moveTo(d,u):e.lineTo(d,u)}e.closePath();const r={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:128},o=new S.ExtrudeGeometry(e,r),i=new S.MeshPhysicalMaterial({color:new S.Color(16777215),metalness:0,roughness:.15,transparent:!0,transmission:1,thickness:.4,ior:1.5,opacity:1,clearcoat:1,clearcoatRoughness:.05,sheen:1,sheenColor:new S.Color(16777215),envMapIntensity:1}),a=new S.Mesh(o,i);a.receiveShadow=!0;const c=new S.Group;return c.add(a),c.position.set(this.position.x,this.position.y,this.position.z),c.rotation.x=Math.PI/2,c.rotation.z=Math.PI/6,c}}class na{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var f,d;const t=new S.Group,n=((f=e.styleOptions)==null?void 0:f.hexRadius)||Math.floor(e.divisions/2),r=((d=e.styleOptions)==null?void 0:d.tileSize)||1,o=String(e.color||"#ffffff"),i=At.getGridSpacing(r),a=i.width,c=i.height;for(let u=-n;u<=n;u++){const l=Math.max(-n,-u-n),g=Math.min(n,-u+n);for(let y=l;y<=g;y++){const w=a*(u+y/2),m=c*.75*y,x=At.getYPosition(r),T=new ta(new S.Vector3(w,x,m),r,o).createMesh();t.add(T)}}return t}dispose(){}}class ra{constructor(){this.name="Stone Tile Grid",this.textureLoader=new S.TextureLoader,this.loadedTextures=new Map}createGrid(e){var g,y,w,m;const t=new S.Group,n=e.size,r=e.divisions,o=n/r,i=o*.02,a=o-i,c=((g=e.styleOptions)==null?void 0:g.height)||o*.05,f=((y=e.styleOptions)==null?void 0:y.bevelSize)||c*.2,d=((w=e.styleOptions)==null?void 0:w.randomHeight)||!1,u=((m=e.styleOptions)==null?void 0:m.randomRotation)||!1,l=this.createStoneMaterial(e);for(let x=0;x<r;x++)for(let b=0;b<r;b++){const T=(x-r/2)*o+o/2,M=(b-r/2)*o+o/2,A=d?c*(.8+Math.random()*.4):c,I=new S.Shape,P=a/2;I.moveTo(-P,-P),I.lineTo(P,-P),I.lineTo(P,P),I.lineTo(-P,P),I.closePath();const D={depth:A,bevelEnabled:!0,bevelSize:f,bevelThickness:f,bevelSegments:2},R=new S.ExtrudeGeometry(I,D);R.rotateX(-Math.PI/2);const O=new S.Mesh(R,l);O.position.set(T,-A/2,M),O.castShadow=!0,O.receiveShadow=!0,u&&(O.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(O)}return t}createStoneMaterial(e){var i,a,c,f,d;const t=new S.Color(e.color||8421504),n=((i=e.styleOptions)==null?void 0:i.metalness)||0,r=((a=e.styleOptions)==null?void 0:a.roughness)||.8,o={color:t,metalness:n,roughness:r};if((c=e.styleOptions)!=null&&c.texture){const u=this.loadTexture(e.styleOptions.texture);u&&(o.map=u,u.wrapS=u.wrapT=S.RepeatWrapping,u.repeat.set(1,1))}if((f=e.styleOptions)!=null&&f.normalMap){const u=this.loadTexture(e.styleOptions.normalMap);u&&(o.normalMap=u,u.wrapS=u.wrapT=S.RepeatWrapping,u.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.roughnessMap){const u=this.loadTexture(e.styleOptions.roughnessMap);u&&(o.roughnessMap=u,u.wrapS=u.wrapT=S.RepeatWrapping,u.repeat.set(1,1))}return new S.MeshStandardMaterial(o)}loadTexture(e){if(this.loadedTextures.has(e))return this.loadedTextures.get(e)||null;try{const t=this.textureLoader.load(e);return this.loadedTextures.set(e,t),t}catch(t){return console.warn("Failed to load texture:",e,t),null}}dispose(){this.loadedTextures.forEach(e=>{e.dispose()}),this.loadedTextures.clear()}}const ei=class ei{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 o=this.gridStyles.get(at.SQUARE_WIRE);if(!o)throw new Error("Square wire grid style not found");return o.createGrid(t)}const r=n.createGrid(t);return r.name=`Grid_${e}`,r}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()}};ei.gridStyles=new Map([[at.SQUARE_WIRE,new Ho],[at.HEXAGONAL_WIRE,new ea],[at.HEXAGONAL_GLASS,new na],[at.STONE_TILES,new ra]]);let _n=ei;class ia{addHelpers(e,t){try{if(!(e instanceof St))return W.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene();if(t.grid){const r=n.userData,o=typeof t.grid=="object"?t.grid:null,i={enabled:!0,color:(o==null?void 0:o.colorGrid)||t.gridColor||"#AAAAAA",type:o!=null&&o.type?o.type:at.HEXAGONAL_GLASS,opacity:o==null?void 0:o.opacity,styleOptions:o==null?void 0:o.styleOptions};if(n.userData={...r,gridOptions:i},o!=null&&o.size||o!=null&&o.divisions){const a=i.type||at.HEXAGONAL_GLASS,c=o.size||10,f=o.divisions||10,d={size:c,divisions:f,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:Math.floor(f/2),tileSize:1,...i.styleOptions}},u=_n.createGrid(a,d);u.userData.isGrid=!0,u.userData.isDefaultGrid=!0,n.add(u)}}if(t.axes){const r=t.axesSize||5,o=new S.AxesHelper(r);n.add(o)}return W.ok(void 0)}catch(n){return W.err(new H("Failed to add helpers to scene",te.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}addDynamicGrid(e,t,n=1.2){try{if(!(e instanceof St))return W.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const r=e.getThreeScene(),o=r.userData,i=o==null?void 0:o.gridOptions;if(!(i!=null&&i.enabled))return W.ok(void 0);const a=[];r.traverse(I=>{var P,D,R;((P=I.userData)!=null&&P.isGrid||(D=I.userData)!=null&&D.isHexGrid||(R=I.userData)!=null&&R.isDefaultGrid)&&a.push(I)}),a.forEach(I=>r.remove(I));let c;t instanceof Fe||"getThreeObject"in t&&typeof t.getThreeObject=="function"?c=t.getThreeObject():c=t;const d=new S.Box3().setFromObject(c).getSize(new S.Vector3),l=1,y=At.getGridSpacing(l).width,w=Math.max(d.x,d.z)*n;let m=0,x=y;for(;x<w&&m<20;)m++,x+=2*y;w<y*.8?m=0:m<3&&w>y*2&&(m=3);const b=i.type||at.HEXAGONAL_GLASS,M={size:Math.max(d.x,d.z)*n,divisions:m*2+1,color:i.color,opacity:i.opacity,styleOptions:{hexRadius:m,tileSize:l,...i.styleOptions}},A=_n.createGrid(b,M);return A.userData.isGrid=!0,A.userData.isHexGrid=!0,r.add(A),W.ok(void 0)}catch(r){return W.err(new H("Failed to add dynamic grid",te.SCENE_OPERATION_FAILED,{originalError:r}))}}addLighting(e,t){try{if(!(e instanceof St))return W.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene();if(t.ambient){const r=new S.Color(t.ambient.color||"#404040"),o=t.ambient.intensity??Math.PI,i=new S.AmbientLight(r,o);n.add(i)}if(t.hemisphere){const r=new S.Color(t.hemisphere.skyColor||"#ffffbb"),o=new S.Color(t.hemisphere.groundColor||"#080820"),i=t.hemisphere.intensity??1,a=new S.HemisphereLight(r,o,i);n.add(a)}if(t.directional){const r=new S.Color(t.directional.color||"#ffffff"),o=t.directional.intensity??Math.PI,i=new S.DirectionalLight(r,o);if(t.directional.position){const a=t.directional.position;if(a instanceof S.Vector3)i.position.copy(a);else if(Array.isArray(a))i.position.set(a[0],a[1],a[2]);else if(typeof a=="object"&&"x"in a&&"y"in a&&"z"in a){const c=a;i.position.set(c.x,c.y,c.z)}}else i.position.set(6,6,6);if(t.directional.castShadow&&(i.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(i.shadow.mapSize.width=a.mapSize.width,i.shadow.mapSize.height=a.mapSize.height),a.camera){const c=i.shadow.camera;a.camera.near!==void 0&&(c.near=a.camera.near),a.camera.far!==void 0&&(c.far=a.camera.far),a.camera.left!==void 0&&(c.left=a.camera.left),a.camera.right!==void 0&&(c.right=a.camera.right),a.camera.top!==void 0&&(c.top=a.camera.top),a.camera.bottom!==void 0&&(c.bottom=a.camera.bottom)}a.bias!==void 0&&(i.shadow.bias=a.bias),a.radius!==void 0&&(i.shadow.radius=a.radius)}i.target.position.set(0,0,0),n.add(i),n.add(i.target),i.shadow&&i.shadow.camera.updateProjectionMatrix()}return W.ok(void 0)}catch(n){return W.err(new H("Failed to add lighting to scene",te.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof St))return W.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene(),r=document.createElement("canvas");r.width=2,r.height=512;const o=r.getContext("2d");if(!o)return W.err(new H("Failed to create canvas context",te.SCENE_OPERATION_FAILED));const i=o.createLinearGradient(0,0,0,r.height);i.addColorStop(0,t.topColor),i.addColorStop(1,t.bottomColor),o.fillStyle=i,o.fillRect(0,0,r.width,r.height);const a=new S.CanvasTexture(r);return a.needsUpdate=!0,n.background=a,W.ok(void 0)}catch(n){return W.err(new H("Failed to create gradient background",te.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}fitCameraToObject(e,t,n){try{let r;e instanceof Fe||"getThreeObject"in e&&typeof e.getThreeObject=="function"?r=e.getThreeObject():r=e;let o;t instanceof sr||"getThreeCamera"in t&&typeof t.getThreeCamera=="function"?o=t.getThreeCamera():o=t;let i;n instanceof xi||n instanceof bi||"getThreeControls"in n&&typeof n.getThreeControls=="function"?i=n.getThreeControls():i=n;const a=new S.Box3().setFromObject(r),c=a.getCenter(new S.Vector3),f=a.getSize(new S.Vector3),d=Math.max(f.x,f.y,f.z);let u;"fov"in o?u=o.fov*(Math.PI/180):u=50*(Math.PI/180);let l=Math.abs(d/2/Math.tan(u/2));l*=2;const g=-Math.PI/4,y=Math.PI/8,w=c.x+l*Math.sin(g)*Math.cos(y),m=c.y+l*Math.sin(y),x=c.z+l*Math.cos(g)*Math.cos(y);return o.position.set(w,m,x),o.lookAt(c),o.updateProjectionMatrix(),i&&i.target&&(i.target.copy(c),i.update()),W.ok(void 0)}catch(r){return W.err(new H("Failed to fit camera to object",te.CAMERA_INIT_FAILED,{originalError:r}))}}}const wi=0,sa=1,_i=2,Ti=2,pr=1.25,Si=1,mt=6*4+4+4,Tn=65535,oa=Math.pow(2,-24),mr=Symbol("SKIP_GENERATION");function Mi(s){return s.index?s.index.count:s.attributes.position.count}function Ot(s){return Mi(s)/3}function Ai(s,e=ArrayBuffer){return s>65535?new Uint32Array(new e(4*s)):new Uint16Array(new e(2*s))}function aa(s,e){if(!s.index){const t=s.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=Ai(t,n);s.setIndex(new h.BufferAttribute(r,1));for(let o=0;o<t;o++)r[o]=o}}function Ii(s,e){const t=Ot(s),n=e||s.drawRange,r=n.start/3,o=(n.start+n.count)/3,i=Math.max(0,r),a=Math.min(t,o)-i;return[{offset:Math.floor(i),count:Math.floor(a)}]}function Ci(s,e){if(!s.groups||!s.groups.length)return Ii(s,e);const t=[],n=new Set,r=e||s.drawRange,o=r.start/3,i=(r.start+r.count)/3;for(const c of s.groups){const f=c.start/3,d=(c.start+c.count)/3;n.add(Math.max(o,f)),n.add(Math.min(i,d))}const a=Array.from(n.values()).sort((c,f)=>c-f);for(let c=0;c<a.length-1;c++){const f=a[c],d=a[c+1];t.push({offset:Math.floor(f),count:Math.floor(d-f)})}return t}function ca(s,e){const t=Ot(s),n=Ci(s,e).sort((i,a)=>i.offset-a.offset),r=n[n.length-1];r.count=Math.min(t-r.offset,r.count);let o=0;return n.forEach(({count:i})=>o+=i),t!==o}function gr(s,e,t,n,r){let o=1/0,i=1/0,a=1/0,c=-1/0,f=-1/0,d=-1/0,u=1/0,l=1/0,g=1/0,y=-1/0,w=-1/0,m=-1/0;for(let x=e*6,b=(e+t)*6;x<b;x+=6){const T=s[x+0],M=s[x+1],A=T-M,I=T+M;A<o&&(o=A),I>c&&(c=I),T<u&&(u=T),T>y&&(y=T);const P=s[x+2],D=s[x+3],R=P-D,O=P+D;R<i&&(i=R),O>f&&(f=O),P<l&&(l=P),P>w&&(w=P);const k=s[x+4],L=s[x+5],V=k-L,G=k+L;V<a&&(a=V),G>d&&(d=G),k<g&&(g=k),k>m&&(m=k)}n[0]=o,n[1]=i,n[2]=a,n[3]=c,n[4]=f,n[5]=d,r[0]=u,r[1]=l,r[2]=g,r[3]=y,r[4]=w,r[5]=m}function la(s,e=null,t=null,n=null){const r=s.attributes.position,o=s.index?s.index.array:null,i=Ot(s),a=r.normalized;let c;e===null?(c=new Float32Array(i*6*4),t=0,n=i):(c=e,t=t||0,n=n||i);const f=r.array,d=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const l=["getX","getY","getZ"];for(let g=t;g<t+n;g++){const y=g*3,w=g*6;let m=y+0,x=y+1,b=y+2;o&&(m=o[m],x=o[x],b=o[b]),a||(m=m*u+d,x=x*u+d,b=b*u+d);for(let T=0;T<3;T++){let M,A,I;a?(M=r[l[T]](m),A=r[l[T]](x),I=r[l[T]](b)):(M=f[m+T],A=f[x+T],I=f[b+T]);let P=M;A<P&&(P=A),I<P&&(P=I);let D=M;A>D&&(D=A),I>D&&(D=I);const R=(D-P)/2,O=T*2;c[w+O+0]=P+R,c[w+O+1]=R+(Math.abs(P)+R)*oa}}return c}function be(s,e,t){return t.min.x=e[s],t.min.y=e[s+1],t.min.z=e[s+2],t.max.x=e[s+3],t.max.y=e[s+4],t.max.z=e[s+5],t}function Pi(s){let e=-1,t=-1/0;for(let n=0;n<3;n++){const r=s[n+3]-s[n];r>t&&(t=r,e=n)}return e}function Di(s,e){e.set(s)}function Fi(s,e,t){let n,r;for(let o=0;o<3;o++){const i=o+3;n=s[o],r=e[o],t[o]=n<r?n:r,n=s[i],r=e[i],t[i]=n>r?n:r}}function Sn(s,e,t){for(let n=0;n<3;n++){const r=e[s+2*n],o=e[s+2*n+1],i=r-o,a=r+o;i<t[n]&&(t[n]=i),a>t[n+3]&&(t[n+3]=a)}}function tn(s){const e=s[3]-s[0],t=s[4]-s[1],n=s[5]-s[2];return 2*(e*t+t*n+n*e)}const ct=32,ua=(s,e)=>s.candidate-e.candidate,gt=new Array(ct).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Mn=new Float32Array(6);function ha(s,e,t,n,r,o){let i=-1,a=0;if(o===wi)i=Pi(e),i!==-1&&(a=(e[i]+e[i+3])/2);else if(o===sa)i=Pi(s),i!==-1&&(a=fa(t,n,r,i));else if(o===_i){const c=tn(s);let f=pr*r;const d=n*6,u=(n+r)*6;for(let l=0;l<3;l++){const g=e[l],m=(e[l+3]-g)/ct;if(r<ct/4){const x=[...gt];x.length=r;let b=0;for(let M=d;M<u;M+=6,b++){const A=x[b];A.candidate=t[M+2*l],A.count=0;const{bounds:I,leftCacheBounds:P,rightCacheBounds:D}=A;for(let R=0;R<3;R++)D[R]=1/0,D[R+3]=-1/0,P[R]=1/0,P[R+3]=-1/0,I[R]=1/0,I[R+3]=-1/0;Sn(M,t,I)}x.sort(ua);let T=r;for(let M=0;M<T;M++){const A=x[M];for(;M+1<T&&x[M+1].candidate===A.candidate;)x.splice(M+1,1),T--}for(let M=d;M<u;M+=6){const A=t[M+2*l];for(let I=0;I<T;I++){const P=x[I];A>=P.candidate?Sn(M,t,P.rightCacheBounds):(Sn(M,t,P.leftCacheBounds),P.count++)}}for(let M=0;M<T;M++){const A=x[M],I=A.count,P=r-A.count,D=A.leftCacheBounds,R=A.rightCacheBounds;let O=0;I!==0&&(O=tn(D)/c);let k=0;P!==0&&(k=tn(R)/c);const L=Si+pr*(O*I+k*P);L<f&&(i=l,f=L,a=A.candidate)}}else{for(let T=0;T<ct;T++){const M=gt[T];M.count=0,M.candidate=g+m+T*m;const A=M.bounds;for(let I=0;I<3;I++)A[I]=1/0,A[I+3]=-1/0}for(let T=d;T<u;T+=6){let I=~~((t[T+2*l]-g)/m);I>=ct&&(I=ct-1);const P=gt[I];P.count++,Sn(T,t,P.bounds)}const x=gt[ct-1];Di(x.bounds,x.rightCacheBounds);for(let T=ct-2;T>=0;T--){const M=gt[T],A=gt[T+1];Fi(M.bounds,A.rightCacheBounds,M.rightCacheBounds)}let b=0;for(let T=0;T<ct-1;T++){const M=gt[T],A=M.count,I=M.bounds,D=gt[T+1].rightCacheBounds;A!==0&&(b===0?Di(I,Mn):Fi(I,Mn,Mn)),b+=A;let R=0,O=0;b!==0&&(R=tn(Mn)/c);const k=r-b;k!==0&&(O=tn(D)/c);const L=Si+pr*(R*b+O*k);L<f&&(i=l,f=L,a=M.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${o} used.`);return{axis:i,pos:a}}function fa(s,e,t,n){let r=0;for(let o=e,i=e+t;o<i;o++)r+=s[o*6+n*2];return r/t}class vr{constructor(){this.boundingData=new Float32Array(6)}}function da(s,e,t,n,r,o){let i=n,a=n+r-1;const c=o.pos,f=o.axis*2;for(;;){for(;i<=a&&t[i*6+f]<c;)i++;for(;i<=a&&t[a*6+f]>=c;)a--;if(i<a){for(let d=0;d<3;d++){let u=e[i*3+d];e[i*3+d]=e[a*3+d],e[a*3+d]=u}for(let d=0;d<6;d++){let u=t[i*6+d];t[i*6+d]=t[a*6+d],t[a*6+d]=u}i++,a--}else return i}}function pa(s,e,t,n,r,o){let i=n,a=n+r-1;const c=o.pos,f=o.axis*2;for(;;){for(;i<=a&&t[i*6+f]<c;)i++;for(;i<=a&&t[a*6+f]>=c;)a--;if(i<a){let d=s[i];s[i]=s[a],s[a]=d;for(let u=0;u<6;u++){let l=t[i*6+u];t[i*6+u]=t[a*6+u],t[a*6+u]=l}i++,a--}else return i}}function Re(s,e){return e[s+15]===65535}function Ne(s,e){return e[s+6]}function Be(s,e){return e[s+14]}function We(s){return s+8}function Ue(s,e){return e[s+6]}function yr(s,e){return e[s+7]}function Yh(s){return s}let Ri,nn,An,Oi;const ma=Math.pow(2,32);function xr(s){return"count"in s?1:1+xr(s.left)+xr(s.right)}function ga(s,e,t){return Ri=new Float32Array(t),nn=new Uint32Array(t),An=new Uint16Array(t),Oi=new Uint8Array(t),br(s,e)}function br(s,e){const t=s/4,n=s/2,r="count"in e,o=e.boundingData;for(let i=0;i<6;i++)Ri[t+i]=o[i];if(r)if(e.buffer){const i=e.buffer;Oi.set(new Uint8Array(i),s);for(let a=s,c=s+i.byteLength;a<c;a+=mt){const f=a/2;Re(f,An)||(nn[a/4+6]+=t)}return s+i.byteLength}else{const i=e.offset,a=e.count;return nn[t+6]=i,An[n+14]=a,An[n+15]=Tn,s+mt}else{const i=e.left,a=e.right,c=e.splitAxis;let f;if(f=br(s+mt,i),f/4>ma)throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return nn[t+6]=f/4,f=br(f,a),nn[t+7]=c,f}}function va(s,e){const t=(s.index?s.index.count:s.attributes.position.count)/3,n=t>2**16,r=n?4:2,o=e?new SharedArrayBuffer(t*r):new ArrayBuffer(t*r),i=n?new Uint32Array(o):new Uint16Array(o);for(let a=0,c=i.length;a<c;a++)i[a]=a;return i}function ya(s,e,t,n,r){const{maxDepth:o,verbose:i,maxLeafTris:a,strategy:c,onProgress:f,indirect:d}=r,u=s._indirectBuffer,l=s.geometry,g=l.index?l.index.array:null,y=d?pa:da,w=Ot(l),m=new Float32Array(6);let x=!1;const b=new vr;return gr(e,t,n,b.boundingData,m),M(b,t,n,m),b;function T(A){f&&f(A/w)}function M(A,I,P,D=null,R=0){if(!x&&R>=o&&(x=!0,i&&(console.warn(`MeshBVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`),console.warn(l))),P<=a||R>=o)return T(I+P),A.offset=I,A.count=P,A;const O=ha(A.boundingData,D,e,I,P,c);if(O.axis===-1)return T(I+P),A.offset=I,A.count=P,A;const k=y(u,g,e,I,P,O);if(k===I||k===I+P)T(I+P),A.offset=I,A.count=P;else{A.splitAxis=O.axis;const L=new vr,V=I,G=k-I;A.left=L,gr(e,V,G,L.boundingData,m),M(L,V,G,m,R+1);const Q=new vr,J=k,me=P-G;A.right=Q,gr(e,J,me,Q.boundingData,m),M(Q,J,me,m,R+1)}return A}}function xa(s,e){const t=s.geometry;e.indirect&&(s._indirectBuffer=va(t,e.useSharedArrayBuffer),ca(t,e.range)&&!e.verbose&&console.warn('MeshBVH: Provided geometry contains groups or a range that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.')),s._indirectBuffer||aa(t,e);const n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,r=la(t),o=e.indirect?Ii(t,e.range):Ci(t,e.range);s._roots=o.map(i=>{const a=ya(s,r,i.offset,i.count,e),c=xr(a),f=new n(mt*c);return ga(0,a,f),f})}class lt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,r=-1/0;for(let o=0,i=e.length;o<i;o++){const c=e[o][t];n=c<n?c:n,r=c>r?c:r}this.min=n,this.max=r}setFromPoints(e,t){let n=1/0,r=-1/0;for(let o=0,i=t.length;o<i;o++){const a=t[o],c=e.dot(a);n=c<n?c:n,r=c>r?c:r}this.min=n,this.max=r}isSeparated(e){return this.min>e.max||e.min>this.max}}lt.prototype.setFromBox=function(){const s=new h.Vector3;return function(t,n){const r=n.min,o=n.max;let i=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let f=0;f<=1;f++)for(let d=0;d<=1;d++){s.x=r.x*c+o.x*(1-c),s.y=r.y*f+o.y*(1-f),s.z=r.z*d+o.z*(1-d);const u=t.dot(s);i=Math.min(u,i),a=Math.max(u,a)}this.min=i,this.max=a}}();const ba=function(){const s=new h.Vector3,e=new h.Vector3,t=new h.Vector3;return function(r,o,i){const a=r.start,c=s,f=o.start,d=e;t.subVectors(a,f),s.subVectors(r.end,r.start),e.subVectors(o.end,o.start);const u=t.dot(d),l=d.dot(c),g=d.dot(d),y=t.dot(c),m=c.dot(c)*g-l*l;let x,b;m!==0?x=(u*l-y*g)/m:x=0,b=(u+x*l)/g,i.x=x,i.y=b}}(),wr=function(){const s=new h.Vector2,e=new h.Vector3,t=new h.Vector3;return function(r,o,i,a){ba(r,o,s);let c=s.x,f=s.y;if(c>=0&&c<=1&&f>=0&&f<=1){r.at(c,i),o.at(f,a);return}else if(c>=0&&c<=1){f<0?o.at(0,a):o.at(1,a),r.closestPointToPoint(a,!0,i);return}else if(f>=0&&f<=1){c<0?r.at(0,i):r.at(1,i),o.closestPointToPoint(i,!0,a);return}else{let d;c<0?d=r.start:d=r.end;let u;f<0?u=o.start:u=o.end;const l=e,g=t;if(r.closestPointToPoint(u,!0,e),o.closestPointToPoint(d,!0,t),l.distanceToSquared(u)<=g.distanceToSquared(d)){i.copy(l),a.copy(u);return}else{i.copy(d),a.copy(g);return}}}}(),wa=function(){const s=new h.Vector3,e=new h.Vector3,t=new h.Plane,n=new h.Line3;return function(o,i){const{radius:a,center:c}=o,{a:f,b:d,c:u}=i;if(n.start=f,n.end=d,n.closestPointToPoint(c,!0,s).distanceTo(c)<=a||(n.start=f,n.end=u,n.closestPointToPoint(c,!0,s).distanceTo(c)<=a)||(n.start=d,n.end=u,n.closestPointToPoint(c,!0,s).distanceTo(c)<=a))return!0;const w=i.getPlane(t);if(Math.abs(w.distanceToPoint(c))<=a){const x=w.projectPoint(c,e);if(i.containsPoint(x))return!0}return!1}}(),_a=1e-15;function _r(s){return Math.abs(s)<_a}class Qe extends h.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new h.Vector3),this.satBounds=new Array(4).fill().map(()=>new lt),this.points=[this.a,this.b,this.c],this.sphere=new h.Sphere,this.plane=new h.Plane,this.needsUpdate=!0}intersectsSphere(e){return wa(e,this)}update(){const e=this.a,t=this.b,n=this.c,r=this.points,o=this.satAxes,i=this.satBounds,a=o[0],c=i[0];this.getNormal(a),c.setFromPoints(a,r);const f=o[1],d=i[1];f.subVectors(e,t),d.setFromPoints(f,r);const u=o[2],l=i[2];u.subVectors(t,n),l.setFromPoints(u,r);const g=o[3],y=i[3];g.subVectors(n,e),y.setFromPoints(g,r),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Qe.prototype.closestPointToSegment=function(){const s=new h.Vector3,e=new h.Vector3,t=new h.Line3;return function(r,o=null,i=null){const{start:a,end:c}=r,f=this.points;let d,u=1/0;for(let l=0;l<3;l++){const g=(l+1)%3;t.start.copy(f[l]),t.end.copy(f[g]),wr(t,r,s,e),d=s.distanceToSquared(e),d<u&&(u=d,o&&o.copy(s),i&&i.copy(e))}return this.closestPointToPoint(a,s),d=a.distanceToSquared(s),d<u&&(u=d,o&&o.copy(s),i&&i.copy(a)),this.closestPointToPoint(c,s),d=c.distanceToSquared(s),d<u&&(u=d,o&&o.copy(s),i&&i.copy(c)),Math.sqrt(u)}}(),Qe.prototype.intersectsTriangle=function(){const s=new Qe,e=new Array(3),t=new Array(3),n=new lt,r=new lt,o=new h.Vector3,i=new h.Vector3,a=new h.Vector3,c=new h.Vector3,f=new h.Vector3,d=new h.Line3,u=new h.Line3,l=new h.Line3,g=new h.Vector3;function y(w,m,x){const b=w.points;let T=0,M=-1;for(let A=0;A<3;A++){const{start:I,end:P}=d;I.copy(b[A]),P.copy(b[(A+1)%3]),d.delta(i);const D=_r(m.distanceToPoint(I));if(_r(m.normal.dot(i))&&D){x.copy(d),T=2;break}const R=m.intersectLine(d,g);if(!R&&D&&g.copy(I),(R||D)&&!_r(g.distanceTo(P))){if(T<=1)(T===1?x.start:x.end).copy(g),D&&(M=T);else if(T>=2){(M===1?x.start:x.end).copy(g),T=2;break}if(T++,T===2&&M===-1)break}}return T}return function(m,x=null,b=!1){this.needsUpdate&&this.update(),m.isExtendedTriangle?m.needsUpdate&&m.update():(s.copy(m),s.update(),m=s);const T=this.plane,M=m.plane;if(Math.abs(T.normal.dot(M.normal))>1-1e-10){const A=this.satBounds,I=this.satAxes;t[0]=m.a,t[1]=m.b,t[2]=m.c;for(let R=0;R<4;R++){const O=A[R],k=I[R];if(n.setFromPoints(k,t),O.isSeparated(n))return!1}const P=m.satBounds,D=m.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let R=0;R<4;R++){const O=P[R],k=D[R];if(n.setFromPoints(k,e),O.isSeparated(n))return!1}for(let R=0;R<4;R++){const O=I[R];for(let k=0;k<4;k++){const L=D[k];if(o.crossVectors(O,L),n.setFromPoints(o,e),r.setFromPoints(o,t),n.isSeparated(r))return!1}}return x&&(b||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),x.start.set(0,0,0),x.end.set(0,0,0)),!0}else{const A=y(this,M,u);if(A===1&&m.containsPoint(u.end))return x&&(x.start.copy(u.end),x.end.copy(u.end)),!0;if(A!==2)return!1;const I=y(m,T,l);if(I===1&&this.containsPoint(l.end))return x&&(x.start.copy(l.end),x.end.copy(l.end)),!0;if(I!==2)return!1;if(u.delta(a),l.delta(c),a.dot(c)<0){let V=l.start;l.start=l.end,l.end=V}const P=u.start.dot(a),D=u.end.dot(a),R=l.start.dot(a),O=l.end.dot(a),k=D<R,L=P<O;return P!==O&&R!==D&&k===L?!1:(x&&(f.subVectors(u.start,l.start),f.dot(a)>0?x.start.copy(u.start):x.start.copy(l.start),f.subVectors(u.end,l.end),f.dot(a)<0?x.end.copy(u.end):x.end.copy(l.end)),!0)}}}(),Qe.prototype.distanceToPoint=function(){const s=new h.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),Qe.prototype.distanceToTriangle=function(){const s=new h.Vector3,e=new h.Vector3,t=["a","b","c"],n=new h.Line3,r=new h.Line3;return function(i,a=null,c=null){const f=a||c?n:null;if(this.intersectsTriangle(i,f))return(a||c)&&(a&&f.getCenter(a),c&&f.getCenter(c)),0;let d=1/0;for(let u=0;u<3;u++){let l;const g=t[u],y=i[g];this.closestPointToPoint(y,s),l=y.distanceToSquared(s),l<d&&(d=l,a&&a.copy(s),c&&c.copy(y));const w=this[g];i.closestPointToPoint(w,s),l=w.distanceToSquared(s),l<d&&(d=l,a&&a.copy(w),c&&c.copy(s))}for(let u=0;u<3;u++){const l=t[u],g=t[(u+1)%3];n.set(this[l],this[g]);for(let y=0;y<3;y++){const w=t[y],m=t[(y+1)%3];r.set(i[w],i[m]),wr(n,r,s,e);const x=s.distanceToSquared(e);x<d&&(d=x,a&&a.copy(s),c&&c.copy(e))}}return Math.sqrt(d)}}();class Oe{constructor(e,t,n){this.isOrientedBox=!0,this.min=new h.Vector3,this.max=new h.Vector3,this.matrix=new h.Matrix4,this.invMatrix=new h.Matrix4,this.points=new Array(8).fill().map(()=>new h.Vector3),this.satAxes=new Array(3).fill().map(()=>new h.Vector3),this.satBounds=new Array(3).fill().map(()=>new lt),this.alignedSatBounds=new Array(3).fill().map(()=>new lt),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}}Oe.prototype.update=function(){return function(){const e=this.matrix,t=this.min,n=this.max,r=this.points;for(let f=0;f<=1;f++)for(let d=0;d<=1;d++)for(let u=0;u<=1;u++){const l=1*f|2*d|4*u,g=r[l];g.x=f?n.x:t.x,g.y=d?n.y:t.y,g.z=u?n.z:t.z,g.applyMatrix4(e)}const o=this.satBounds,i=this.satAxes,a=r[0];for(let f=0;f<3;f++){const d=i[f],u=o[f],l=1<<f,g=r[l];d.subVectors(a,g),u.setFromPoints(d,r)}const c=this.alignedSatBounds;c[0].setFromPointsField(r,"x"),c[1].setFromPointsField(r,"y"),c[2].setFromPointsField(r,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),Oe.prototype.intersectsBox=function(){const s=new lt;return function(t){this.needsUpdate&&this.update();const n=t.min,r=t.max,o=this.satBounds,i=this.satAxes,a=this.alignedSatBounds;if(s.min=n.x,s.max=r.x,a[0].isSeparated(s)||(s.min=n.y,s.max=r.y,a[1].isSeparated(s))||(s.min=n.z,s.max=r.z,a[2].isSeparated(s)))return!1;for(let c=0;c<3;c++){const f=i[c],d=o[c];if(s.setFromBox(f,t),d.isSeparated(s))return!1}return!0}}(),Oe.prototype.intersectsTriangle=function(){const s=new Qe,e=new Array(3),t=new lt,n=new lt,r=new h.Vector3;return function(i){this.needsUpdate&&this.update(),i.isExtendedTriangle?i.needsUpdate&&i.update():(s.copy(i),s.update(),i=s);const a=this.satBounds,c=this.satAxes;e[0]=i.a,e[1]=i.b,e[2]=i.c;for(let l=0;l<3;l++){const g=a[l],y=c[l];if(t.setFromPoints(y,e),g.isSeparated(t))return!1}const f=i.satBounds,d=i.satAxes,u=this.points;for(let l=0;l<3;l++){const g=f[l],y=d[l];if(t.setFromPoints(y,u),g.isSeparated(t))return!1}for(let l=0;l<3;l++){const g=c[l];for(let y=0;y<4;y++){const w=d[y];if(r.crossVectors(g,w),t.setFromPoints(r,e),n.setFromPoints(r,u),t.isSeparated(n))return!1}}return!0}}(),Oe.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}}(),Oe.prototype.distanceToPoint=function(){const s=new h.Vector3;return function(t){return this.closestPointToPoint(t,s),t.distanceTo(s)}}(),Oe.prototype.distanceToBox=function(){const s=["x","y","z"],e=new Array(12).fill().map(()=>new h.Line3),t=new Array(12).fill().map(()=>new h.Line3),n=new h.Vector3,r=new h.Vector3;return function(i,a=0,c=null,f=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(c||f)&&(i.getCenter(r),this.closestPointToPoint(r,n),i.closestPointToPoint(n,r),c&&c.copy(n),f&&f.copy(r)),0;const d=a*a,u=i.min,l=i.max,g=this.points;let y=1/0;for(let m=0;m<8;m++){const x=g[m];r.copy(x).clamp(u,l);const b=x.distanceToSquared(r);if(b<y&&(y=b,c&&c.copy(x),f&&f.copy(r),b<d))return Math.sqrt(b)}let w=0;for(let m=0;m<3;m++)for(let x=0;x<=1;x++)for(let b=0;b<=1;b++){const T=(m+1)%3,M=(m+2)%3,A=x<<T|b<<M,I=1<<m|x<<T|b<<M,P=g[A],D=g[I];e[w].set(P,D);const O=s[m],k=s[T],L=s[M],V=t[w],G=V.start,Q=V.end;G[O]=u[O],G[k]=x?u[k]:l[k],G[L]=b?u[L]:l[k],Q[O]=l[O],Q[k]=x?u[k]:l[k],Q[L]=b?u[L]:l[k],w++}for(let m=0;m<=1;m++)for(let x=0;x<=1;x++)for(let b=0;b<=1;b++){r.x=m?l.x:u.x,r.y=x?l.y:u.y,r.z=b?l.z:u.z,this.closestPointToPoint(r,n);const T=r.distanceToSquared(n);if(T<y&&(y=T,c&&c.copy(n),f&&f.copy(r),T<d))return Math.sqrt(T)}for(let m=0;m<12;m++){const x=e[m];for(let b=0;b<12;b++){const T=t[b];wr(x,T,n,r);const M=n.distanceToSquared(r);if(M<y&&(y=M,c&&c.copy(n),f&&f.copy(r),M<d))return Math.sqrt(M)}}return Math.sqrt(y)}}();class Tr{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 Ta extends Tr{constructor(){super(()=>new Qe)}}const je=new Ta;class Sa{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 de=new Sa;let vt,Lt;const Nt=[],In=new Tr(()=>new h.Box3);function Ma(s,e,t,n,r,o){vt=In.getPrimitive(),Lt=In.getPrimitive(),Nt.push(vt,Lt),de.setBuffer(s._roots[e]);const i=Sr(0,s.geometry,t,n,r,o);de.clearBuffer(),In.releasePrimitive(vt),In.releasePrimitive(Lt),Nt.pop(),Nt.pop();const a=Nt.length;return a>0&&(Lt=Nt[a-1],vt=Nt[a-2]),i}function Sr(s,e,t,n,r=null,o=0,i=0){const{float32Array:a,uint16Array:c,uint32Array:f}=de;let d=s*2;if(Re(d,c)){const l=Ne(s,f),g=Be(d,c);return be(s,a,vt),n(l,g,!1,i,o+s,vt)}else{let O=function(L){const{uint16Array:V,uint32Array:G}=de;let Q=L*2;for(;!Re(Q,V);)L=We(L),Q=L*2;return Ne(L,G)},k=function(L){const{uint16Array:V,uint32Array:G}=de;let Q=L*2;for(;!Re(Q,V);)L=Ue(L,G),Q=L*2;return Ne(L,G)+Be(Q,V)};const l=We(s),g=Ue(s,f);let y=l,w=g,m,x,b,T;if(r&&(b=vt,T=Lt,be(y,a,b),be(w,a,T),m=r(b),x=r(T),x<m)){y=g,w=l;const L=m;m=x,x=L,b=T}b||(b=vt,be(y,a,b));const M=Re(y*2,c),A=t(b,M,m,i+1,o+y);let I;if(A===Ti){const L=O(y),G=k(y)-L;I=n(L,G,!0,i+1,o+y,b)}else I=A&&Sr(y,e,t,n,r,o,i+1);if(I)return!0;T=Lt,be(w,a,T);const P=Re(w*2,c),D=t(T,P,x,i+1,o+w);let R;if(D===Ti){const L=O(w),G=k(w)-L;R=n(L,G,!0,i+1,o+w,T)}else R=D&&Sr(w,e,t,n,r,o,i+1);return!!R}}const rn=new h.Vector3,Mr=new h.Vector3;function Aa(s,e,t={},n=0,r=1/0){const o=n*n,i=r*r;let a=1/0,c=null;if(s.shapecast({boundsTraverseOrder:d=>(rn.copy(e).clamp(d.min,d.max),rn.distanceToSquared(e)),intersectsBounds:(d,u,l)=>l<a&&l<i,intersectsTriangle:(d,u)=>{d.closestPointToPoint(e,rn);const l=e.distanceToSquared(rn);return l<a&&(Mr.copy(rn),a=l,c=u),l<o}}),a===1/0)return null;const f=Math.sqrt(a);return t.point?t.point.copy(Mr):t.point=Mr.clone(),t.distance=f,t.faceIndex=c,t}const kt=new h.Vector3,zt=new h.Vector3,Bt=new h.Vector3,Cn=new h.Vector2,Pn=new h.Vector2,Dn=new h.Vector2,Li=new h.Vector3,Ni=new h.Vector3,ki=new h.Vector3,Fn=new h.Vector3;function Ia(s,e,t,n,r,o,i,a){let c;if(o===h.BackSide?c=s.intersectTriangle(n,t,e,!0,r):c=s.intersectTriangle(e,t,n,o!==h.DoubleSide,r),c===null)return null;const f=s.origin.distanceTo(r);return f<i||f>a?null:{distance:f,point:r.clone()}}function Ca(s,e,t,n,r,o,i,a,c,f,d){kt.fromBufferAttribute(e,o),zt.fromBufferAttribute(e,i),Bt.fromBufferAttribute(e,a);const u=Ia(s,kt,zt,Bt,Fn,c,f,d);if(u){n&&(Cn.fromBufferAttribute(n,o),Pn.fromBufferAttribute(n,i),Dn.fromBufferAttribute(n,a),u.uv=h.Triangle.getInterpolation(Fn,kt,zt,Bt,Cn,Pn,Dn,new h.Vector2)),r&&(Cn.fromBufferAttribute(r,o),Pn.fromBufferAttribute(r,i),Dn.fromBufferAttribute(r,a),u.uv1=h.Triangle.getInterpolation(Fn,kt,zt,Bt,Cn,Pn,Dn,new h.Vector2)),t&&(Li.fromBufferAttribute(t,o),Ni.fromBufferAttribute(t,i),ki.fromBufferAttribute(t,a),u.normal=h.Triangle.getInterpolation(Fn,kt,zt,Bt,Li,Ni,ki,new h.Vector3),u.normal.dot(s.direction)>0&&u.normal.multiplyScalar(-1));const l={a:o,b:i,c:a,normal:new h.Vector3,materialIndex:0};h.Triangle.getNormal(kt,zt,Bt,l.normal),u.face=l,u.faceIndex=o}return u}function Rn(s,e,t,n,r,o,i){const a=n*3;let c=a+0,f=a+1,d=a+2;const u=s.index;s.index&&(c=u.getX(c),f=u.getX(f),d=u.getX(d));const{position:l,normal:g,uv:y,uv1:w}=s.attributes,m=Ca(t,l,g,y,w,c,f,d,e,o,i);return m?(m.faceIndex=n,r&&r.push(m),m):null}function _e(s,e,t,n){const r=s.a,o=s.b,i=s.c;let a=e,c=e+1,f=e+2;t&&(a=t.getX(a),c=t.getX(c),f=t.getX(f)),r.x=n.getX(a),r.y=n.getY(a),r.z=n.getZ(a),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c),i.x=n.getX(f),i.y=n.getY(f),i.z=n.getZ(f)}function Pa(s,e,t,n,r,o,i,a){const{geometry:c,_indirectBuffer:f}=s;for(let d=n,u=n+r;d<u;d++)Rn(c,e,t,d,o,i,a)}function Da(s,e,t,n,r,o,i){const{geometry:a,_indirectBuffer:c}=s;let f=1/0,d=null;for(let u=n,l=n+r;u<l;u++){let g;g=Rn(a,e,t,u,null,o,i),g&&g.distance<f&&(d=g,f=g.distance)}return d}function Fa(s,e,t,n,r,o,i){const{geometry:a}=t,{index:c}=a,f=a.attributes.position;for(let d=s,u=e+s;d<u;d++){let l;if(l=d,_e(i,l*3,c,f),i.needsUpdate=!0,n(i,l,r,o))return!0}return!1}function Ra(s,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=s.geometry,n=t.index?t.index.array:null,r=t.attributes.position;let o,i,a,c,f=0;const d=s._roots;for(let l=0,g=d.length;l<g;l++)o=d[l],i=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,f),f+=o.byteLength;function u(l,g,y=!1){const w=l*2;if(a[w+15]===Tn){const x=i[l+6],b=a[w+14];let T=1/0,M=1/0,A=1/0,I=-1/0,P=-1/0,D=-1/0;for(let R=3*x,O=3*(x+b);R<O;R++){let k=n[R];const L=r.getX(k),V=r.getY(k),G=r.getZ(k);L<T&&(T=L),L>I&&(I=L),V<M&&(M=V),V>P&&(P=V),G<A&&(A=G),G>D&&(D=G)}return c[l+0]!==T||c[l+1]!==M||c[l+2]!==A||c[l+3]!==I||c[l+4]!==P||c[l+5]!==D?(c[l+0]=T,c[l+1]=M,c[l+2]=A,c[l+3]=I,c[l+4]=P,c[l+5]=D,!0):!1}else{const x=l+8,b=i[l+6],T=x+g,M=b+g;let A=y,I=!1,P=!1;e?A||(I=e.has(T),P=e.has(M),A=!I&&!P):(I=!0,P=!0);const D=A||I,R=A||P;let O=!1;D&&(O=u(x,g,A));let k=!1;R&&(k=u(b,g,A));const L=O||k;if(L)for(let V=0;V<3;V++){const G=x+V,Q=b+V,J=c[G],me=c[G+3],Ce=c[Q],ge=c[Q+3];c[l+V]=J<Ce?J:Ce,c[l+V+3]=me>ge?me:ge}return L}}}function yt(s,e,t,n,r){let o,i,a,c,f,d;const u=1/t.direction.x,l=1/t.direction.y,g=1/t.direction.z,y=t.origin.x,w=t.origin.y,m=t.origin.z;let x=e[s],b=e[s+3],T=e[s+1],M=e[s+3+1],A=e[s+2],I=e[s+3+2];return u>=0?(o=(x-y)*u,i=(b-y)*u):(o=(b-y)*u,i=(x-y)*u),l>=0?(a=(T-w)*l,c=(M-w)*l):(a=(M-w)*l,c=(T-w)*l),o>c||a>i||((a>o||isNaN(o))&&(o=a),(c<i||isNaN(i))&&(i=c),g>=0?(f=(A-m)*g,d=(I-m)*g):(f=(I-m)*g,d=(A-m)*g),o>d||f>i)?!1:((f>o||o!==o)&&(o=f),(d<i||i!==i)&&(i=d),o<=r&&i>=n)}function Oa(s,e,t,n,r,o,i,a){const{geometry:c,_indirectBuffer:f}=s;for(let d=n,u=n+r;d<u;d++){let l=f?f[d]:d;Rn(c,e,t,l,o,i,a)}}function La(s,e,t,n,r,o,i){const{geometry:a,_indirectBuffer:c}=s;let f=1/0,d=null;for(let u=n,l=n+r;u<l;u++){let g;g=Rn(a,e,t,c?c[u]:u,null,o,i),g&&g.distance<f&&(d=g,f=g.distance)}return d}function Na(s,e,t,n,r,o,i){const{geometry:a}=t,{index:c}=a,f=a.attributes.position;for(let d=s,u=e+s;d<u;d++){let l;if(l=t.resolveTriangleIndex(d),_e(i,l*3,c,f),i.needsUpdate=!0,n(i,l,r,o))return!0}return!1}function ka(s,e,t,n,r,o,i){de.setBuffer(s._roots[e]),Ar(0,s,t,n,r,o,i),de.clearBuffer()}function Ar(s,e,t,n,r,o,i){const{float32Array:a,uint16Array:c,uint32Array:f}=de,d=s*2;if(Re(d,c)){const l=Ne(s,f),g=Be(d,c);Pa(e,t,n,l,g,r,o,i)}else{const l=We(s);yt(l,a,n,o,i)&&Ar(l,e,t,n,r,o,i);const g=Ue(s,f);yt(g,a,n,o,i)&&Ar(g,e,t,n,r,o,i)}}const za=["x","y","z"];function Ba(s,e,t,n,r,o){de.setBuffer(s._roots[e]);const i=Ir(0,s,t,n,r,o);return de.clearBuffer(),i}function Ir(s,e,t,n,r,o){const{float32Array:i,uint16Array:a,uint32Array:c}=de;let f=s*2;if(Re(f,a)){const u=Ne(s,c),l=Be(f,a);return Da(e,t,n,u,l,r,o)}else{const u=yr(s,c),l=za[u],y=n.direction[l]>=0;let w,m;y?(w=We(s),m=Ue(s,c)):(w=Ue(s,c),m=We(s));const b=yt(w,i,n,r,o)?Ir(w,e,t,n,r,o):null;if(b){const A=b.point[l];if(y?A<=i[m+u]:A>=i[m+u+3])return b}const M=yt(m,i,n,r,o)?Ir(m,e,t,n,r,o):null;return b&&M?b.distance<=M.distance?b:M:b||M||null}}const On=new h.Box3,Ut=new Qe,Et=new Qe,sn=new h.Matrix4,zi=new Oe,Ln=new Oe;function Ua(s,e,t,n){de.setBuffer(s._roots[e]);const r=Cr(0,s,t,n);return de.clearBuffer(),r}function Cr(s,e,t,n,r=null){const{float32Array:o,uint16Array:i,uint32Array:a}=de;let c=s*2;if(r===null&&(t.boundingBox||t.computeBoundingBox(),zi.set(t.boundingBox.min,t.boundingBox.max,n),r=zi),Re(c,i)){const d=e.geometry,u=d.index,l=d.attributes.position,g=t.index,y=t.attributes.position,w=Ne(s,a),m=Be(c,i);if(sn.copy(n).invert(),t.boundsTree)return be(s,o,Ln),Ln.matrix.copy(sn),Ln.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:b=>Ln.intersectsBox(b),intersectsTriangle:b=>{b.a.applyMatrix4(n),b.b.applyMatrix4(n),b.c.applyMatrix4(n),b.needsUpdate=!0;for(let T=w*3,M=(m+w)*3;T<M;T+=3)if(_e(Et,T,u,l),Et.needsUpdate=!0,b.intersectsTriangle(Et))return!0;return!1}});for(let x=w*3,b=(m+w)*3;x<b;x+=3){_e(Ut,x,u,l),Ut.a.applyMatrix4(sn),Ut.b.applyMatrix4(sn),Ut.c.applyMatrix4(sn),Ut.needsUpdate=!0;for(let T=0,M=g.count;T<M;T+=3)if(_e(Et,T,g,y),Et.needsUpdate=!0,Ut.intersectsTriangle(Et))return!0}}else{const d=s+8,u=a[s+6];return be(d,o,On),!!(r.intersectsBox(On)&&Cr(d,e,t,n,r)||(be(u,o,On),r.intersectsBox(On)&&Cr(u,e,t,n,r)))}}const Nn=new h.Matrix4,Pr=new Oe,on=new Oe,Ea=new h.Vector3,Ga=new h.Vector3,Va=new h.Vector3,Wa=new h.Vector3;function ja(s,e,t,n={},r={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),Pr.set(e.boundingBox.min,e.boundingBox.max,t),Pr.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,f=a.index,d=e.attributes.position,u=e.index,l=je.getPrimitive(),g=je.getPrimitive();let y=Ea,w=Ga,m=null,x=null;r&&(m=Va,x=Wa);let b=1/0,T=null,M=null;return Nn.copy(t).invert(),on.matrix.copy(Nn),s.shapecast({boundsTraverseOrder:A=>Pr.distanceToBox(A),intersectsBounds:(A,I,P)=>P<b&&P<i?(I&&(on.min.copy(A.min),on.max.copy(A.max),on.needsUpdate=!0),!0):!1,intersectsRange:(A,I)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:D=>on.distanceToBox(D),intersectsBounds:(D,R,O)=>O<b&&O<i,intersectsRange:(D,R)=>{for(let O=D,k=D+R;O<k;O++){_e(g,3*O,u,d),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let L=A,V=A+I;L<V;L++){_e(l,3*L,f,c),l.needsUpdate=!0;const G=l.distanceToTriangle(g,y,m);if(G<b&&(w.copy(y),x&&x.copy(m),b=G,T=L,M=O),G<o)return!0}}}});{const P=Ot(e);for(let D=0,R=P;D<R;D++){_e(g,3*D,u,d),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let O=A,k=A+I;O<k;O++){_e(l,3*O,f,c),l.needsUpdate=!0;const L=l.distanceToTriangle(g,y,m);if(L<b&&(w.copy(y),x&&x.copy(m),b=L,T=O,M=D),L<o)return!0}}}}}),je.releasePrimitive(l),je.releasePrimitive(g),b===1/0?null:(n.point?n.point.copy(w):n.point=w.clone(),n.distance=b,n.faceIndex=T,r&&(r.point?r.point.copy(x):r.point=x.clone(),r.point.applyMatrix4(Nn),w.applyMatrix4(Nn),r.distance=w.sub(r.point).length(),r.faceIndex=M),n)}function qa(s,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=s.geometry,n=t.index?t.index.array:null,r=t.attributes.position;let o,i,a,c,f=0;const d=s._roots;for(let l=0,g=d.length;l<g;l++)o=d[l],i=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,f),f+=o.byteLength;function u(l,g,y=!1){const w=l*2;if(a[w+15]===Tn){const x=i[l+6],b=a[w+14];let T=1/0,M=1/0,A=1/0,I=-1/0,P=-1/0,D=-1/0;for(let R=x,O=x+b;R<O;R++){const k=3*s.resolveTriangleIndex(R);for(let L=0;L<3;L++){let V=k+L;V=n?n[V]:V;const G=r.getX(V),Q=r.getY(V),J=r.getZ(V);G<T&&(T=G),G>I&&(I=G),Q<M&&(M=Q),Q>P&&(P=Q),J<A&&(A=J),J>D&&(D=J)}}return c[l+0]!==T||c[l+1]!==M||c[l+2]!==A||c[l+3]!==I||c[l+4]!==P||c[l+5]!==D?(c[l+0]=T,c[l+1]=M,c[l+2]=A,c[l+3]=I,c[l+4]=P,c[l+5]=D,!0):!1}else{const x=l+8,b=i[l+6],T=x+g,M=b+g;let A=y,I=!1,P=!1;e?A||(I=e.has(T),P=e.has(M),A=!I&&!P):(I=!0,P=!0);const D=A||I,R=A||P;let O=!1;D&&(O=u(x,g,A));let k=!1;R&&(k=u(b,g,A));const L=O||k;if(L)for(let V=0;V<3;V++){const G=x+V,Q=b+V,J=c[G],me=c[G+3],Ce=c[Q],ge=c[Q+3];c[l+V]=J<Ce?J:Ce,c[l+V+3]=me>ge?me:ge}return L}}}function Za(s,e,t,n,r,o,i){de.setBuffer(s._roots[e]),Dr(0,s,t,n,r,o,i),de.clearBuffer()}function Dr(s,e,t,n,r,o,i){const{float32Array:a,uint16Array:c,uint32Array:f}=de,d=s*2;if(Re(d,c)){const l=Ne(s,f),g=Be(d,c);Oa(e,t,n,l,g,r,o,i)}else{const l=We(s);yt(l,a,n,o,i)&&Dr(l,e,t,n,r,o,i);const g=Ue(s,f);yt(g,a,n,o,i)&&Dr(g,e,t,n,r,o,i)}}const Ya=["x","y","z"];function Ka(s,e,t,n,r,o){de.setBuffer(s._roots[e]);const i=Fr(0,s,t,n,r,o);return de.clearBuffer(),i}function Fr(s,e,t,n,r,o){const{float32Array:i,uint16Array:a,uint32Array:c}=de;let f=s*2;if(Re(f,a)){const u=Ne(s,c),l=Be(f,a);return La(e,t,n,u,l,r,o)}else{const u=yr(s,c),l=Ya[u],y=n.direction[l]>=0;let w,m;y?(w=We(s),m=Ue(s,c)):(w=Ue(s,c),m=We(s));const b=yt(w,i,n,r,o)?Fr(w,e,t,n,r,o):null;if(b){const A=b.point[l];if(y?A<=i[m+u]:A>=i[m+u+3])return b}const M=yt(m,i,n,r,o)?Fr(m,e,t,n,r,o):null;return b&&M?b.distance<=M.distance?b:M:b||M||null}}const kn=new h.Box3,Gt=new Qe,Vt=new Qe,an=new h.Matrix4,Bi=new Oe,zn=new Oe;function Xa(s,e,t,n){de.setBuffer(s._roots[e]);const r=Rr(0,s,t,n);return de.clearBuffer(),r}function Rr(s,e,t,n,r=null){const{float32Array:o,uint16Array:i,uint32Array:a}=de;let c=s*2;if(r===null&&(t.boundingBox||t.computeBoundingBox(),Bi.set(t.boundingBox.min,t.boundingBox.max,n),r=Bi),Re(c,i)){const d=e.geometry,u=d.index,l=d.attributes.position,g=t.index,y=t.attributes.position,w=Ne(s,a),m=Be(c,i);if(an.copy(n).invert(),t.boundsTree)return be(s,o,zn),zn.matrix.copy(an),zn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:b=>zn.intersectsBox(b),intersectsTriangle:b=>{b.a.applyMatrix4(n),b.b.applyMatrix4(n),b.c.applyMatrix4(n),b.needsUpdate=!0;for(let T=w,M=m+w;T<M;T++)if(_e(Vt,3*e.resolveTriangleIndex(T),u,l),Vt.needsUpdate=!0,b.intersectsTriangle(Vt))return!0;return!1}});for(let x=w,b=m+w;x<b;x++){const T=e.resolveTriangleIndex(x);_e(Gt,3*T,u,l),Gt.a.applyMatrix4(an),Gt.b.applyMatrix4(an),Gt.c.applyMatrix4(an),Gt.needsUpdate=!0;for(let M=0,A=g.count;M<A;M+=3)if(_e(Vt,M,g,y),Vt.needsUpdate=!0,Gt.intersectsTriangle(Vt))return!0}}else{const d=s+8,u=a[s+6];return be(d,o,kn),!!(r.intersectsBox(kn)&&Rr(d,e,t,n,r)||(be(u,o,kn),r.intersectsBox(kn)&&Rr(u,e,t,n,r)))}}const Bn=new h.Matrix4,Or=new Oe,cn=new Oe,$a=new h.Vector3,Qa=new h.Vector3,Ja=new h.Vector3,Ha=new h.Vector3;function ec(s,e,t,n={},r={},o=0,i=1/0){e.boundingBox||e.computeBoundingBox(),Or.set(e.boundingBox.min,e.boundingBox.max,t),Or.needsUpdate=!0;const a=s.geometry,c=a.attributes.position,f=a.index,d=e.attributes.position,u=e.index,l=je.getPrimitive(),g=je.getPrimitive();let y=$a,w=Qa,m=null,x=null;r&&(m=Ja,x=Ha);let b=1/0,T=null,M=null;return Bn.copy(t).invert(),cn.matrix.copy(Bn),s.shapecast({boundsTraverseOrder:A=>Or.distanceToBox(A),intersectsBounds:(A,I,P)=>P<b&&P<i?(I&&(cn.min.copy(A.min),cn.max.copy(A.max),cn.needsUpdate=!0),!0):!1,intersectsRange:(A,I)=>{if(e.boundsTree){const P=e.boundsTree;return P.shapecast({boundsTraverseOrder:D=>cn.distanceToBox(D),intersectsBounds:(D,R,O)=>O<b&&O<i,intersectsRange:(D,R)=>{for(let O=D,k=D+R;O<k;O++){const L=P.resolveTriangleIndex(O);_e(g,3*L,u,d),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let V=A,G=A+I;V<G;V++){const Q=s.resolveTriangleIndex(V);_e(l,3*Q,f,c),l.needsUpdate=!0;const J=l.distanceToTriangle(g,y,m);if(J<b&&(w.copy(y),x&&x.copy(m),b=J,T=V,M=O),J<o)return!0}}}})}else{const P=Ot(e);for(let D=0,R=P;D<R;D++){_e(g,3*D,u,d),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let O=A,k=A+I;O<k;O++){const L=s.resolveTriangleIndex(O);_e(l,3*L,f,c),l.needsUpdate=!0;const V=l.distanceToTriangle(g,y,m);if(V<b&&(w.copy(y),x&&x.copy(m),b=V,T=O,M=D),V<o)return!0}}}}}),je.releasePrimitive(l),je.releasePrimitive(g),b===1/0?null:(n.point?n.point.copy(w):n.point=w.clone(),n.distance=b,n.faceIndex=T,r&&(r.point?r.point.copy(x):r.point=x.clone(),r.point.applyMatrix4(Bn),w.applyMatrix4(Bn),r.distance=w.sub(r.point).length(),r.faceIndex=M),n)}function tc(){return typeof SharedArrayBuffer<"u"}const ln=new de.constructor,Un=new de.constructor,xt=new Tr(()=>new h.Box3),Wt=new h.Box3,jt=new h.Box3,Lr=new h.Box3,Nr=new h.Box3;let kr=!1;function nc(s,e,t,n){if(kr)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");kr=!0;const r=s._roots,o=e._roots;let i,a=0,c=0;const f=new h.Matrix4().copy(t).invert();for(let d=0,u=r.length;d<u;d++){ln.setBuffer(r[d]),c=0;const l=xt.getPrimitive();be(0,ln.float32Array,l),l.applyMatrix4(f);for(let g=0,y=o.length;g<y&&(Un.setBuffer(o[g]),i=Je(0,0,t,f,n,a,c,0,0,l),Un.clearBuffer(),c+=o[g].length,!i);g++);if(xt.releasePrimitive(l),ln.clearBuffer(),a+=r[d].length,i)break}return kr=!1,i}function Je(s,e,t,n,r,o=0,i=0,a=0,c=0,f=null,d=!1){let u,l;d?(u=Un,l=ln):(u=ln,l=Un);const g=u.float32Array,y=u.uint32Array,w=u.uint16Array,m=l.float32Array,x=l.uint32Array,b=l.uint16Array,T=s*2,M=e*2,A=Re(T,w),I=Re(M,b);let P=!1;if(I&&A)d?P=r(Ne(e,x),Be(e*2,b),Ne(s,y),Be(s*2,w),c,i+e,a,o+s):P=r(Ne(s,y),Be(s*2,w),Ne(e,x),Be(e*2,b),a,o+s,c,i+e);else if(I){const D=xt.getPrimitive();be(e,m,D),D.applyMatrix4(t);const R=We(s),O=Ue(s,y);be(R,g,Wt),be(O,g,jt);const k=D.intersectsBox(Wt),L=D.intersectsBox(jt);P=k&&Je(e,R,n,t,r,i,o,c,a+1,D,!d)||L&&Je(e,O,n,t,r,i,o,c,a+1,D,!d),xt.releasePrimitive(D)}else{const D=We(e),R=Ue(e,x);be(D,m,Lr),be(R,m,Nr);const O=f.intersectsBox(Lr),k=f.intersectsBox(Nr);if(O&&k)P=Je(s,D,t,n,r,o,i,a,c+1,f,d)||Je(s,R,t,n,r,o,i,a,c+1,f,d);else if(O)if(A)P=Je(s,D,t,n,r,o,i,a,c+1,f,d);else{const L=xt.getPrimitive();L.copy(Lr).applyMatrix4(t);const V=We(s),G=Ue(s,y);be(V,g,Wt),be(G,g,jt);const Q=L.intersectsBox(Wt),J=L.intersectsBox(jt);P=Q&&Je(D,V,n,t,r,i,o,c,a+1,L,!d)||J&&Je(D,G,n,t,r,i,o,c,a+1,L,!d),xt.releasePrimitive(L)}else if(k)if(A)P=Je(s,R,t,n,r,o,i,a,c+1,f,d);else{const L=xt.getPrimitive();L.copy(Nr).applyMatrix4(t);const V=We(s),G=Ue(s,y);be(V,g,Wt),be(G,g,jt);const Q=L.intersectsBox(Wt),J=L.intersectsBox(jt);P=Q&&Je(R,V,n,t,r,i,o,c,a+1,L,!d)||J&&Je(R,G,n,t,r,i,o,c,a+1,L,!d),xt.releasePrimitive(L)}}return P}const En=new Oe,Ui=new h.Box3,rc={strategy:wi,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class zr{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,r=e._roots,o=e._indirectBuffer,i=n.getIndex();let a;return t.cloneBuffers?a={roots:r.map(c=>c.slice()),index:i?i.array.slice():null,indirectBuffer:o?o.slice():null}:a={roots:r,index:i?i.array:null,indirectBuffer:o},a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:r,roots:o,indirectBuffer:i}=e,a=new zr(t,{...n,[mr]:!0});if(a._roots=o,a._indirectBuffer=i||null,n.setIndex){const c=t.getIndex();if(c===null){const f=new h.BufferAttribute(e.index,1,!1);t.setIndex(f)}else c.array!==r&&(c.array.set(r),c.needsUpdate=!0)}return a}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...rc,[mr]:!1},t),t.useSharedArrayBuffer&&!tc())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[mr]||(xa(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new h.Box3))),this.resolveTriangleIndex=t.indirect?n=>this._indirectBuffer[n]:n=>n}refit(e=null){return(this.indirect?qa:Ra)(this,e)}traverse(e,t=0){const n=this._roots[t],r=new Uint32Array(n),o=new Uint16Array(n);i(0);function i(a,c=0){const f=a*2,d=o[f+15]===Tn;if(d){const u=r[a+6],l=o[f+14];e(c,d,new Float32Array(n,a*4,6),u,l)}else{const u=a+mt/4,l=r[a+6],g=r[a+7];e(c,d,new Float32Array(n,a*4,6),g)||(i(u,c+1),i(l,c+1))}}}raycast(e,t=h.FrontSide,n=0,r=1/0){const o=this._roots,i=this.geometry,a=[],c=t.isMaterial,f=Array.isArray(t),d=i.groups,u=c?t.side:t,l=this.indirect?Za:ka;for(let g=0,y=o.length;g<y;g++){const w=f?t[d[g].materialIndex].side:u,m=a.length;if(l(this,g,w,e,a,n,r),f){const x=d[g].materialIndex;for(let b=m,T=a.length;b<T;b++)a[b].face.materialIndex=x}}return a}raycastFirst(e,t=h.FrontSide,n=0,r=1/0){const o=this._roots,i=this.geometry,a=t.isMaterial,c=Array.isArray(t);let f=null;const d=i.groups,u=a?t.side:t,l=this.indirect?Ka:Ba;for(let g=0,y=o.length;g<y;g++){const w=c?t[d[g].materialIndex].side:u,m=l(this,g,w,e,n,r);m!=null&&(f==null||m.distance<f.distance)&&(f=m,c&&(m.face.materialIndex=d[g].materialIndex))}return f}intersectsGeometry(e,t){let n=!1;const r=this._roots,o=this.indirect?Xa:Ua;for(let i=0,a=r.length;i<a&&(n=o(this,i,e,t),!n);i++);return n}shapecast(e){const t=je.getPrimitive(),n=this.indirect?Na:Fa;let{boundsTraverseOrder:r,intersectsBounds:o,intersectsRange:i,intersectsTriangle:a}=e;if(i&&a){const u=i;i=(l,g,y,w,m)=>u(l,g,y,w,m)?!0:n(l,g,this,a,y,w,t)}else i||(a?i=(u,l,g,y)=>n(u,l,this,a,g,y,t):i=(u,l,g)=>g);let c=!1,f=0;const d=this._roots;for(let u=0,l=d.length;u<l;u++){const g=d[u];if(c=Ma(this,u,o,i,r,f),c)break;f+=g.byteLength}return je.releasePrimitive(t),c}bvhcast(e,t,n){let{intersectsRanges:r,intersectsTriangles:o}=n;const i=je.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,f=this.indirect?y=>{const w=this.resolveTriangleIndex(y);_e(i,w*3,a,c)}:y=>{_e(i,y*3,a,c)},d=je.getPrimitive(),u=e.geometry.index,l=e.geometry.attributes.position,g=e.indirect?y=>{const w=e.resolveTriangleIndex(y);_e(d,w*3,u,l)}:y=>{_e(d,y*3,u,l)};if(o){const y=(w,m,x,b,T,M,A,I)=>{for(let P=x,D=x+b;P<D;P++){g(P),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let R=w,O=w+m;R<O;R++)if(f(R),i.needsUpdate=!0,o(i,d,R,P,T,M,A,I))return!0}return!1};if(r){const w=r;r=function(m,x,b,T,M,A,I,P){return w(m,x,b,T,M,A,I,P)?!0:y(m,x,b,T,M,A,I,P)}}else r=y}return nc(this,e,t,r)}intersectsBox(e,t){return En.set(e.min,e.max,t),En.needsUpdate=!0,this.shapecast({intersectsBounds:n=>En.intersectsBox(n),intersectsTriangle:n=>En.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},r={},o=0,i=1/0){return(this.indirect?ec:ja)(this,e,t,n,r,o,i)}closestPointToPoint(e,t={},n=0,r=1/0){return Aa(this,e,t,n,r)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{be(0,new Float32Array(n),Ui),e.union(Ui)}),e}}function ic(s){switch(s){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function sc(s){switch(s){case 1:return h.RedFormat;case 2:return h.RGFormat;case 3:return h.RGBAFormat;case 4:return h.RGBAFormat}}function Ei(s){switch(s){case 1:return h.RedIntegerFormat;case 2:return h.RGIntegerFormat;case 3:return h.RGBAIntegerFormat;case 4:return h.RGBAIntegerFormat}}class Gi extends h.DataTexture{constructor(){super(),this.minFilter=h.NearestFilter,this.magFilter=h.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(e){const t=this.overrideItemSize,n=e.itemSize,r=e.count;if(t!==null){if(n*r%t!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");e.itemSize=t,e.count=r*n/t}const o=e.itemSize,i=e.count,a=e.normalized,c=e.array.constructor,f=c.BYTES_PER_ELEMENT;let d=this._forcedType,u=o;if(d===null)switch(c){case Float32Array:d=h.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:d=h.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:d=h.IntType;break}let l,g,y,w,m=ic(o);switch(d){case h.FloatType:y=1,g=sc(o),a&&f===1?(w=c,m+="8",c===Uint8Array?l=h.UnsignedByteType:(l=h.ByteType,m+="_SNORM")):(w=Float32Array,m+="32F",l=h.FloatType);break;case h.IntType:m+=f*8+"I",y=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,g=Ei(o),f===1?(w=Int8Array,l=h.ByteType):f===2?(w=Int16Array,l=h.ShortType):(w=Int32Array,l=h.IntType);break;case h.UnsignedIntType:m+=f*8+"UI",y=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,g=Ei(o),f===1?(w=Uint8Array,l=h.UnsignedByteType):f===2?(w=Uint16Array,l=h.UnsignedShortType):(w=Uint32Array,l=h.UnsignedIntType);break}u===3&&(g===h.RGBAFormat||g===h.RGBAIntegerFormat)&&(u=4);const x=Math.ceil(Math.sqrt(i))||1,b=u*x*x,T=new w(b),M=e.normalized;e.normalized=!1;for(let A=0;A<i;A++){const I=u*A;T[I]=e.getX(A)/y,o>=2&&(T[I+1]=e.getY(A)/y),o>=3&&(T[I+2]=e.getZ(A)/y,u===4&&(T[I+3]=1)),o>=4&&(T[I+3]=e.getW(A)/y)}e.normalized=M,this.internalFormat=m,this.format=g,this.type=l,this.image.width=x,this.image.height=x,this.image.data=T,this.needsUpdate=!0,this.dispose(),e.itemSize=n,e.count=r}}class Vi extends Gi{constructor(){super(),this._forcedType=h.UnsignedIntType}}class Wi extends Gi{constructor(){super(),this._forcedType=h.FloatType}}class oc{constructor(){this.index=new Vi,this.position=new Wi,this.bvhBounds=new h.DataTexture,this.bvhContents=new h.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(cc(e,this.bvhBounds,this.bvhContents),this.position.updateFrom(t.attributes.position),e.indirect){const n=e._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==n.length)if(t.index)this._cachedIndexAttr=t.index.clone();else{const r=Ai(Mi(t));this._cachedIndexAttr=new h.BufferAttribute(r,1,!1)}ac(t,n,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(t.index)}dispose(){const{index:e,position:t,bvhBounds:n,bvhContents:r}=this;e&&e.dispose(),t&&t.dispose(),n&&n.dispose(),r&&r.dispose()}}function ac(s,e,t){const n=t.array,r=s.index?s.index.array:null;for(let o=0,i=e.length;o<i;o++){const a=3*o,c=3*e[o];for(let f=0;f<3;f++)n[a+f]=r?r[c+f]:c+f}}function cc(s,e,t){const n=s._roots;if(n.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const r=n[0],o=new Uint16Array(r),i=new Uint32Array(r),a=new Float32Array(r),c=r.byteLength/mt,f=2*Math.ceil(Math.sqrt(c/2)),d=new Float32Array(4*f*f),u=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*u*u);for(let g=0;g<c;g++){const y=g*mt/4,w=y*2,m=y;for(let x=0;x<3;x++)d[8*g+0+x]=a[m+0+x],d[8*g+4+x]=a[m+3+x];if(Re(w,o)){const x=Be(w,o),b=Ne(y,i),T=4294901760|x;l[g*2+0]=T,l[g*2+1]=b}else{const x=4*Ue(y,i)/mt,b=yr(y,i);l[g*2+0]=b,l[g*2+1]=x}}e.image.data=d,e.image.width=f,e.image.height=f,e.format=h.RGBAFormat,e.type=h.FloatType,e.internalFormat="RGBA32F",e.minFilter=h.NearestFilter,e.magFilter=h.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose(),t.image.data=l,t.image.width=u,t.image.height=u,t.format=h.RGIntegerFormat,t.type=h.UnsignedIntType,t.internalFormat="RG32UI",t.minFilter=h.NearestFilter,t.magFilter=h.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose()}const lc=`
|
|
1
|
+
(function(nt,Ce){typeof exports=="object"&&typeof module<"u"?Ce(exports,require("react/jsx-runtime"),require("react"),require("three")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","three"],Ce):(nt=typeof globalThis<"u"?globalThis:nt||self,Ce(nt.SimpleViewer={},nt.jsxRuntime,nt.React,nt.THREE))})(this,function(nt,Ce,ne,h){"use strict";function xo(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const A=xo(h);class H 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,H)}static fromError(e,t,n){if(e instanceof H)return e;const i=e instanceof Error?e.message:String(e),o={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new H(i,t,o)}}var te=(r=>(r.SCENE_INIT_FAILED="SCENE_INIT_FAILED",r.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",r.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",r.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",r.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",r.INITIALIZATION_FAILED="INITIALIZATION_FAILED",r.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",r.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",r.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",r.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",r.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",r.INVALID_CONFIGURATION="INVALID_CONFIGURATION",r.RENDER_ERROR="RENDER_ERROR",r.RENDER_FAILED="RENDER_FAILED",r.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",r.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",r.INVALID_STATE="INVALID_STATE",r.INVALID_PARAMETER="INVALID_PARAMETER",r.OPERATION_FAILED="OPERATION_FAILED",r.UNKNOWN="UNKNOWN",r))(te||{});const q={ok(r){return{ok:!0,value:r}},err(r){return{ok:!1,error:r}},wrap(r){try{return q.ok(r())}catch(e){return q.err(e instanceof H?e:new H(String(e),te.UNKNOWN,{originalError:e}))}}};class In{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 i;(i=this.listeners.get(e))==null||i.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(i=>{try{i(t)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}})}once(e,t){const n=this.on(e,i=>{n(),t(i)});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)}}class bo{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,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()}enableContinuousRendering(){this.continuousRenderingEnabled=!0,this.wakeUp()}disableContinuousRendering(){this.continuousRenderingEnabled=!1}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 i=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&i<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(i),this.lastRenderTime=n,this.needsRender=!1,this.enableIdleDetection&&!this.alwaysRender&&(this.wakeUp(),this.continuousRenderingEnabled||(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.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}class yr{static serialize(e,t,n,i){const o=t.position,s=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:o.x,y:o.y,z:o.z},cameraTarget:{x:s.x,y:s.y,z:s.z},controlsTarget:{x:s.x,y:s.y,z:s.z},rendererSize:{width:i.clientWidth,height:i.clientHeight}}}static async restore(e,t,n,i){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&&i&&await i(e.modelUrl)}}function ft(r){return r!==null&&typeof r=="object"&&"getInternalRenderer"in r&&typeof r.getInternalRenderer=="function"}class it{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 it({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new it({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new it({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new it({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new it({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new it({...this.data,status:"rendering"})}updateRenderInfo(e){return new it({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new it({...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 wo{constructor(){this.state=new it,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)}})}}class _o{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,i){if(this.isShowingScreenshot)return;const o=this.renderer.getDomElement(),s=o.toDataURL("image/png"),a=document.createElement("img");a.src=s,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=o.parentElement;if(c){this.serializedSceneState=yr.serialize(n,e,t,o),o.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const d=()=>{this.restore()};a.addEventListener("mousedown",d),a.addEventListener("touchstart",d);const f=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",f),this.screenshotResizeHandler=f,this.screenshotElement&&this.screenshotElement.src?i==null||i():console.warn("[ScreenshotManager] Screenshot capture failed, keeping scene resources")}}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.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class So{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.autoFitToObject=e.autoFitToObject??!1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const n=performance.now();try{let i;if(typeof e=="string"){this.lastModelUrl=e;const a=await this.modelLoader.load(e);if(!a.ok)throw a.error;i=a.value.scene}else i=e;this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const o=this.scene.add(i);if(!o.ok)throw o.error;if(this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(i);a.ok||console.warn("Failed to align model to floor:",a.error)}if(i.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=i,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,i,2);a.ok||console.warn("Failed to add dynamic grid:",a.error)}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(i,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const s=performance.now()-n;return t.emit("model:loaded",{model:i,loadTime:s}),q.ok(i)}catch(i){const o=i instanceof H?i:new H("Failed to load model",te.MODEL_LOAD_FAILED,{originalError:i,source:e});return t.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),q.err(o)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.traverse(t=>{var n,i,o;if("geometry"in t&&((n=t.geometry)!=null&&n.dispose)&&((o=(i=t.geometry)==null?void 0:i.dispose)==null||o.call(i)),"material"in t&&t.material){const s=t.material;Array.isArray(s)?s.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):s!=null&&s.dispose&&s.dispose()}}),e.dispose()}dispose(){this.disposeCurrentModel(),this.lastModelUrl=void 0}}class mi{static getMemoryInfo(){const e=performance;return e.memory?{jsHeapUsed:Math.round(e.memory.usedJSHeapSize/1048576),jsHeapTotal:Math.round(e.memory.totalJSHeapSize/1048576),jsHeapLimit:Math.round(e.memory.jsHeapSizeLimit/1048576)}:null}static formatBytes(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":e<1073741824?(e/1048576).toFixed(1)+" MB":(e/1073741824).toFixed(1)+" GB"}static logMemoryUsage(e="Memory"){const t=this.getMemoryInfo();t&&t.webglMemory}static startMonitoring(e=5e3,t="MemoryMonitor"){const n=setInterval(()=>{this.getMemoryInfo()},e);return()=>clearInterval(n)}}class To{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){mi.logMemoryUsage("Before scene disposal"),!e&&this.pathTracingService,this.environmentService&&this.environmentService.dispose(),this.scene.traverse&&this.scene.traverse(t=>{var n,i,o,s;"geometry"in t&&t.geometry&&((i=(n=t.geometry).dispose)==null||i.call(n)),"material"in t&&t.material&&(Array.isArray(t.material)?t.material.forEach(a=>{var c;(c=a.dispose)==null||c.call(a)}):(s=(o=t.material).dispose)==null||s.call(o))}),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection(),mi.logMemoryUsage("After scene disposal"),setTimeout(()=>{mi.logMemoryUsage("After GC delay")},2e3)}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.clear&&this.scene.clear(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}class Mo{constructor(e){var i;this.lastFrameTime=0,this.frameCount=0,this.pathTracingCompleteHandled=!1,this.disposed=!1,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.pathTracingService=e.pathTracingService,this.stateManager=new wo,this.screenshotManager=new _o({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}}),this.modelManager=new So({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,autoFitToObject:(i=this.options.camera)==null?void 0:i.autoFitToObject}),this.resourceManager=new To({scene:this.scene,pathTracingService:this.pathTracingService,environmentService:this.environmentService}),this.events=new In;const t=this.options.rendering||{},n=this.options.staticScene!==!1;this.renderLoopManager=new bo({enableIdleDetection:t.enableIdleDetection??n,idleDelay:t.idleDelay,targetFPS:t.targetFPS,enableFrameRateLimiting:t.enableFrameRateLimiting,alwaysRender:!1})}async initialize(){var e,t,n,i,o,s,a,c,d,f,u,l;try{const g=this.rendererOptions||{},y=this.renderer.initialize(g);if(!y.ok)return y;if(this.sceneSetupService){if(this.options.helpers){const x={grid:this.options.helpers.grid,axes:this.options.helpers.axes,gridColor:"#AAAAAA"},w=this.sceneSetupService.addHelpers(this.scene,x);w.ok||console.warn("Failed to add helpers:",w.error)}const m=this.options.lighting;if(m){const x={ambient:m.ambientLight?{color:String(m.ambientLight.color),intensity:m.ambientLight.intensity}:void 0,hemisphere:m.hemisphereLight?{skyColor:String(m.hemisphereLight.skyColor),groundColor:String(m.hemisphereLight.groundColor),intensity:m.hemisphereLight.intensity}:void 0,directional:m.directionalLight?{color:String(m.directionalLight.color),intensity:m.directionalLight.intensity,position:Array.isArray(m.directionalLight.position)?m.directionalLight.position:void 0,castShadow:m.directionalLight.castShadow,shadow:m.directionalLight.shadow}:void 0},w=this.sceneSetupService.addLighting(this.scene,x);w.ok||console.warn("Failed to add lighting:",w.error)}const _=(e=this.options.environment)==null?void 0:e.url;if(this.options.backgroundColor&&!_&&this.sceneSetupService){const x=this.sceneSetupService.createGradientBackground(this.scene,{topColor:String(this.options.backgroundColor),bottomColor:String(this.options.backgroundColor)});x.ok||console.warn("Failed to set background:",x.error)}}if(this.environmentService){const m=await this.environmentService.initialize({renderer:this.renderer,autoDispose:!0});m.ok||console.warn("Failed to initialize environment service:",m.error);const _=(t=this.options.environment)==null?void 0:t.url;if(_){const x=await this.environmentService.loadEnvironmentMap(_);x.ok?this.environmentService.applyToScene(this.scene,x.value,{backgroundBlurriness:(n=this.options.environment)==null?void 0:n.backgroundBlurriness,backgroundIntensity:(i=this.options.environment)==null?void 0:i.backgroundIntensity,environmentIntensity:(o=this.options.environment)==null?void 0:o.environmentIntensity}):console.warn("Failed to load environment map:",x.error)}else if((s=this.options.helpers)!=null&&s.studioEnvironment){const x=this.environmentService.createStudioEnvironment();if(x.ok){if(this.environmentService.applyToScene(this.scene,x.value,{backgroundBlurriness:(a=this.options.environment)==null?void 0:a.backgroundBlurriness,backgroundIntensity:(c=this.options.environment)==null?void 0:c.backgroundIntensity,environmentIntensity:(d=this.options.environment)==null?void 0:d.environmentIntensity}),(f=this.options.helpers)!=null&&f.darkStudioMode&&this.sceneSetupService){const w="#1a1a1f",S=this.sceneSetupService.createGradientBackground(this.scene,{topColor:w,bottomColor:w});S.ok||console.warn("Failed to set dark studio background:",S.error)}}else console.warn("Failed to create studio environment:",x.error)}}const b=((u=this.options.pathTracing)==null?void 0:u.enabled)??!1;if(this.pathTracingService&&b){const m=await this.pathTracingService.initialize({enabled:!0,renderer:this.renderer});m.ok?(this.options.pathTracing&&this.pathTracingService.updateSettings({samples:this.options.pathTracing.maxSamples??300,bounces:this.options.pathTracing.bounces,transmissiveBounces:this.options.pathTracing.transmissiveBounces,renderScale:this.options.pathTracing.renderScale,lowResScale:this.options.pathTracing.lowResScale,dynamicLowRes:this.options.pathTracing.dynamicLowRes,enablePathTracing:this.options.pathTracing.enabled??b}),this.pathTracingService.events.on("pathtracing:paused",_=>{this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),setTimeout(()=>{this.renderLoopManager.stop()},100)})):console.warn("Failed to initialize path tracing:",m.error)}if(this.stateManager.setInitialized(),this.startRenderLoop(),!this.options.staticScene)this.renderLoopManager.setAlwaysRender(!0);else{const m=((l=this.options.pathTracing)==null?void 0:l.enabled)??!1;this.pathTracingService&&m&&this.renderLoopManager.enableContinuousRendering()}return this.renderLoopManager.requestRender(),q.ok(void 0)}catch(g){const y=new H("Failed to initialize viewer",te.INITIALIZATION_FAILED,{originalError:g});return this.stateManager.setError(y),this.events.emit("error",{error:y}),q.err(y)}}async loadModel(e){var t;if(!this.stateManager.canLoad())return q.err(new H("Cannot load model in current state",te.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const n=await this.modelManager.loadModel(e,this.events);if(n.ok){this.stateManager.setLoaded(n.value),this.renderLoopManager.requestRender();const i=((t=this.options.pathTracing)==null?void 0:t.enabled)??!1;return this.pathTracingService&&i&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),q.ok(void 0)}else return this.stateManager.setError(n.error),n}catch(n){const i=n instanceof H?n:new H("Failed to load model",te.MODEL_LOAD_FAILED,{originalError:n,source:e});return this.stateManager.setError(i),q.err(i)}}startRenderLoop(){this.renderLoopManager.start(e=>{var d,f,u,l,g;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.renderer===null){this.renderLoopManager.stop();return}this.frameCount%60;const t=performance.now(),n=e>0?1e3/e:0;if(this.controls.update()){this.events.emit("controls:change",{controls:this.controls});const y=((d=this.options.pathTracing)==null?void 0:d.enabled)??!1;this.pathTracingService&&y&&(this.pathTracingService.reset(),this.pathTracingCompleteHandled=!1),this.renderLoopManager.requestRender()}const o=((f=this.pathTracingService)==null?void 0:f.isEnabled())||!1,s=((u=this.pathTracingService)==null?void 0:u.getSampleCount())||0,a=((l=this.options.pathTracing)==null?void 0:l.maxSamples)??300;if(this.renderFrame().catch(y=>{console.error("[ViewerCore] Render frame error:",y)}),(((g=this.pathTracingService)==null?void 0:g.getSampleCount())||0)>=a&&!this.pathTracingCompleteHandled&&o){if(this.pathTracingCompleteHandled=!0,this.renderLoopManager.disableContinuousRendering(),this.options.staticScene||this.renderLoopManager.setAlwaysRender(!1),this.events.emit("pathtracing:complete",{samples:s,totalTime:t-(this.pathTracingStartTime||0)}),this.options.replaceWithScreenshotOnComplete)setTimeout(()=>{this.replaceWithScreenshot(),setTimeout(()=>{this.renderLoopManager.stop()},200)},100);else if(this.renderLoopManager.requestRender(),setTimeout(()=>{this.renderLoopManager.stop()},100),ft(this.renderer)){const y=this.renderer.getInternalRenderer();y&&(y.autoClear=!1)}}this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t}),this.lastFrameTime=t})}stopRenderLoop(){this.renderLoopManager.stop()}async renderFrame(){var d,f,u,l;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();let t;const n=((d=this.pathTracingService)==null?void 0:d.isEnabled())||!1,i=((f=this.pathTracingService)==null?void 0:f.getSampleCount())||0,o=((u=this.options.pathTracing)==null?void 0:u.maxSamples)??300;if(this.pathTracingService&&!this.pathTracingService.isPathTracerDisposed()&&(n||i>=o&&i>0)&&this.pathTracingService?(this.pathTracingService.getSampleCount()===0&&(this.pathTracingStartTime=performance.now()),t=await this.pathTracingService.render(this.scene,this.camera)):t=this.renderer.render(this.scene,this.camera),!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}const a=performance.now()-e,c=((l=this.pathTracingService)==null?void 0:l.getSampleCount())||0;this.events.emit("render:complete",{frame:this.frameCount,renderTime:a,samples:c})}resize(e,t){var o;const n=this.renderer.getDomElement();if(n.width===e&&n.height===t)return;const i=(o=this.pathTracingService)==null?void 0:o.isEnabled();this.pathTracingService&&this.pathTracingService.hasImageOverlay()&&(this.pathTracingService.removeImageOverlay(),this.pathTracingService.reset()),this.camera.type==="perspective"&&"aspect"in this.camera&&(this.camera.aspect=e/t),this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}i&&this.pathTracingService&&this.pathTracingService.setEnabled(!0),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){var t;const e=this.screenshotManager.getSerializedState();!this.pathTracingService&&((t=this.options.pathTracing)!=null&&t.enabled)&&console.warn("[ViewerCore] Cannot recreate path tracing service - feature disabled"),e&&await yr.restore(e,this.camera,this.controls,async n=>{const i=await this.loadModel(n);i.ok||console.error("[ViewerCore] Failed to reload model:",i.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}dispose(){this.disposed=!0,this.stopRenderLoop(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.scene.clear(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class xt{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 xt(e)}static create(e=0,t=0,n=0){return new xt(new A.Vector3(e,t,n))}}class Ee{constructor(e){this.object=e,this.positionAdapter=xt.fromThreeVector(e.position),this.rotationAdapter=xt.fromThreeVector(e.rotation),this.scaleAdapter=xt.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 position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof Ee?(this.object.add(e.getThreeObject()),q.ok(void 0)):q.err(new H("Child must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return q.err(new H("Failed to add child object",te.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ee?(this.object.remove(e.getThreeObject()),q.ok(void 0)):q.err(new H("Child must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return q.err(new H("Failed to remove child object",te.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Ee(t))})}clone(){return new Ee(this.object.clone())}dispose(){this.object.traverse(e=>{var t;e instanceof A.Mesh&&((t=e.geometry)==null||t.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>n.dispose()):e.material.dispose()))})}getThreeObject(){return this.object}static fromThreeObject(e){return new Ee(e)}static create(){return new Ee(new A.Object3D)}}class Dt{constructor(e){this.scene=e||new A.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 Ee?(this.scene.add(e.getThreeObject()),q.ok(void 0)):q.err(new H("Object must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return q.err(new H("Failed to add object to scene",te.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ee?(this.scene.remove(e.getThreeObject()),q.ok(void 0)):q.err(new H("Object must be a ThreeObject3DAdapter",te.INVALID_PARAMETER))}catch(t){return q.err(new H("Failed to remove object from scene",te.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}traverse(e){this.scene.traverse(t=>{e(new Ee(t))})}get background(){return this.scene.background instanceof A.Color?new gi(this.scene.background):this.scene.background instanceof A.Texture?new Cn(this.scene.background):null}set background(e){e instanceof gi?this.scene.background=e.getThreeColor():e instanceof Cn?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new vr(this.scene.fog):null}set fog(e){e instanceof vr?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new Cn(this.scene.environment):null}set environment(e){e instanceof Cn?this.scene.environment=e.getThreeTexture():this.scene.environment=null}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class gi{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 Cn=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 vr{constructor(e){this.fog=e}get color(){return new gi(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class yi extends Ee{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof A.PerspectiveCamera||this.camera instanceof A.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof A.PerspectiveCamera||this.camera instanceof A.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof A.PerspectiveCamera||this.camera instanceof A.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof A.PerspectiveCamera||this.camera instanceof A.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof xt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof A.PerspectiveCamera||this.camera instanceof A.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new A.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class vi extends yi{constructor(e){const t=e||new A.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=75,t=1,n=.1,i=1e3){return new vi(new A.PerspectiveCamera(e,t,n,i))}}function Ao(){const r="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?r[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}class Io{constructor(e){this.renderer=null,this._id=Ao(),this.canvas=e}get id(){return this._id}initialize(e){try{if(this.renderer=new A.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const t={basic:A.BasicShadowMap,pcf:A.PCFShadowMap,pcfsoft:A.PCFSoftShadowMap,vsm:A.VSMShadowMap};this.renderer.shadowMap.type=t[e.shadowMap.type]}if(e.toneMapping){const t={none:A.NoToneMapping,linear:A.LinearToneMapping,reinhard:A.ReinhardToneMapping,cineon:A.CineonToneMapping,aces:A.ACESFilmicToneMapping};this.renderer.toneMapping=t[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}if(e.pixelRatio!==void 0?this.renderer.setPixelRatio(e.pixelRatio):this.renderer.setPixelRatio(window.devicePixelRatio),this.canvas){const{clientWidth:t,clientHeight:n}=this.canvas.parentElement||this.canvas;t&&n&&this.renderer.setSize(t,n)}return this.renderer.outputColorSpace=A.SRGBColorSpace,q.ok(void 0)}catch(t){return q.err(new H("Failed to initialize renderer",te.RENDERER_INIT_FAILED,{originalError:t,options:e}))}}render(e,t){if(!this.renderer)return q.err(new H("Renderer not initialized",te.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof Dt))return q.err(new H("Scene must be a ThreeSceneAdapter",te.INVALID_PARAMETER));if(!(t instanceof yi))return q.err(new H("Camera must be a ThreeCameraAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene(),i=t.getThreeCamera();return this.renderer.__pathTracingActive||this.renderer.render(n,i),q.ok(void 0)}catch(n){return q.err(new H("Failed to render frame",te.RENDER_FAILED,{originalError:n}))}}setSize(e,t){if(this.renderer){this.renderer.setSize(e,t,!1);const n=this.renderer.domElement;n.style.width="100%",n.style.height="100%"}}setPixelRatio(e){this.renderer&&this.renderer.setPixelRatio(e)}getDomElement(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.domElement}getContext(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.getContext()}get capabilities(){if(!this.renderer)return{maxTextureSize:0,maxCubemapSize:0,maxAttributes:0,maxVertexUniforms:0,maxFragmentUniforms:0,maxSamples:0,isWebGL2:!1};const e=this.renderer.capabilities;return{maxTextureSize:e.maxTextureSize,maxCubemapSize:e.maxCubemapSize,maxAttributes:e.maxAttributes,maxVertexUniforms:e.maxVertexUniforms,maxFragmentUniforms:e.maxFragmentUniforms,maxSamples:e.maxSamples||0,isWebGL2:e.isWebGL2}}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function xr(r,e){if(e===h.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),r;if(e===h.TriangleFanDrawMode||e===h.TriangleStripDrawMode){let t=r.getIndex();if(t===null){const s=[],a=r.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)s.push(c);r.setIndex(s),t=r.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),r}const n=t.count-2,i=[];if(e===h.TriangleFanDrawMode)for(let s=1;s<=n;s++)i.push(t.getX(0)),i.push(t.getX(s)),i.push(t.getX(s+1));else for(let s=0;s<n;s++)s%2===0?(i.push(t.getX(s)),i.push(t.getX(s+1)),i.push(t.getX(s+2))):(i.push(t.getX(s+2)),i.push(t.getX(s+1)),i.push(t.getX(s)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=r.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),r}function Co(r){const e=new Map,t=new Map,n=r.clone();return br(r,n,function(i,o){e.set(o,i),t.set(i,o)}),n.traverse(function(i){if(!i.isSkinnedMesh)return;const o=i,s=e.get(i),a=s.skeleton.bones;o.skeleton=s.skeleton.clone(),o.bindMatrix.copy(s.bindMatrix),o.skeleton.bones=a.map(function(c){return t.get(c)}),o.bind(o.skeleton,o.bindMatrix)}),n}function br(r,e,t){t(r,e);for(let n=0;n<r.children.length;n++)br(r.children[n],e.children[n],t)}class Po extends h.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Lo(t)}),this.register(function(t){return new No(t)}),this.register(function(t){return new jo(t)}),this.register(function(t){return new qo(t)}),this.register(function(t){return new Zo(t)}),this.register(function(t){return new Bo(t)}),this.register(function(t){return new zo(t)}),this.register(function(t){return new Uo(t)}),this.register(function(t){return new Eo(t)}),this.register(function(t){return new Oo(t)}),this.register(function(t){return new Go(t)}),this.register(function(t){return new ko(t)}),this.register(function(t){return new Wo(t)}),this.register(function(t){return new Vo(t)}),this.register(function(t){return new Fo(t)}),this.register(function(t){return new wr(t,se.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new wr(t,se.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Yo(t)})}load(e,t,n,i){const o=this;let s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){const d=h.LoaderUtils.extractUrlBase(e);s=h.LoaderUtils.resolveURL(d,this.path)}else s=h.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(d){i?i(d):console.error(d),o.manager.itemError(e),o.manager.itemEnd(e)},c=new h.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(d){try{o.parse(d,s,function(f){t(f),o.manager.itemEnd(e)},a)}catch(f){a(f)}},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,i){let o;const s={},a={},c=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===_r){try{s[se.KHR_BINARY_GLTF]=new Ko(e)}catch(u){i&&i(u);return}o=JSON.parse(s[se.KHR_BINARY_GLTF].content)}else o=JSON.parse(c.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const d=new aa(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});d.fileLoader.setRequestHeader(this.requestHeader);for(let f=0;f<this.pluginCallbacks.length;f++){const u=this.pluginCallbacks[f](d);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,s[u.name]=!0}if(o.extensionsUsed)for(let f=0;f<o.extensionsUsed.length;++f){const u=o.extensionsUsed[f],l=o.extensionsRequired||[];switch(u){case se.KHR_MATERIALS_UNLIT:s[u]=new Ro;break;case se.KHR_DRACO_MESH_COMPRESSION:s[u]=new Xo(o,this.dracoLoader);break;case se.KHR_TEXTURE_TRANSFORM:s[u]=new $o;break;case se.KHR_MESH_QUANTIZATION:s[u]=new Qo;break;default:l.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}d.setExtensions(s),d.setPlugins(a),d.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,o){n.parse(e,t,i,o)})}}function Do(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}function Te(r,e,t){const n=r.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}const se={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 Fo{constructor(e){this.parser=e,this.name=se.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const o=t.json,c=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let d;const f=new h.Color(16777215);c.color!==void 0&&f.setRGB(c.color[0],c.color[1],c.color[2],h.LinearSRGBColorSpace);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new h.DirectionalLight(f),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new h.PointLight(f),d.distance=u;break;case"spot":d=new h.SpotLight(f),d.distance=u,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,d.angle=c.spot.outerConeAngle,d.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,d.target.position.set(0,0,-1),d.add(d.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return d.position.set(0,0,0),ut(d,c),c.intensity!==void 0&&(d.intensity=c.intensity),d.name=t.createUniqueName(c.name||"light_"+e),i=Promise.resolve(d),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],a=(o.extensions&&o.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}}class Ro{constructor(){this.name=se.KHR_MATERIALS_UNLIT}getMaterialType(){return h.MeshBasicMaterial}extendParams(e,t,n){const i=[];e.color=new h.Color(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const s=o.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],h.LinearSRGBColorSpace),e.opacity=s[3]}o.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",o.baseColorTexture,h.SRGBColorSpace))}return Promise.all(i)}}class Oo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class Lo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const o=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new h.Vector2(o,o)}return Promise.all(i)}}class No{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class ko{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&i.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&&i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(i)}}class Bo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_SHEEN}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];if(t.sheenColor=new h.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){const o=n.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],h.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,h.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(i)}}class zo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&i.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(i)}}class Uo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_VOLUME}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const o=n.attenuationColor||[1,1,1];return t.attenuationColor=new h.Color().setRGB(o[0],o[1],o[2],h.LinearSRGBColorSpace),Promise.all(i)}}class Eo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_IOR}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5),Promise.resolve()}}class Go{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const o=n.specularColorFactor||[1,1,1];return t.specularColor=new h.Color().setRGB(o[0],o[1],o[2],h.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,h.SRGBColorSpace)),Promise.all(i)}}class Vo{constructor(e){this.parser=e,this.name=se.EXT_MATERIALS_BUMP}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&i.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(i)}}class Wo{constructor(e){this.parser=e,this.name=se.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Te(this.parser,e,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Te(this.parser,e,this.name);if(n===null)return Promise.resolve();const i=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&i.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(i)}}class jo{constructor(e){this.parser=e,this.name=se.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const o=i.extensions[this.name],s=t.options.ktx2Loader;if(!s){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,o.source,s)}}class qo{constructor(e){this.parser=e,this.name=se.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const s=o.extensions[t],a=i.images[s.source];let c=n.textureLoader;if(a.uri){const d=n.options.manager.getHandler(a.uri);d!==null&&(c=d)}return n.loadTextureImage(e,s.source,c)}}class Zo{constructor(e){this.parser=e,this.name=se.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const s=o.extensions[t],a=i.images[s.source];let c=n.textureLoader;if(a.uri){const d=n.options.manager.getHandler(a.uri);d!==null&&(c=d)}return n.loadTextureImage(e,s.source,c)}}class wr{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 i=n.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.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 o.then(function(a){const c=i.byteOffset||0,d=i.byteLength||0,f=i.count,u=i.byteStride,l=new Uint8Array(a,c,d);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(f,u,l,i.mode,i.filter).then(function(g){return g.buffer}):s.ready.then(function(){const g=new ArrayBuffer(f*u);return s.decodeGltfBuffer(new Uint8Array(g),f,u,l,i.mode,i.filter),g})})}else return null}}class Yo{constructor(e){this.name=se.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 i=t.meshes[n.mesh];for(const d of i.primitives)if(d.mode!==Xe.TRIANGLES&&d.mode!==Xe.TRIANGLE_STRIP&&d.mode!==Xe.TRIANGLE_FAN&&d.mode!==void 0)return null;const s=n.extensions[this.name].attributes,a=[],c={};for(const d in s)a.push(this.parser.getDependency("accessor",s[d]).then(f=>(c[d]=f,c[d])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(d=>{const f=d.pop(),u=f.isGroup?f.children:[f],l=d[0].count,g=[];for(const y of u){const b=new h.Matrix4,m=new h.Vector3,_=new h.Quaternion,x=new h.Vector3(1,1,1),w=new h.InstancedMesh(y.geometry,y.material,l);for(let S=0;S<l;S++)c.TRANSLATION&&m.fromBufferAttribute(c.TRANSLATION,S),c.ROTATION&&_.fromBufferAttribute(c.ROTATION,S),c.SCALE&&x.fromBufferAttribute(c.SCALE,S),w.setMatrixAt(S,b.compose(m,_,x));for(const S in c)if(S==="_COLOR_0"){const M=c[S];w.instanceColor=new h.InstancedBufferAttribute(M.array,M.itemSize,M.normalized)}else S!=="TRANSLATION"&&S!=="ROTATION"&&S!=="SCALE"&&y.geometry.setAttribute(S,c[S]);h.Object3D.prototype.copy.call(w,y),this.parser.assignFinalMaterial(w),g.push(w)}return f.isGroup?(f.clear(),f.add(...g),f):g[0]}))}}const _r="glTF",ln=12,Sr={JSON:1313821514,BIN:5130562};class Ko{constructor(e){this.name=se.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ln),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!==_r)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-ln,o=new DataView(e,ln);let s=0;for(;s<i;){const a=o.getUint32(s,!0);s+=4;const c=o.getUint32(s,!0);if(s+=4,c===Sr.JSON){const d=new Uint8Array(e,ln+s,a);this.content=n.decode(d)}else if(c===Sr.BIN){const d=ln+s;this.body=e.slice(d,d+a)}s+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Xo{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=se.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,a={},c={},d={};for(const f in s){const u=bi[f]||f.toLowerCase();a[u]=s[f]}for(const f in e.attributes){const u=bi[f]||f.toLowerCase();if(s[f]!==void 0){const l=n.accessors[e.attributes[f]],g=Vt[l.componentType];d[u]=g.name,c[u]=l.normalized===!0}}return t.getDependency("bufferView",o).then(function(f){return new Promise(function(u,l){i.decodeDracoFile(f,function(g){for(const y in g.attributes){const b=g.attributes[y],m=c[y];m!==void 0&&(b.normalized=m)}u(g)},a,d,h.LinearSRGBColorSpace,l)})})}}class $o{constructor(){this.name=se.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 Qo{constructor(){this.name=se.KHR_MESH_QUANTIZATION}}class Tr extends h.Interpolant{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let s=0;s!==i;s++)t[s]=n[o+s];return t}interpolate_(e,t,n,i){const o=this.resultBuffer,s=this.sampleValues,a=this.valueSize,c=a*2,d=a*3,f=i-t,u=(n-t)/f,l=u*u,g=l*u,y=e*d,b=y-d,m=-2*g+3*l,_=g-l,x=1-m,w=_-l+u;for(let S=0;S!==a;S++){const M=s[b+S+a],I=s[b+S+c]*f,C=s[y+S+a],D=s[y+S]*f;o[S]=x*M+w*I+m*C+_*D}return o}}const Jo=new h.Quaternion;class Ho extends Tr{interpolate_(e,t,n,i){const o=super.interpolate_(e,t,n,i);return Jo.fromArray(o).normalize().toArray(o),o}}const Xe={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Vt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Mr={9728:h.NearestFilter,9729:h.LinearFilter,9984:h.NearestMipmapNearestFilter,9985:h.LinearMipmapNearestFilter,9986:h.NearestMipmapLinearFilter,9987:h.LinearMipmapLinearFilter},Ar={33071:h.ClampToEdgeWrapping,33648:h.MirroredRepeatWrapping,10497:h.RepeatWrapping},xi={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},bi={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"},bt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},ea={CUBICSPLINE:void 0,LINEAR:h.InterpolateLinear,STEP:h.InterpolateDiscrete},wi={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function ta(r){return r.DefaultMaterial===void 0&&(r.DefaultMaterial=new h.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:h.FrontSide})),r.DefaultMaterial}function Ft(r,e,t){for(const n in t.extensions)r[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function ut(r,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(r.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function na(r,e,t){let n=!1,i=!1,o=!1;for(let d=0,f=e.length;d<f;d++){const u=e[d];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(i=!0),u.COLOR_0!==void 0&&(o=!0),n&&i&&o)break}if(!n&&!i&&!o)return Promise.resolve(r);const s=[],a=[],c=[];for(let d=0,f=e.length;d<f;d++){const u=e[d];if(n){const l=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):r.attributes.position;s.push(l)}if(i){const l=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):r.attributes.normal;a.push(l)}if(o){const l=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):r.attributes.color;c.push(l)}}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(c)]).then(function(d){const f=d[0],u=d[1],l=d[2];return n&&(r.morphAttributes.position=f),i&&(r.morphAttributes.normal=u),o&&(r.morphAttributes.color=l),r.morphTargetsRelative=!0,r})}function ia(r,e){if(r.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)r.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(r.morphTargetInfluences.length===t.length){r.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)r.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function ra(r){let e;const t=r.extensions&&r.extensions[se.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+_i(t.attributes):e=r.indices+":"+_i(r.attributes)+":"+r.mode,r.targets!==void 0)for(let n=0,i=r.targets.length;n<i;n++)e+=":"+_i(r.targets[n]);return e}function _i(r){let e="";const t=Object.keys(r).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+r[t[n]]+";";return e}function Si(r){switch(r){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 sa(r){return r.search(/\.jpe?g($|\?)/i)>0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":r.search(/\.ktx2($|\?)/i)>0||r.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const oa=new h.Matrix4;class aa{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Do,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,i=-1,o=!1,s=-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+)/);i=n&&c?parseInt(c[1],10):-1,o=a.indexOf("Firefox")>-1,s=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||o&&s<98?this.textureLoader=new h.TextureLoader(this.options.manager):this.textureLoader=new h.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new h.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,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(s){const a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:n,userData:{}};return Ft(o,a,i),ut(a,i),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 i=0,o=t.length;i<o;i++){const s=t[i].joints;for(let a=0,c=s.length;a<c;a++)e[s[a]].isBone=!0}for(let i=0,o=e.length;i<o;i++){const s=e[i];s.mesh!==void 0&&(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0&&(n[s.mesh].isSkinnedMesh=!0)),s.camera!==void 0&&this._addNodeRef(this.cameraCache,s.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 i=n.clone(),o=(s,a)=>{const c=this.associations.get(s);c!=null&&this.associations.set(a,c);for(const[d,f]of s.children.entries())o(f,a.children[d])};return o(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const o=e(t[i]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,s){return n.getDependency(e,s)})),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[se.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(o,s){n.load(h.LoaderUtils.resolveURL(t.uri,i.path),o,void 0,function(){s(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 i=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const s=xi[i.type],a=Vt[i.componentType],c=i.normalized===!0,d=new a(i.count*s);return Promise.resolve(new h.BufferAttribute(d,s,c))}const o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(s){const a=s[0],c=xi[i.type],d=Vt[i.componentType],f=d.BYTES_PER_ELEMENT,u=f*c,l=i.byteOffset||0,g=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,y=i.normalized===!0;let b,m;if(g&&g!==u){const _=Math.floor(l/g),x="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+_+":"+i.count;let w=t.cache.get(x);w||(b=new d(a,_*g,i.count*g/f),w=new h.InterleavedBuffer(b,g/f),t.cache.add(x,w)),m=new h.InterleavedBufferAttribute(w,c,l%g/f,y)}else a===null?b=new d(i.count*c):b=new d(a,l,i.count*c),m=new h.BufferAttribute(b,c,y);if(i.sparse!==void 0){const _=xi.SCALAR,x=Vt[i.sparse.indices.componentType],w=i.sparse.indices.byteOffset||0,S=i.sparse.values.byteOffset||0,M=new x(s[1],w,i.sparse.count*_),I=new d(s[2],S,i.sparse.count*c);a!==null&&(m=new h.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let C=0,D=M.length;C<D;C++){const L=M[C];if(m.setX(L,I[C*c]),c>=2&&m.setY(L,I[C*c+1]),c>=3&&m.setZ(L,I[C*c+2]),c>=4&&m.setW(L,I[C*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=y}return m})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,s=t.images[o];let a=this.textureLoader;if(s.uri){const c=n.manager.getHandler(s.uri);c!==null&&(a=c)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,n){const i=this,o=this.json,s=o.textures[e],a=o.images[t],c=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[c])return this.textureCache[c];const d=this.loadImageSource(t,n).then(function(f){f.flipY=!1,f.name=s.name||a.name||"",f.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(f.name=a.uri);const l=(o.samplers||{})[s.sampler]||{};return f.magFilter=Mr[l.magFilter]||h.LinearFilter,f.minFilter=Mr[l.minFilter]||h.LinearMipmapLinearFilter,f.wrapS=Ar[l.wrapS]||h.RepeatWrapping,f.wrapT=Ar[l.wrapT]||h.RepeatWrapping,f.generateMipmaps=!f.isCompressedTexture&&f.minFilter!==h.NearestFilter&&f.minFilter!==h.LinearFilter,i.associations.set(f,{textures:e}),f}).catch(function(){return null});return this.textureCache[c]=d,d}loadImageSource(e,t){const n=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const s=i.images[e],a=self.URL||self.webkitURL;let c=s.uri||"",d=!1;if(s.bufferView!==void 0)c=n.getDependency("bufferView",s.bufferView).then(function(u){d=!0;const l=new Blob([u],{type:s.mimeType});return c=a.createObjectURL(l),c});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const f=Promise.resolve(c).then(function(u){return new Promise(function(l,g){let y=l;t.isImageBitmapLoader===!0&&(y=function(b){const m=new h.Texture(b);m.needsUpdate=!0,l(m)}),t.load(h.LoaderUtils.resolveURL(u,o.path),y,void 0,g)})}).then(function(u){return d===!0&&a.revokeObjectURL(c),ut(u,s),u.userData.mimeType=s.mimeType||sa(s.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=f,f}assignTexture(e,t,n,i){const o=this;return this.getDependency("texture",n.index).then(function(s){if(!s)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(s=s.clone(),s.channel=n.texCoord),o.extensions[se.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[se.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=o.associations.get(s);s=o.extensions[se.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),o.associations.set(s,c)}}return i!==void 0&&(s.colorSpace=i),e[t]=s,s})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new h.PointsMaterial,h.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 h.LineBasicMaterial,h.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(i||o||s){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),s&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),o&&(c.vertexColors=!0),s&&(c.flatShading=!0),i&&(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 h.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,i=this.extensions,o=n.materials[e];let s;const a={},c=o.extensions||{},d=[];if(c[se.KHR_MATERIALS_UNLIT]){const u=i[se.KHR_MATERIALS_UNLIT];s=u.getMaterialType(),d.push(u.extendParams(a,o,t))}else{const u=o.pbrMetallicRoughness||{};if(a.color=new h.Color(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const l=u.baseColorFactor;a.color.setRGB(l[0],l[1],l[2],h.LinearSRGBColorSpace),a.opacity=l[3]}u.baseColorTexture!==void 0&&d.push(t.assignTexture(a,"map",u.baseColorTexture,h.SRGBColorSpace)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(d.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),d.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),s=this._invokeOne(function(l){return l.getMaterialType&&l.getMaterialType(e)}),d.push(Promise.all(this._invokeAll(function(l){return l.extendMaterialParams&&l.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=h.DoubleSide);const f=o.alphaMode||wi.OPAQUE;if(f===wi.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,f===wi.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&s!==h.MeshBasicMaterial&&(d.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new h.Vector2(1,1),o.normalTexture.scale!==void 0)){const u=o.normalTexture.scale;a.normalScale.set(u,u)}if(o.occlusionTexture!==void 0&&s!==h.MeshBasicMaterial&&(d.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&s!==h.MeshBasicMaterial){const u=o.emissiveFactor;a.emissive=new h.Color().setRGB(u[0],u[1],u[2],h.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&s!==h.MeshBasicMaterial&&d.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,h.SRGBColorSpace)),Promise.all(d).then(function(){const u=new s(a);return o.name&&(u.name=o.name),ut(u,o),t.associations.set(u,{materials:e}),o.extensions&&Ft(i,u,o),u})}createUniqueName(e){const t=h.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,i=this.primitiveCache;function o(a){return n[se.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return Ir(c,a,t)})}const s=[];for(let a=0,c=e.length;a<c;a++){const d=e[a],f=ra(d),u=i[f];if(u)s.push(u.promise);else{let l;d.extensions&&d.extensions[se.KHR_DRACO_MESH_COMPRESSION]?l=o(d):l=Ir(new h.BufferGeometry,d,t),i[f]={primitive:d,promise:l},s.push(l)}}return Promise.all(s)}loadMesh(e){const t=this,n=this.json,i=this.extensions,o=n.meshes[e],s=o.primitives,a=[];for(let c=0,d=s.length;c<d;c++){const f=s[c].material===void 0?ta(this.cache):this.getDependency("material",s[c].material);a.push(f)}return a.push(t.loadGeometries(s)),Promise.all(a).then(function(c){const d=c.slice(0,c.length-1),f=c[c.length-1],u=[];for(let g=0,y=f.length;g<y;g++){const b=f[g],m=s[g];let _;const x=d[g];if(m.mode===Xe.TRIANGLES||m.mode===Xe.TRIANGLE_STRIP||m.mode===Xe.TRIANGLE_FAN||m.mode===void 0)_=o.isSkinnedMesh===!0?new h.SkinnedMesh(b,x):new h.Mesh(b,x),_.isSkinnedMesh===!0&&_.normalizeSkinWeights(),m.mode===Xe.TRIANGLE_STRIP?_.geometry=xr(_.geometry,h.TriangleStripDrawMode):m.mode===Xe.TRIANGLE_FAN&&(_.geometry=xr(_.geometry,h.TriangleFanDrawMode));else if(m.mode===Xe.LINES)_=new h.LineSegments(b,x);else if(m.mode===Xe.LINE_STRIP)_=new h.Line(b,x);else if(m.mode===Xe.LINE_LOOP)_=new h.LineLoop(b,x);else if(m.mode===Xe.POINTS)_=new h.Points(b,x);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);Object.keys(_.geometry.morphAttributes).length>0&&ia(_,o),_.name=t.createUniqueName(o.name||"mesh_"+e),ut(_,o),m.extensions&&Ft(i,_,m),t.assignFinalMaterial(_),u.push(_)}for(let g=0,y=u.length;g<y;g++)t.associations.set(u[g],{meshes:e,primitives:g});if(u.length===1)return o.extensions&&Ft(i,u[0],o),u[0];const l=new h.Group;o.extensions&&Ft(i,l,o),t.associations.set(l,{meshes:e});for(let g=0,y=u.length;g<y;g++)l.add(u[g]);return l})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new h.PerspectiveCamera(h.MathUtils.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new h.OrthographicCamera(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),ut(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,o=t.joints.length;i<o;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const o=i.pop(),s=i,a=[],c=[];for(let d=0,f=s.length;d<f;d++){const u=s[d];if(u){a.push(u);const l=new h.Matrix4;o!==null&&l.fromArray(o.array,d*16),c.push(l)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[d])}return new h.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,s=[],a=[],c=[],d=[],f=[];for(let u=0,l=i.channels.length;u<l;u++){const g=i.channels[u],y=i.samplers[g.sampler],b=g.target,m=b.node,_=i.parameters!==void 0?i.parameters[y.input]:y.input,x=i.parameters!==void 0?i.parameters[y.output]:y.output;b.node!==void 0&&(s.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",_)),c.push(this.getDependency("accessor",x)),d.push(y),f.push(b))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(c),Promise.all(d),Promise.all(f)]).then(function(u){const l=u[0],g=u[1],y=u[2],b=u[3],m=u[4],_=[];for(let w=0,S=l.length;w<S;w++){const M=l[w],I=g[w],C=y[w],D=b[w],L=m[w];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();const R=n._createAnimationTracks(M,I,C,D,L);if(R)for(let N=0;N<R.length;N++)_.push(R[N])}const x=new h.AnimationClip(o,void 0,_);return ut(x,i),x})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(o){const s=n._getNodeRef(n.meshCache,i.mesh,o);return i.weights!==void 0&&s.traverse(function(a){if(a.isMesh)for(let c=0,d=i.weights.length;c<d;c++)a.morphTargetInfluences[c]=i.weights[c]}),s})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],o=n._loadNodeShallow(e),s=[],a=i.children||[];for(let d=0,f=a.length;d<f;d++)s.push(n.getDependency("node",a[d]));const c=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([o,Promise.all(s),c]).then(function(d){const f=d[0],u=d[1],l=d[2];l!==null&&f.traverse(function(g){g.isSkinnedMesh&&g.bind(l,oa)});for(let g=0,y=u.length;g<y;g++)f.add(u[g]);if(f.userData.pivot!==void 0&&u.length>0){const g=f.userData.pivot,y=u[0];f.pivot=new h.Vector3().fromArray(g),f.position.x-=g[0],f.position.y-=g[1],f.position.z-=g[2],y.position.set(0,0,0),delete f.userData.pivot}return f})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],s=o.name?i.createUniqueName(o.name):"",a=[],c=i._invokeOne(function(d){return d.createNodeMesh&&d.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(i.getDependency("camera",o.camera).then(function(d){return i._getNodeRef(i.cameraCache,o.camera,d)})),i._invokeAll(function(d){return d.createNodeAttachment&&d.createNodeAttachment(e)}).forEach(function(d){a.push(d)}),this.nodeCache[e]=Promise.all(a).then(function(d){let f;if(o.isBone===!0?f=new h.Bone:d.length>1?f=new h.Group:d.length===1?f=d[0]:f=new h.Object3D,f!==d[0])for(let u=0,l=d.length;u<l;u++)f.add(d[u]);if(o.name&&(f.userData.name=o.name,f.name=s),ut(f,o),o.extensions&&Ft(n,f,o),o.matrix!==void 0){const u=new h.Matrix4;u.fromArray(o.matrix),f.applyMatrix4(u)}else o.translation!==void 0&&f.position.fromArray(o.translation),o.rotation!==void 0&&f.quaternion.fromArray(o.rotation),o.scale!==void 0&&f.scale.fromArray(o.scale);if(!i.associations.has(f))i.associations.set(f,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){const u=i.associations.get(f);i.associations.set(f,{...u})}return i.associations.get(f).nodes=e,f}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,o=new h.Group;n.name&&(o.name=i.createUniqueName(n.name)),ut(o,n),n.extensions&&Ft(t,o,n);const s=n.nodes||[],a=[];for(let c=0,d=s.length;c<d;c++)a.push(i.getDependency("node",s[c]));return Promise.all(a).then(function(c){for(let f=0,u=c.length;f<u;f++){const l=c[f];l.parent!==null?o.add(Co(l)):o.add(l)}const d=f=>{const u=new Map;for(const[l,g]of i.associations)(l instanceof h.Material||l instanceof h.Texture)&&u.set(l,g);return f.traverse(l=>{const g=i.associations.get(l);g!=null&&u.set(l,g)}),u};return i.associations=d(o),o})}_createAnimationTracks(e,t,n,i,o){const s=[],a=e.name?e.name:e.uuid,c=[];bt[o.path]===bt.weights?e.traverse(function(l){l.morphTargetInfluences&&c.push(l.name?l.name:l.uuid)}):c.push(a);let d;switch(bt[o.path]){case bt.weights:d=h.NumberKeyframeTrack;break;case bt.rotation:d=h.QuaternionKeyframeTrack;break;case bt.translation:case bt.scale:d=h.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:d=h.NumberKeyframeTrack;break;case 2:case 3:default:d=h.VectorKeyframeTrack;break}break}const f=i.interpolation!==void 0?ea[i.interpolation]:h.InterpolateLinear,u=this._getArrayFromAccessor(n);for(let l=0,g=c.length;l<g;l++){const y=new d(c[l]+"."+bt[o.path],t.array,u,f);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),s.push(y)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Si(t.constructor),i=new Float32Array(t.length);for(let o=0,s=t.length;o<s;o++)i[o]=t[o]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof h.QuaternionKeyframeTrack?Ho:Tr;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function ca(r,e,t){const n=e.attributes,i=new h.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,d=a.max;if(c!==void 0&&d!==void 0){if(i.set(new h.Vector3(c[0],c[1],c[2]),new h.Vector3(d[0],d[1],d[2])),a.normalized){const f=Si(Vt[a.componentType]);i.min.multiplyScalar(f),i.max.multiplyScalar(f)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const a=new h.Vector3,c=new h.Vector3;for(let d=0,f=o.length;d<f;d++){const u=o[d];if(u.POSITION!==void 0){const l=t.json.accessors[u.POSITION],g=l.min,y=l.max;if(g!==void 0&&y!==void 0){if(c.setX(Math.max(Math.abs(g[0]),Math.abs(y[0]))),c.setY(Math.max(Math.abs(g[1]),Math.abs(y[1]))),c.setZ(Math.max(Math.abs(g[2]),Math.abs(y[2]))),l.normalized){const b=Si(Vt[l.componentType]);c.multiplyScalar(b)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}r.boundingBox=i;const s=new h.Sphere;i.getCenter(s.center),s.radius=i.min.distanceTo(i.max)/2,r.boundingSphere=s}function Ir(r,e,t){const n=e.attributes,i=[];function o(s,a){return t.getDependency("accessor",s).then(function(c){r.setAttribute(a,c)})}for(const s in n){const a=bi[s]||s.toLowerCase();a in r.attributes||i.push(o(n[s],a))}if(e.indices!==void 0&&!r.index){const s=t.getDependency("accessor",e.indices).then(function(a){r.setIndex(a)});i.push(s)}return h.ColorManagement.workingColorSpace!==h.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${h.ColorManagement.workingColorSpace}" not supported.`),ut(r,e),ca(r,e,t),Promise.all(i).then(function(){return e.targets!==void 0?na(r,e.targets,t):r})}class la{constructor(){this.loadingManager=new A.LoadingManager,this.loader=new Po(this.loadingManager)}async load(e){try{return new Promise(t=>{this.loader.load(e,n=>{var o;const i={scene:new Ee(n.scene),animations:this.convertAnimations(n.animations),cameras:(o=n.cameras)==null?void 0:o.map(s=>{const a=s instanceof A.PerspectiveCamera,c=s instanceof A.OrthographicCamera;return{name:s.name,type:s.type,fov:a?s.fov:void 0,aspect:a?s.aspect:void 0,near:a||c?s.near:.1,far:a||c?s.far:1e3}}),userData:n.userData};t(q.ok(i))},n=>{n.total>0},n=>{t(q.err(new H("Failed to load GLTF model",te.MODEL_LOAD_FAILED,{url:e,originalError:n})))})})}catch(t){return q.err(new H("Failed to initiate model loading",te.MODEL_LOAD_FAILED,{url:e,originalError:t}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}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 A.VectorKeyframeTrack?"vector":e instanceof A.QuaternionKeyframeTrack?"quaternion":e instanceof A.NumberKeyframeTrack?"number":e instanceof A.BooleanKeyframeTrack?"boolean":"number"}}class Cr{static createLoader(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();switch(t){case"gltf":case"glb":return new la;default:throw new H(`Unsupported file format: ${t}`,te.UNSUPPORTED_FORMAT,{url:e,extension:t})}}}const Pr={type:"change"},Ti={type:"start"},Dr={type:"end"},Pn=new h.Ray,Fr=new h.Plane,ua=Math.cos(70*h.MathUtils.DEG2RAD),Pe=new h.Vector3,qe=2*Math.PI,ue={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Mi=1e-6;class Rr extends h.Controls{constructor(e,t=null){super(e,t),this.state=ue.NONE,this.target=new h.Vector3,this.cursor=new h.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:h.MOUSE.ROTATE,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.PAN},this.touches={ONE:h.TOUCH.ROTATE,TWO:h.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 h.Vector3,this._lastQuaternion=new h.Quaternion,this._lastTargetPosition=new h.Vector3,this._quat=new h.Quaternion().setFromUnitVectors(e.up,new h.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new h.Spherical,this._sphericalDelta=new h.Spherical,this._scale=1,this._panOffset=new h.Vector3,this._rotateStart=new h.Vector2,this._rotateEnd=new h.Vector2,this._rotateDelta=new h.Vector2,this._panStart=new h.Vector2,this._panEnd=new h.Vector2,this._panDelta=new h.Vector2,this._dollyStart=new h.Vector2,this._dollyEnd=new h.Vector2,this._dollyDelta=new h.Vector2,this._dollyDirection=new h.Vector3,this._mouse=new h.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=da.bind(this),this._onPointerDown=ha.bind(this),this._onPointerUp=fa.bind(this),this._onContextMenu=ba.bind(this),this._onMouseWheel=ga.bind(this),this._onKeyDown=ya.bind(this),this._onTouchStart=va.bind(this),this._onTouchMove=xa.bind(this),this._onMouseDown=pa.bind(this),this._onMouseMove=ma.bind(this),this._interceptControlDown=wa.bind(this),this._interceptControlUp=_a.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="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(Pr),this.update(),this.state=ue.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Pe.copy(t).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===ue.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,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=qe:n>Math.PI&&(n-=qe),i<-Math.PI?i+=qe:i>Math.PI&&(i-=qe),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,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 o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=s!=this._spherical.radius}if(Pe.setFromSpherical(this._spherical),Pe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Pe),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){const a=Pe.length();s=this._clampDistance(a*this._scale);const c=a-s;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new h.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(),o=c!==this.object.zoom;const d=new h.Vector3(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(a),this.object.updateMatrixWorld(),s=Pe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;s!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position):(Pn.origin.copy(this.object.position),Pn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Pn.direction))<ua?this.object.lookAt(this.target):(Fr.setFromNormalAndCoplanarPoint(this.object.up,this.target),Pn.intersectPlane(Fr,this.target))))}else if(this.object.isOrthographicCamera){const s=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>Mi||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Mi||this._lastTargetPosition.distanceToSquared(this.target)>Mi?(this.dispatchEvent(Pr),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){Pe.setFromMatrixColumn(t,0),Pe.multiplyScalar(-e),this._panOffset.add(Pe)}_panUp(e,t){this.screenSpacePanning===!0?Pe.setFromMatrixColumn(t,1):(Pe.setFromMatrixColumn(t,0),Pe.crossVectors(this.object.up,Pe)),Pe.multiplyScalar(e),this._panOffset.add(Pe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Pe.copy(i).sub(this.target);let o=Pe.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/n.clientHeight,this.object.matrix),this._panUp(2*t*o/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(),i=e-n.left,o=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-(o/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),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_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),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,o=Math.sqrt(n*n+i*i);this._dollyStart.set(0,o)}_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),i=.5*(e.pageX+n.x),o=.5*(e.pageY+n.y);this._rotateEnd.set(i,o)}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),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}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,i=e.pageY-t.y,o=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,o),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 s=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(s,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 h.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 ha(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function da(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function fa(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Dr),this.state=ue.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 pa(r){let e;switch(r.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 h.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=ue.DOLLY;break;case h.MOUSE.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=ue.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=ue.ROTATE}break;case h.MOUSE.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=ue.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=ue.PAN}break;default:this.state=ue.NONE}this.state!==ue.NONE&&this.dispatchEvent(Ti)}function ma(r){switch(this.state){case ue.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case ue.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case ue.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function ga(r){this.enabled===!1||this.enableZoom===!1||this.state!==ue.NONE||(r.preventDefault(),this.dispatchEvent(Ti),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(Dr))}function ya(r){this.enabled!==!1&&this._handleKeyDown(r)}function va(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case h.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=ue.TOUCH_ROTATE;break;case h.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=ue.TOUCH_PAN;break;default:this.state=ue.NONE}break;case 2:switch(this.touches.TWO){case h.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=ue.TOUCH_DOLLY_PAN;break;case h.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=ue.TOUCH_DOLLY_ROTATE;break;default:this.state=ue.NONE}break;default:this.state=ue.NONE}this.state!==ue.NONE&&this.dispatchEvent(Ti)}function xa(r){switch(this._trackPointer(r),this.state){case ue.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case ue.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case ue.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case ue.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=ue.NONE}}function ba(r){this.enabled!==!1&&r.preventDefault()}function wa(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function _a(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const Ai=new h.Plane,Dn=new h.Raycaster,Wt=new h.Vector2,Ii=new h.Vector3;class Sa extends Rr{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:h.MOUSE.PAN,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.ROTATE},this.touches={ONE:h.TOUCH.PAN,TWO:h.TOUCH.DOLLY_ROTATE},this._panWorldStart=new h.Vector3}_handleMouseDownPan(e){if(super._handleMouseDownPan(e),this._panOffset.set(0,0,0),this.screenSpacePanning===!0)return;Ai.setFromNormalAndCoplanarPoint(this.object.up,this.target);const n=this.domElement.getBoundingClientRect();Wt.x=(e.clientX-n.left)/n.width*2-1,Wt.y=-((e.clientY-n.top)/n.height)*2+1,Dn.setFromCamera(Wt,this.object),Dn.ray.intersectPlane(Ai,this._panWorldStart)}_handleMouseMovePan(e){if(this.screenSpacePanning===!0){super._handleMouseMovePan(e);return}const n=this.domElement.getBoundingClientRect();Wt.x=(e.clientX-n.left)/n.width*2-1,Wt.y=-((e.clientY-n.top)/n.height)*2+1,Dn.setFromCamera(Wt,this.object),Dn.ray.intersectPlane(Ai,Ii)&&(Ii.sub(this._panWorldStart),this._panOffset.copy(Ii).negate(),this.update())}}class Or{constructor(e){this.controls=e,this.targetAdapter=xt.fromThreeVector(e.target)}get enabled(){return this.controls.enabled}set enabled(e){this.controls.enabled=e}get enableDamping(){return this.controls.enableDamping}set enableDamping(e){this.controls.enableDamping=e}get dampingFactor(){return this.controls.dampingFactor}set dampingFactor(e){this.controls.dampingFactor=e}get enableZoom(){return this.controls.enableZoom}set enableZoom(e){this.controls.enableZoom=e}get enableRotate(){return this.controls.enableRotate}set enableRotate(e){this.controls.enableRotate=e}get enablePan(){return this.controls.enablePan}set enablePan(e){this.controls.enablePan=e}get zoomSpeed(){return this.controls.zoomSpeed}set zoomSpeed(e){this.controls.zoomSpeed=e}get minDistance(){return this.controls.minDistance}set minDistance(e){this.controls.minDistance=e}get maxDistance(){return this.controls.maxDistance}set maxDistance(e){this.controls.maxDistance=e}get rotateSpeed(){return this.controls.rotateSpeed}set rotateSpeed(e){this.controls.rotateSpeed=e}get minPolarAngle(){return this.controls.minPolarAngle}set minPolarAngle(e){this.controls.minPolarAngle=e}get maxPolarAngle(){return this.controls.maxPolarAngle}set maxPolarAngle(e){this.controls.maxPolarAngle=e}get minAzimuthAngle(){return this.controls.minAzimuthAngle}set minAzimuthAngle(e){this.controls.minAzimuthAngle=e}get maxAzimuthAngle(){return this.controls.maxAzimuthAngle}set maxAzimuthAngle(e){this.controls.maxAzimuthAngle=e}get panSpeed(){return this.controls.panSpeed}set panSpeed(e){this.controls.panSpeed=e}get screenSpacePanning(){return this.controls.screenSpacePanning}set screenSpacePanning(e){this.controls.screenSpacePanning=e}get target(){return this.targetAdapter}update(){return this.controls.update()}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}getThreeControls(){return this.controls}}class Lr extends Or{constructor(e,t){const n=new Rr(e,t);super(n),this.orbitControls=n}get type(){return"orbit"}get autoRotate(){return this.orbitControls.autoRotate}set autoRotate(e){this.orbitControls.autoRotate=e}get autoRotateSpeed(){return this.orbitControls.autoRotateSpeed}set autoRotateSpeed(e){this.orbitControls.autoRotateSpeed=e}}class Nr extends Or{constructor(e,t){const n=new Sa(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const _n=class _n{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.getHeight(e)+this.getBevelSize(e))}};_n.HEIGHT_RATIO=.075,_n.BEVEL_RATIO=.25,_n.GAP_FACTOR=1.05;let Rt=_n;var pt=(r=>(r.SQUARE_WIRE="square_wire",r.HEXAGONAL_WIRE="hexagonal_wire",r.HEXAGONAL_GLASS="hexagonal_glass",r.STONE_TILES="stone_tiles",r.CUSTOM="custom",r))(pt||{});class Ta{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,i=new A.Color(e.color||8947848),o=new A.Color(e.centerLineColor||e.color||4473924),s=new A.GridHelper(t,n,o,i);if(e.opacity!==void 0&&e.opacity<1){const a=s.material;a.transparent=!0,a.opacity=e.opacity}return s}dispose(){}}class Ma{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var f;const t=new A.Group,n=((f=e.styleOptions)==null?void 0:f.hexRadius)||Math.floor(e.divisions/2),i=e.size/(n*2),o=new A.Color(e.color||8947848),s=e.opacity||.4,a=new A.LineBasicMaterial({color:o,transparent:!0,opacity:s}),c=i*Math.sqrt(3),d=i*2;for(let u=-n;u<=n;u++){const l=Math.max(-n,-u-n),g=Math.min(n,-u+n);for(let y=l;y<=g;y++){const b=c*(u+y/2),m=d*.75*y,_=[],x=Math.PI*2/6;for(let M=0;M<=6;M++){const I=M*x+Math.PI/6,C=b+i*Math.cos(I),D=m+i*Math.sin(I);_.push(new A.Vector3(C,0,D))}const w=new A.BufferGeometry().setFromPoints(_),S=new A.Line(w,a);t.add(S)}}return t}dispose(){}}class Aa{constructor(e,t,n){this.position=e,this.size=t,this.color=n,this.height=Rt.getHeight(this.size),this.bevel=Rt.getBevelSize(this.size)}createMesh(){const e=new A.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let d=0;d<6;d++){const f=t*Math.cos(d*n),u=t*Math.sin(d*n);d===0?e.moveTo(f,u):e.lineTo(f,u)}e.closePath();const i={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:128},o=new A.ExtrudeGeometry(e,i),s=new A.MeshPhysicalMaterial({color:new A.Color(16777215),metalness:0,roughness:.15,transparent:!0,transmission:1,thickness:.4,ior:1.5,opacity:1,clearcoat:1,clearcoatRoughness:.05,sheen:1,sheenColor:new A.Color(16777215),envMapIntensity:1}),a=new A.Mesh(o,s);a.receiveShadow=!0;const c=new A.Group;return c.add(a),c.position.set(this.position.x,this.position.y,this.position.z),c.rotation.x=Math.PI/2,c.rotation.z=Math.PI/6,c}}class Ia{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var d,f;const t=new A.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)||Math.floor(e.divisions/2),i=((f=e.styleOptions)==null?void 0:f.tileSize)||1,o=String(e.color||"#ffffff"),s=Rt.getGridSpacing(i),a=s.width,c=s.height;for(let u=-n;u<=n;u++){const l=Math.max(-n,-u-n),g=Math.min(n,-u+n);for(let y=l;y<=g;y++){const b=a*(u+y/2),m=c*.75*y,_=Rt.getYPosition(i),w=new Aa(new A.Vector3(b,_,m),i,o).createMesh();t.add(w)}}return t}dispose(){}}class Ca{constructor(){this.name="Stone Tile Grid",this.textureLoader=new A.TextureLoader,this.loadedTextures=new Map}createGrid(e){var g,y,b,m;const t=new A.Group,n=e.size,i=e.divisions,o=n/i,s=o*.02,a=o-s,c=((g=e.styleOptions)==null?void 0:g.height)||o*.05,d=((y=e.styleOptions)==null?void 0:y.bevelSize)||c*.2,f=((b=e.styleOptions)==null?void 0:b.randomHeight)||!1,u=((m=e.styleOptions)==null?void 0:m.randomRotation)||!1,l=this.createStoneMaterial(e);for(let _=0;_<i;_++)for(let x=0;x<i;x++){const w=(_-i/2)*o+o/2,S=(x-i/2)*o+o/2,M=f?c*(.8+Math.random()*.4):c,I=new A.Shape,C=a/2;I.moveTo(-C,-C),I.lineTo(C,-C),I.lineTo(C,C),I.lineTo(-C,C),I.closePath();const D={depth:M,bevelEnabled:!0,bevelSize:d,bevelThickness:d,bevelSegments:2},L=new A.ExtrudeGeometry(I,D);L.rotateX(-Math.PI/2);const R=new A.Mesh(L,l);R.position.set(w,-M/2,S),R.castShadow=!0,R.receiveShadow=!0,u&&(R.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(R)}return t}createStoneMaterial(e){var s,a,c,d,f;const t=new A.Color(e.color||8421504),n=((s=e.styleOptions)==null?void 0:s.metalness)||0,i=((a=e.styleOptions)==null?void 0:a.roughness)||.8,o={color:t,metalness:n,roughness:i};if((c=e.styleOptions)!=null&&c.texture){const u=this.loadTexture(e.styleOptions.texture);u&&(o.map=u,u.wrapS=u.wrapT=A.RepeatWrapping,u.repeat.set(1,1))}if((d=e.styleOptions)!=null&&d.normalMap){const u=this.loadTexture(e.styleOptions.normalMap);u&&(o.normalMap=u,u.wrapS=u.wrapT=A.RepeatWrapping,u.repeat.set(1,1))}if((f=e.styleOptions)!=null&&f.roughnessMap){const u=this.loadTexture(e.styleOptions.roughnessMap);u&&(o.roughnessMap=u,u.wrapS=u.wrapT=A.RepeatWrapping,u.repeat.set(1,1))}return new A.MeshStandardMaterial(o)}loadTexture(e){if(this.loadedTextures.has(e))return this.loadedTextures.get(e)||null;try{const t=this.textureLoader.load(e);return this.loadedTextures.set(e,t),t}catch(t){return console.warn("Failed to load texture:",e,t),null}}dispose(){this.loadedTextures.forEach(e=>{e.dispose()}),this.loadedTextures.clear()}}const pr=class pr{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 o=this.gridStyles.get(pt.SQUARE_WIRE);if(!o)throw new Error("Square wire grid style not found");return o.createGrid(t)}const i=n.createGrid(t);return i.name=`Grid_${e}`,i}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()}};pr.gridStyles=new Map([[pt.SQUARE_WIRE,new Ta],[pt.HEXAGONAL_WIRE,new Ma],[pt.HEXAGONAL_GLASS,new Ia],[pt.STONE_TILES,new Ca]]);let Fn=pr;class Pa{addHelpers(e,t){try{if(!(e instanceof Dt))return q.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene();if(t.grid){const i=n.userData,o=typeof t.grid=="object"?t.grid:null,s={enabled:!0,color:(o==null?void 0:o.colorGrid)||t.gridColor||"#AAAAAA",type:o!=null&&o.type?o.type:pt.HEXAGONAL_GLASS,opacity:o==null?void 0:o.opacity,styleOptions:o==null?void 0:o.styleOptions};if(n.userData={...i,gridOptions:s},o!=null&&o.size||o!=null&&o.divisions){const a=s.type||pt.HEXAGONAL_GLASS,c=o.size||10,d=o.divisions||10,f={size:c,divisions:d,color:s.color,opacity:s.opacity,styleOptions:{hexRadius:Math.floor(d/2),tileSize:1,...s.styleOptions}},u=Fn.createGrid(a,f);u.userData.isGrid=!0,u.userData.isDefaultGrid=!0,n.add(u)}}if(t.axes){const i=t.axesSize||5,o=new A.AxesHelper(i);n.add(o)}return q.ok(void 0)}catch(n){return q.err(new H("Failed to add helpers to scene",te.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}addDynamicGrid(e,t,n=1.2){try{if(!(e instanceof Dt))return q.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const i=e.getThreeScene(),o=i.userData,s=o==null?void 0:o.gridOptions;if(!(s!=null&&s.enabled))return q.ok(void 0);const a=[];i.traverse(I=>{var C,D,L;((C=I.userData)!=null&&C.isGrid||(D=I.userData)!=null&&D.isHexGrid||(L=I.userData)!=null&&L.isDefaultGrid)&&a.push(I)}),a.forEach(I=>i.remove(I));let c;t instanceof Ee||"getThreeObject"in t&&typeof t.getThreeObject=="function"?c=t.getThreeObject():c=t;const f=new A.Box3().setFromObject(c).getSize(new A.Vector3),l=1,y=Rt.getGridSpacing(l).width,b=Math.max(f.x,f.z)*n;let m=0,_=y;for(;_<b&&m<20;)m++,_+=2*y;b<y*.8?m=0:m<3&&b>y*2&&(m=3);const x=s.type||pt.HEXAGONAL_GLASS,S={size:Math.max(f.x,f.z)*n,divisions:m*2+1,color:s.color,opacity:s.opacity,styleOptions:{hexRadius:m,tileSize:l,...s.styleOptions}},M=Fn.createGrid(x,S);return M.userData.isGrid=!0,M.userData.isHexGrid=!0,i.add(M),q.ok(void 0)}catch(i){return q.err(new H("Failed to add dynamic grid",te.SCENE_OPERATION_FAILED,{originalError:i}))}}addLighting(e,t){try{if(!(e instanceof Dt))return q.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene();if(t.ambient){const i=new A.Color(t.ambient.color||"#404040"),o=t.ambient.intensity??Math.PI,s=new A.AmbientLight(i,o);n.add(s)}if(t.hemisphere){const i=new A.Color(t.hemisphere.skyColor||"#ffffbb"),o=new A.Color(t.hemisphere.groundColor||"#080820"),s=t.hemisphere.intensity??1,a=new A.HemisphereLight(i,o,s);n.add(a)}if(t.directional){const i=new A.Color(t.directional.color||"#ffffff"),o=t.directional.intensity??Math.PI,s=new A.DirectionalLight(i,o);if(t.directional.position){const a=t.directional.position;if(a instanceof A.Vector3)s.position.copy(a);else if(Array.isArray(a))s.position.set(a[0],a[1],a[2]);else if(typeof a=="object"&&"x"in a&&"y"in a&&"z"in a){const c=a;s.position.set(c.x,c.y,c.z)}}else s.position.set(6,6,6);if(t.directional.castShadow&&(s.castShadow=!0,t.directional.shadow)){const a=t.directional.shadow;if(a.mapSize&&(s.shadow.mapSize.width=a.mapSize.width,s.shadow.mapSize.height=a.mapSize.height),a.camera){const c=s.shadow.camera;a.camera.near!==void 0&&(c.near=a.camera.near),a.camera.far!==void 0&&(c.far=a.camera.far),a.camera.left!==void 0&&(c.left=a.camera.left),a.camera.right!==void 0&&(c.right=a.camera.right),a.camera.top!==void 0&&(c.top=a.camera.top),a.camera.bottom!==void 0&&(c.bottom=a.camera.bottom)}a.bias!==void 0&&(s.shadow.bias=a.bias),a.radius!==void 0&&(s.shadow.radius=a.radius)}s.target.position.set(0,0,0),n.add(s),n.add(s.target),s.shadow&&s.shadow.camera.updateProjectionMatrix()}return q.ok(void 0)}catch(n){return q.err(new H("Failed to add lighting to scene",te.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}createGradientBackground(e,t){try{if(!(e instanceof Dt))return q.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));const n=e.getThreeScene(),i=document.createElement("canvas");i.width=2,i.height=512;const o=i.getContext("2d");if(!o)return q.err(new H("Failed to create canvas context",te.SCENE_OPERATION_FAILED));const s=o.createLinearGradient(0,0,0,i.height);s.addColorStop(0,t.topColor),s.addColorStop(1,t.bottomColor),o.fillStyle=s,o.fillRect(0,0,i.width,i.height);const a=new A.CanvasTexture(i);return a.needsUpdate=!0,n.background=a,q.ok(void 0)}catch(n){return q.err(new H("Failed to create gradient background",te.SCENE_OPERATION_FAILED,{originalError:n,options:t}))}}fitCameraToObject(e,t,n){try{let i;e instanceof Ee||"getThreeObject"in e&&typeof e.getThreeObject=="function"?i=e.getThreeObject():i=e;let o;t instanceof yi||"getThreeCamera"in t&&typeof t.getThreeCamera=="function"?o=t.getThreeCamera():o=t;let s;n instanceof Lr||n instanceof Nr||"getThreeControls"in n&&typeof n.getThreeControls=="function"?s=n.getThreeControls():s=n;const a=new A.Box3().setFromObject(i),c=a.getCenter(new A.Vector3),d=a.getSize(new A.Vector3),f=Math.max(d.x,d.y,d.z);let u;"fov"in o?u=o.fov*(Math.PI/180):u=50*(Math.PI/180);let l=Math.abs(f/2/Math.tan(u/2));l*=2;const g=-Math.PI/4,y=Math.PI/8,b=c.x+l*Math.sin(g)*Math.cos(y),m=c.y+l*Math.sin(y),_=c.z+l*Math.cos(g)*Math.cos(y);return o.position.set(b,m,_),o.lookAt(c),o.updateProjectionMatrix(),s&&s.target&&(s.target.copy(c),s.update()),q.ok(void 0)}catch(i){return q.err(new H("Failed to fit camera to object",te.CAMERA_INIT_FAILED,{originalError:i}))}}}const kr=0,Da=1,Br=2,zr=2,Ci=1.25,Ur=1,Oe=6*4+4+4,De=Oe/4,Pi=65535,Fa=Pi<<16,Rn=Math.pow(2,-24),Di=Symbol("SKIP_GENERATION"),Er={strategy:kr,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Di]:!1};function _e(r,e,t){return t.min.x=e[r],t.min.y=e[r+1],t.min.z=e[r+2],t.max.x=e[r+3],t.max.y=e[r+4],t.max.z=e[r+5],t}function Gr(r){let e=-1,t=-1/0;for(let n=0;n<3;n++){const i=r[n+3]-r[n];i>t&&(t=i,e=n)}return e}function Vr(r,e){e.set(r)}function Wr(r,e,t){let n,i;for(let o=0;o<3;o++){const s=o+3;n=r[o],i=e[o],t[o]=n<i?n:i,n=r[s],i=e[s],t[s]=n>i?n:i}}function On(r,e,t){for(let n=0;n<3;n++){const i=e[r+2*n],o=e[r+2*n+1],s=i-o,a=i+o;s<t[n]&&(t[n]=s),a>t[n+3]&&(t[n+3]=a)}}function un(r){const e=r[3]-r[0],t=r[4]-r[1],n=r[5]-r[2];return 2*(e*t+t*n+n*e)}function Ae(r,e){return e[r+15]===Pi}function Be(r,e){return e[r+6]}function ze(r,e){return e[r+14]}function Le(r){return r+De}function Ne(r,e){const t=e[r+6];return r+t*De}function Ln(r,e){return e[r+7]}function gd(r){return r}function Fi(r,e,t,n,i){let o=1/0,s=1/0,a=1/0,c=-1/0,d=-1/0,f=-1/0,u=1/0,l=1/0,g=1/0,y=-1/0,b=-1/0,m=-1/0;const _=r.offset||0;for(let x=(e-_)*6,w=(e+t-_)*6;x<w;x+=6){const S=r[x+0],M=r[x+1],I=S-M,C=S+M;I<o&&(o=I),C>c&&(c=C),S<u&&(u=S),S>y&&(y=S);const D=r[x+2],L=r[x+3],R=D-L,N=D+L;R<s&&(s=R),N>d&&(d=N),D<l&&(l=D),D>b&&(b=D);const O=r[x+4],B=r[x+5],z=O-B,X=O+B;z<a&&(a=z),X>f&&(f=X),O<g&&(g=O),O>m&&(m=O)}n[0]=o,n[1]=s,n[2]=a,n[3]=c,n[4]=d,n[5]=f,i[0]=u,i[1]=l,i[2]=g,i[3]=y,i[4]=b,i[5]=m}const mt=32,Ra=(r,e)=>r.candidate-e.candidate,wt=new Array(mt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Nn=new Float32Array(6);function Oa(r,e,t,n,i,o){let s=-1,a=0;if(o===kr)s=Gr(e),s!==-1&&(a=(e[s]+e[s+3])/2);else if(o===Da)s=Gr(r),s!==-1&&(a=La(t,n,i,s));else if(o===Br){const c=un(r);let d=Ci*i;const f=t.offset||0,u=(n-f)*6,l=(n+i-f)*6;for(let g=0;g<3;g++){const y=e[g],_=(e[g+3]-y)/mt;if(i<mt/4){const x=[...wt];x.length=i;let w=0;for(let M=u;M<l;M+=6,w++){const I=x[w];I.candidate=t[M+2*g],I.count=0;const{bounds:C,leftCacheBounds:D,rightCacheBounds:L}=I;for(let R=0;R<3;R++)L[R]=1/0,L[R+3]=-1/0,D[R]=1/0,D[R+3]=-1/0,C[R]=1/0,C[R+3]=-1/0;On(M,t,C)}x.sort(Ra);let S=i;for(let M=0;M<S;M++){const I=x[M];for(;M+1<S&&x[M+1].candidate===I.candidate;)x.splice(M+1,1),S--}for(let M=u;M<l;M+=6){const I=t[M+2*g];for(let C=0;C<S;C++){const D=x[C];I>=D.candidate?On(M,t,D.rightCacheBounds):(On(M,t,D.leftCacheBounds),D.count++)}}for(let M=0;M<S;M++){const I=x[M],C=I.count,D=i-I.count,L=I.leftCacheBounds,R=I.rightCacheBounds;let N=0;C!==0&&(N=un(L)/c);let O=0;D!==0&&(O=un(R)/c);const B=Ur+Ci*(N*C+O*D);B<d&&(s=g,d=B,a=I.candidate)}}else{for(let S=0;S<mt;S++){const M=wt[S];M.count=0,M.candidate=y+_+S*_;const I=M.bounds;for(let C=0;C<3;C++)I[C]=1/0,I[C+3]=-1/0}for(let S=u;S<l;S+=6){let C=~~((t[S+2*g]-y)/_);C>=mt&&(C=mt-1);const D=wt[C];D.count++,On(S,t,D.bounds)}const x=wt[mt-1];Vr(x.bounds,x.rightCacheBounds);for(let S=mt-2;S>=0;S--){const M=wt[S],I=wt[S+1];Wr(M.bounds,I.rightCacheBounds,M.rightCacheBounds)}let w=0;for(let S=0;S<mt-1;S++){const M=wt[S],I=M.count,C=M.bounds,L=wt[S+1].rightCacheBounds;I!==0&&(w===0?Vr(C,Nn):Wr(C,Nn,Nn)),w+=I;let R=0,N=0;w!==0&&(R=un(Nn)/c);const O=i-w;O!==0&&(N=un(L)/c);const B=Ur+Ci*(R*w+N*O);B<d&&(s=g,d=B,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${o} used.`);return{axis:s,pos:a}}function La(r,e,t,n){let i=0;const o=r.offset;for(let s=e,a=e+t;s<a;s++)i+=r[(s-o)*6+n*2];return i/t}class Ri{constructor(){this.boundingData=new Float32Array(6)}}function Na(r,e,t,n,i,o){let s=n,a=n+i-1;const c=o.pos,d=o.axis*2,f=t.offset||0;for(;;){for(;s<=a&&t[(s-f)*6+d]<c;)s++;for(;s<=a&&t[(a-f)*6+d]>=c;)a--;if(s<a){for(let u=0;u<e;u++){let l=r[s*e+u];r[s*e+u]=r[a*e+u],r[a*e+u]=l}for(let u=0;u<6;u++){const l=s-f,g=a-f,y=t[l*6+u];t[l*6+u]=t[g*6+u],t[g*6+u]=y}s++,a--}else return s}}let jr,kn,Oi,qr;const ka=Math.pow(2,32);function Li(r){return"count"in r?1:1+Li(r.left)+Li(r.right)}function Ba(r,e,t){return jr=new Float32Array(t),kn=new Uint32Array(t),Oi=new Uint16Array(t),qr=new Uint8Array(t),Ni(r,e)}function Ni(r,e){const t=r/4,n=r/2,i="count"in e,o=e.boundingData;for(let s=0;s<6;s++)jr[t+s]=o[s];if(i)return e.buffer?(qr.set(new Uint8Array(e.buffer),r),r+e.buffer.byteLength):(kn[t+6]=e.offset,Oi[n+14]=e.count,Oi[n+15]=Pi,r+Oe);{const{left:s,right:a,splitAxis:c}=e,d=r+Oe;let f=Ni(d,s);const u=r/Oe,g=f/Oe-u;if(g>ka)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return kn[t+6]=g,kn[t+7]=c,Ni(f,a)}}function za(r,e,t,n,i,o){const{maxDepth:s,verbose:a,maxLeafSize:c,strategy:d,onProgress:f}=i,u=r.primitiveBuffer,l=r.primitiveBufferStride,g=new Float32Array(6);let y=!1;const b=new Ri;return Fi(e,t,n,b.boundingData,g),_(b,t,n,g),b;function m(x){f&&f((x-o.offset)/o.count)}function _(x,w,S,M=null,I=0){if(!y&&I>=s&&(y=!0,a&&console.warn(`BVH: Max depth of ${s} reached when generating BVH. Consider increasing maxDepth.`)),S<=c||I>=s)return m(w+S),x.offset=w,x.count=S,x;const C=Oa(x.boundingData,M,e,w,S,d);if(C.axis===-1)return m(w+S),x.offset=w,x.count=S,x;const D=Na(u,l,e,w,S,C);if(D===w||D===w+S)m(w+S),x.offset=w,x.count=S;else{x.splitAxis=C.axis;const L=new Ri,R=w,N=D-w;x.left=L,Fi(e,R,N,L.boundingData,g),_(L,R,N,g,I+1);const O=new Ri,B=D,z=S-N;x.right=O,Fi(e,B,z,O.boundingData,g),_(O,B,z,g,I+1)}return x}}function Ua(r,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=r.getRootRanges(e.range),i=n[0],o=n[n.length-1],s={offset:i.offset,count:o.offset+o.count-i.offset},a=new Float32Array(6*s.count);a.offset=s.offset,r.computePrimitiveBounds(s.offset,s.count,a),r._roots=n.map(c=>{const d=za(r,a,c.offset,c.count,e,s),f=Li(d),u=new t(Oe*f);return Ba(0,d,u),u})}class ki{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 ye=new Ea;let _t,jt;const qt=[],Bn=new ki(()=>new h.Box3);function Ga(r,e,t,n,i,o){_t=Bn.getPrimitive(),jt=Bn.getPrimitive(),qt.push(_t,jt),ye.setBuffer(r._roots[e]);const s=Bi(0,r.geometry,t,n,i,o);ye.clearBuffer(),Bn.releasePrimitive(_t),Bn.releasePrimitive(jt),qt.pop(),qt.pop();const a=qt.length;return a>0&&(jt=qt[a-1],_t=qt[a-2]),s}function Bi(r,e,t,n,i=null,o=0,s=0){const{float32Array:a,uint16Array:c,uint32Array:d}=ye;let f=r*2;if(Ae(f,c)){const l=Be(r,d),g=ze(f,c);return _e(r,a,_t),n(l,g,!1,s,o+r/De,_t)}else{let R=function(O){const{uint16Array:B,uint32Array:z}=ye;let X=O*2;for(;!Ae(X,B);)O=Le(O),X=O*2;return Be(O,z)},N=function(O){const{uint16Array:B,uint32Array:z}=ye;let X=O*2;for(;!Ae(X,B);)O=Ne(O,z),X=O*2;return Be(O,z)+ze(X,B)};const l=Le(r),g=Ne(r,d);let y=l,b=g,m,_,x,w;if(i&&(x=_t,w=jt,_e(y,a,x),_e(b,a,w),m=i(x),_=i(w),_<m)){y=g,b=l;const O=m;m=_,_=O,x=w}x||(x=_t,_e(y,a,x));const S=Ae(y*2,c),M=t(x,S,m,s+1,o+y/De);let I;if(M===zr){const O=R(y),z=N(y)-O;I=n(O,z,!0,s+1,o+y/De,x)}else I=M&&Bi(y,e,t,n,i,o,s+1);if(I)return!0;w=jt,_e(b,a,w);const C=Ae(b*2,c),D=t(w,C,_,s+1,o+b/De);let L;if(D===zr){const O=R(b),z=N(b)-O;L=n(O,z,!0,s+1,o+b/De,w)}else L=D&&Bi(b,e,t,n,i,o,s+1);return!!L}}const hn=new ye.constructor,zn=new ye.constructor,St=new ki(()=>new h.Box3),Zt=new h.Box3,Yt=new h.Box3,zi=new h.Box3,Ui=new h.Box3;let Ei=!1;function Va(r,e,t,n){if(Ei)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ei=!0;const i=r._roots,o=e._roots;let s,a=0,c=0;const d=new h.Matrix4().copy(t).invert();for(let f=0,u=i.length;f<u;f++){hn.setBuffer(i[f]),c=0;const l=St.getPrimitive();_e(0,hn.float32Array,l),l.applyMatrix4(d);for(let g=0,y=o.length;g<y&&(zn.setBuffer(o[g]),s=rt(0,0,t,d,n,a,c,0,0,l),zn.clearBuffer(),c+=o[g].byteLength/Oe,!s);g++);if(St.releasePrimitive(l),hn.clearBuffer(),a+=i[f].byteLength/Oe,s)break}return Ei=!1,s}function rt(r,e,t,n,i,o=0,s=0,a=0,c=0,d=null,f=!1){let u,l;f?(u=zn,l=hn):(u=hn,l=zn);const g=u.float32Array,y=u.uint32Array,b=u.uint16Array,m=l.float32Array,_=l.uint32Array,x=l.uint16Array,w=r*2,S=e*2,M=Ae(w,b),I=Ae(S,x);let C=!1;if(I&&M)f?C=i(Be(e,_),ze(e*2,x),Be(r,y),ze(r*2,b),c,s+e/De,a,o+r/De):C=i(Be(r,y),ze(r*2,b),Be(e,_),ze(e*2,x),a,o+r/De,c,s+e/De);else if(I){const D=St.getPrimitive();_e(e,m,D),D.applyMatrix4(t);const L=Le(r),R=Ne(r,y);_e(L,g,Zt),_e(R,g,Yt);const N=D.intersectsBox(Zt),O=D.intersectsBox(Yt);C=N&&rt(e,L,n,t,i,s,o,c,a+1,D,!f)||O&&rt(e,R,n,t,i,s,o,c,a+1,D,!f),St.releasePrimitive(D)}else{const D=Le(e),L=Ne(e,_);_e(D,m,zi),_e(L,m,Ui);const R=d.intersectsBox(zi),N=d.intersectsBox(Ui);if(R&&N)C=rt(r,D,t,n,i,o,s,a,c+1,d,f)||rt(r,L,t,n,i,o,s,a,c+1,d,f);else if(R)if(M)C=rt(r,D,t,n,i,o,s,a,c+1,d,f);else{const O=St.getPrimitive();O.copy(zi).applyMatrix4(t);const B=Le(r),z=Ne(r,y);_e(B,g,Zt),_e(z,g,Yt);const X=O.intersectsBox(Zt),J=O.intersectsBox(Yt);C=X&&rt(D,B,n,t,i,s,o,c,a+1,O,!f)||J&&rt(D,z,n,t,i,s,o,c,a+1,O,!f),St.releasePrimitive(O)}else if(N)if(M)C=rt(r,L,t,n,i,o,s,a,c+1,d,f);else{const O=St.getPrimitive();O.copy(Ui).applyMatrix4(t);const B=Le(r),z=Ne(r,y);_e(B,g,Zt),_e(z,g,Yt);const X=O.intersectsBox(Zt),J=O.intersectsBox(Yt);C=X&&rt(L,B,n,t,i,s,o,c,a+1,O,!f)||J&&rt(L,z,n,t,i,s,o,c,a+1,O,!f),St.releasePrimitive(O)}}return C}const Zr=new h.Box3,Kt=new Float32Array(6);class Wa{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Er,...e},Ua(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,i){let o=1/0,s=1/0,a=1/0,c=-1/0,d=-1/0,f=-1/0;for(let u=e,l=e+t;u<l;u++){this.writePrimitiveBounds(u,Kt,0);const[g,y,b,m,_,x]=Kt;g<o&&(o=g),m>c&&(c=m),y<s&&(s=y),_>d&&(d=_),b<a&&(a=b),x>f&&(f=x)}return n[i+0]=o,n[i+1]=s,n[i+2]=a,n[i+3]=c,n[i+4]=d,n[i+5]=f,n}computePrimitiveBounds(e,t,n){const i=n.offset||0;for(let o=e,s=e+t;o<s;o++){this.writePrimitiveBounds(o,Kt,0);const[a,c,d,f,u,l]=Kt,g=(a+f)/2,y=(c+u)/2,b=(d+l)/2,m=(f-a)/2,_=(u-c)/2,x=(l-d)/2,w=(o-i)*6;n[w+0]=g,n[w+1]=m+(Math.abs(g)+m)*Rn,n[w+2]=y,n[w+3]=_+(Math.abs(y)+_)*Rn,n[w+4]=b,n[w+5]=x+(Math.abs(b)+x)*Rn}return n}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,i=t.length;n<i;n++)t[n]+=e;else{const n=this._roots;for(let i=0;i<n.length;i++){const o=n[i],s=new Uint32Array(o),a=new Uint16Array(o),c=o.byteLength/Oe;for(let d=0;d<c;d++){const f=De*d,u=2*f;Ae(u,a)&&(s[f+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],i=new Uint32Array(n),o=new Uint16Array(n);s(0);function s(a,c=0){const d=a*2,f=Ae(d,o);if(f){const u=i[a+6],l=o[d+14];e(c,f,new Float32Array(n,a*4,6),u,l)}else{const u=Le(a),l=Ne(a,i),g=Ln(a,i);e(c,f,new Float32Array(n,a*4,6),g)||(s(u,c+1),s(l,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const i=e[t],o=new Uint32Array(i),s=new Uint16Array(i),a=new Float32Array(i),c=i.byteLength/Oe;for(let d=c-1;d>=0;d--){const f=d*De,u=f*2;if(Ae(u,s)){const g=Be(f,o),y=ze(u,s);this.writePrimitiveRangeBounds(g,y,Kt,0),a.set(Kt,f)}else{const g=Le(f),y=Ne(f,o);for(let b=0;b<3;b++){const m=a[g+b],_=a[g+b+3],x=a[y+b],w=a[y+b+3];a[f+b]=m<x?m:x,a[f+b+3]=_>w?_:w}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{_e(0,new Float32Array(n),Zr),e.union(Zr)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:i,intersectsPrimitive:o,scratchPrimitive:s,iterate:a}=e;if(i&&o){const u=i;i=(l,g,y,b,m)=>u(l,g,y,b,m)?!0:a(l,g,this,o,y,b,s)}else i||(o?i=(u,l,g,y)=>a(u,l,this,o,g,y,s):i=(u,l,g)=>g);let c=!1,d=0;const f=this._roots;for(let u=0,l=f.length;u<l;u++){const g=f[u];if(c=Ga(this,u,n,i,t,d),c)break;d+=g.byteLength/Oe}return c}bvhcast(e,t,n){let{intersectsRanges:i}=n;return Va(this,e,t,i)}}function ja(){return typeof SharedArrayBuffer<"u"}function Un(r){return r.index?r.index.count:r.attributes.position.count}function En(r){return Un(r)/3}function Yr(r,e=ArrayBuffer){return r>65535?new Uint32Array(new e(4*r)):new Uint16Array(new e(2*r))}function qa(r,e){if(!r.index){const t=r.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=Yr(t,n);r.setIndex(new h.BufferAttribute(i,1));for(let o=0;o<t;o++)i[o]=o}}function Za(r,e,t){const n=Un(r)/t,i=e||r.drawRange,o=i.start/t,s=(i.start+i.count)/t,a=Math.max(0,o),c=Math.min(n,s)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function Ya(r,e){return r.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Kr(r,e,t){const n=Za(r,e,t),i=Ya(r,t);if(!i.length)return[n];const o=[],s=n.offset,a=n.offset+n.count,c=Un(r)/t,d=[];for(const l of i){const{offset:g,count:y}=l,b=g,m=isFinite(y)?y:c-g,_=g+m;b<a&&_>s&&(d.push({pos:Math.max(s,b),isStart:!0}),d.push({pos:Math.min(a,_),isStart:!1}))}d.sort((l,g)=>l.pos!==g.pos?l.pos-g.pos:l.type==="end"?-1:1);let f=0,u=null;for(const l of d){const g=l.pos;f!==0&&g!==u&&o.push({offset:u,count:g-u}),f+=l.isStart?1:-1,u=g}return o}function Ka(r,e){const t=r[r.length-1],n=t.offset+t.count>2**16,i=r.reduce((d,f)=>d+f.count,0),o=n?4:2,s=e?new SharedArrayBuffer(i*o):new ArrayBuffer(i*o),a=n?new Uint32Array(s):new Uint16Array(s);let c=0;for(let d=0;d<r.length;d++){const{offset:f,count:u}=r[d];for(let l=0;l<u;l++)a[c+l]=f+l;c+=u}return a}class Xa extends Wa{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&&!ja())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={...Er,...t},t[Di]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const i=Kr(t,e.range,n),o=Ka(i,e.useSharedArrayBuffer);this._indirectBuffer=o}else qa(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new h.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Kr(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class gt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,i=-1/0;for(let o=0,s=e.length;o<s;o++){const c=e[o][t];n=c<n?c:n,i=c>i?c:i}this.min=n,this.max=i}setFromPoints(e,t){let n=1/0,i=-1/0;for(let o=0,s=t.length;o<s;o++){const a=t[o],c=e.dot(a);n=c<n?c:n,i=c>i?c:i}this.min=n,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}gt.prototype.setFromBox=function(){const r=new h.Vector3;return function(t,n){const i=n.min,o=n.max;let s=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let d=0;d<=1;d++)for(let f=0;f<=1;f++){r.x=i.x*c+o.x*(1-c),r.y=i.y*d+o.y*(1-d),r.z=i.z*f+o.z*(1-f);const u=t.dot(r);s=Math.min(u,s),a=Math.max(u,a)}this.min=s,this.max=a}}();const $a=function(){const r=new h.Vector3,e=new h.Vector3,t=new h.Vector3;return function(i,o,s){const a=i.start,c=r,d=o.start,f=e;t.subVectors(a,d),r.subVectors(i.end,i.start),e.subVectors(o.end,o.start);const u=t.dot(f),l=f.dot(c),g=f.dot(f),y=t.dot(c),m=c.dot(c)*g-l*l;let _,x;m!==0?_=(u*l-y*g)/m:_=0,x=(u+_*l)/g,s.x=_,s.y=x}}(),Gi=function(){const r=new h.Vector2,e=new h.Vector3,t=new h.Vector3;return function(i,o,s,a){$a(i,o,r);let c=r.x,d=r.y;if(c>=0&&c<=1&&d>=0&&d<=1){i.at(c,s),o.at(d,a);return}else if(c>=0&&c<=1){d<0?o.at(0,a):o.at(1,a),i.closestPointToPoint(a,!0,s);return}else if(d>=0&&d<=1){c<0?i.at(0,s):i.at(1,s),o.closestPointToPoint(s,!0,a);return}else{let f;c<0?f=i.start:f=i.end;let u;d<0?u=o.start:u=o.end;const l=e,g=t;if(i.closestPointToPoint(u,!0,e),o.closestPointToPoint(f,!0,t),l.distanceToSquared(u)<=g.distanceToSquared(f)){s.copy(l),a.copy(u);return}else{s.copy(f),a.copy(g);return}}}}(),Qa=function(){const r=new h.Vector3,e=new h.Vector3,t=new h.Plane,n=new h.Line3;return function(o,s){const{radius:a,center:c}=o,{a:d,b:f,c:u}=s;if(n.start=d,n.end=f,n.closestPointToPoint(c,!0,r).distanceTo(c)<=a||(n.start=d,n.end=u,n.closestPointToPoint(c,!0,r).distanceTo(c)<=a)||(n.start=f,n.end=u,n.closestPointToPoint(c,!0,r).distanceTo(c)<=a))return!0;const b=s.getPlane(t);if(Math.abs(b.distanceToPoint(c))<=a){const _=b.projectPoint(c,e);if(s.containsPoint(_))return!0}return!1}}(),Ja=["x","y","z"],yt=1e-15,Xr=yt*yt;function $e(r){return Math.abs(r)<yt}class st extends h.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new h.Vector3),this.satBounds=new Array(4).fill().map(()=>new gt),this.points=[this.a,this.b,this.c],this.plane=new h.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new h.Line3,this.needsUpdate=!0}intersectsSphere(e){return Qa(e,this)}update(){const e=this.a,t=this.b,n=this.c,i=this.points,o=this.satAxes,s=this.satBounds,a=o[0],c=s[0];this.getNormal(a),c.setFromPoints(a,i);const d=o[1],f=s[1];d.subVectors(e,t),f.setFromPoints(d,i);const u=o[2],l=s[2];u.subVectors(t,n),l.setFromPoints(u,i);const g=o[3],y=s[3];g.subVectors(n,e),y.setFromPoints(g,i);const b=d.length(),m=u.length(),_=g.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,b<yt?m<yt||_<yt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):m<yt?_<yt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):_<yt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}st.prototype.closestPointToSegment=function(){const r=new h.Vector3,e=new h.Vector3,t=new h.Line3;return function(i,o=null,s=null){const{start:a,end:c}=i,d=this.points;let f,u=1/0;for(let l=0;l<3;l++){const g=(l+1)%3;t.start.copy(d[l]),t.end.copy(d[g]),Gi(t,i,r,e),f=r.distanceToSquared(e),f<u&&(u=f,o&&o.copy(r),s&&s.copy(e))}return this.closestPointToPoint(a,r),f=a.distanceToSquared(r),f<u&&(u=f,o&&o.copy(r),s&&s.copy(a)),this.closestPointToPoint(c,r),f=c.distanceToSquared(r),f<u&&(u=f,o&&o.copy(r),s&&s.copy(c)),Math.sqrt(u)}}(),st.prototype.intersectsTriangle=function(){const r=new st,e=new gt,t=new gt,n=new h.Vector3,i=new h.Vector3,o=new h.Vector3,s=new h.Vector3,a=new h.Line3,c=new h.Line3,d=new h.Vector3,f=new h.Vector2,u=new h.Vector2;function l(w,S,M,I){const C=n;!w.isDegenerateIntoPoint&&!w.isDegenerateIntoSegment?C.copy(w.plane.normal):C.copy(S.plane.normal);const D=w.satBounds,L=w.satAxes;for(let O=1;O<4;O++){const B=D[O],z=L[O];if(e.setFromPoints(z,S.points),B.isSeparated(e)||(s.copy(C).cross(z),e.setFromPoints(s,w.points),t.setFromPoints(s,S.points),e.isSeparated(t)))return!1}const R=S.satBounds,N=S.satAxes;for(let O=1;O<4;O++){const B=R[O],z=N[O];if(e.setFromPoints(z,w.points),B.isSeparated(e)||(s.crossVectors(C,z),e.setFromPoints(s,w.points),t.setFromPoints(s,S.points),e.isSeparated(t)))return!1}return M&&(I||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),M.start.set(0,0,0),M.end.set(0,0,0)),!0}function g(w,S,M,I,C,D,L,R,N,O,B){let z=L/(L-R);O.x=I+(C-I)*z,B.start.subVectors(S,w).multiplyScalar(z).add(w),z=L/(L-N),O.y=I+(D-I)*z,B.end.subVectors(M,w).multiplyScalar(z).add(w)}function y(w,S,M,I,C,D,L,R,N,O,B){if(C>0)g(w.c,w.a,w.b,I,S,M,N,L,R,O,B);else if(D>0)g(w.b,w.a,w.c,M,S,I,R,L,N,O,B);else if(R*N>0||L!=0)g(w.a,w.b,w.c,S,M,I,L,R,N,O,B);else if(R!=0)g(w.b,w.a,w.c,M,S,I,R,L,N,O,B);else if(N!=0)g(w.c,w.a,w.b,I,S,M,N,L,R,O,B);else return!0;return!1}function b(w,S,M,I){const C=S.degenerateSegment,D=w.plane.distanceToPoint(C.start),L=w.plane.distanceToPoint(C.end);return $e(D)?$e(L)?l(w,S,M,I):(M&&(M.start.copy(C.start),M.end.copy(C.start)),w.containsPoint(C.start)):$e(L)?(M&&(M.start.copy(C.end),M.end.copy(C.end)),w.containsPoint(C.end)):w.plane.intersectLine(C,n)!=null?(M&&(M.start.copy(n),M.end.copy(n)),w.containsPoint(n)):!1}function m(w,S,M){const I=S.a;return $e(w.plane.distanceToPoint(I))&&w.containsPoint(I)?(M&&(M.start.copy(I),M.end.copy(I)),!0):!1}function _(w,S,M){const I=w.degenerateSegment,C=S.a;return I.closestPointToPoint(C,!0,n),C.distanceToSquared(n)<Xr?(M&&(M.start.copy(C),M.end.copy(C)),!0):!1}function x(w,S,M,I){if(w.isDegenerateIntoSegment)if(S.isDegenerateIntoSegment){const C=w.degenerateSegment,D=S.degenerateSegment,L=i,R=o;C.delta(L),D.delta(R);const N=n.subVectors(D.start,C.start),O=L.x*R.y-L.y*R.x;if($e(O))return!1;const B=(N.x*R.y-N.y*R.x)/O,z=-(L.x*N.y-L.y*N.x)/O;if(B<0||B>1||z<0||z>1)return!1;const X=C.start.z+L.z*B,J=D.start.z+R.z*z;return $e(X-J)?(M&&(M.start.copy(C.start).addScaledVector(L,B),M.end.copy(C.start).addScaledVector(L,B)),!0):!1}else return S.isDegenerateIntoPoint?_(w,S,M):b(S,w,M,I);else{if(w.isDegenerateIntoPoint)return S.isDegenerateIntoPoint?S.a.distanceToSquared(w.a)<Xr?(M&&(M.start.copy(w.a),M.end.copy(w.a)),!0):!1:S.isDegenerateIntoSegment?_(S,w,M):m(S,w,M);if(S.isDegenerateIntoPoint)return m(w,S,M);if(S.isDegenerateIntoSegment)return b(w,S,M,I)}}return function(S,M=null,I=!1){this.needsUpdate&&this.update(),S.isExtendedTriangle?S.needsUpdate&&S.update():(r.copy(S),r.update(),S=r);const C=x(this,S,M,I);if(C!==void 0)return C;const D=this.plane,L=S.plane;let R=L.distanceToPoint(this.a),N=L.distanceToPoint(this.b),O=L.distanceToPoint(this.c);$e(R)&&(R=0),$e(N)&&(N=0),$e(O)&&(O=0);const B=R*N,z=R*O;if(B>0&&z>0)return!1;let X=D.distanceToPoint(S.a),J=D.distanceToPoint(S.b),Me=D.distanceToPoint(S.c);$e(X)&&(X=0),$e(J)&&(J=0),$e(Me)&&(Me=0);const Ve=X*J,Se=X*Me;if(Ve>0&&Se>0)return!1;i.copy(D.normal),o.copy(L.normal);const fe=i.cross(o);let We=0,me=Math.abs(fe.x);const be=Math.abs(fe.y);be>me&&(me=be,We=1),Math.abs(fe.z)>me&&(We=2);const je=Ja[We],le=this.a[je],He=this.b[je],lt=this.c[je],cn=S.a[je],Sn=S.b[je],Et=S.c[je];if(y(this,le,He,lt,B,z,R,N,O,f,a))return l(this,S,M,I);if(y(S,cn,Sn,Et,Ve,Se,X,J,Me,u,c))return l(this,S,M,I);if(f.y<f.x){const It=f.y;f.y=f.x,f.x=It,d.copy(a.start),a.start.copy(a.end),a.end.copy(d)}if(u.y<u.x){const It=u.y;u.y=u.x,u.x=It,d.copy(c.start),c.start.copy(c.end),c.end.copy(d)}return f.y<u.x||u.y<f.x?!1:(M&&(u.x>f.x?M.start.copy(c.start):M.start.copy(a.start),u.y<f.y?M.end.copy(c.end):M.end.copy(a.end)),!0)}}(),st.prototype.distanceToPoint=function(){const r=new h.Vector3;return function(t){return this.closestPointToPoint(t,r),t.distanceTo(r)}}(),st.prototype.distanceToTriangle=function(){const r=new h.Vector3,e=new h.Vector3,t=["a","b","c"],n=new h.Line3,i=new h.Line3;return function(s,a=null,c=null){const d=a||c?n:null;if(this.intersectsTriangle(s,d))return(a||c)&&(a&&d.getCenter(a),c&&d.getCenter(c)),0;let f=1/0;for(let u=0;u<3;u++){let l;const g=t[u],y=s[g];this.closestPointToPoint(y,r),l=y.distanceToSquared(r),l<f&&(f=l,a&&a.copy(r),c&&c.copy(y));const b=this[g];s.closestPointToPoint(b,r),l=b.distanceToSquared(r),l<f&&(f=l,a&&a.copy(b),c&&c.copy(r))}for(let u=0;u<3;u++){const l=t[u],g=t[(u+1)%3];n.set(this[l],this[g]);for(let y=0;y<3;y++){const b=t[y],m=t[(y+1)%3];i.set(s[b],s[m]),Gi(n,i,r,e);const _=r.distanceToSquared(e);_<f&&(f=_,a&&a.copy(r),c&&c.copy(e))}}return Math.sqrt(f)}}();class Ge{constructor(e,t,n){this.isOrientedBox=!0,this.min=new h.Vector3,this.max=new h.Vector3,this.matrix=new h.Matrix4,this.invMatrix=new h.Matrix4,this.points=new Array(8).fill().map(()=>new h.Vector3),this.satAxes=new Array(3).fill().map(()=>new h.Vector3),this.satBounds=new Array(3).fill().map(()=>new gt),this.alignedSatBounds=new Array(3).fill().map(()=>new gt),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}}Ge.prototype.update=function(){return function(){const e=this.matrix,t=this.min,n=this.max,i=this.points;for(let d=0;d<=1;d++)for(let f=0;f<=1;f++)for(let u=0;u<=1;u++){const l=1*d|2*f|4*u,g=i[l];g.x=d?n.x:t.x,g.y=f?n.y:t.y,g.z=u?n.z:t.z,g.applyMatrix4(e)}const o=this.satBounds,s=this.satAxes,a=i[0];for(let d=0;d<3;d++){const f=s[d],u=o[d],l=1<<d,g=i[l];f.subVectors(a,g),u.setFromPoints(f,i)}const c=this.alignedSatBounds;c[0].setFromPointsField(i,"x"),c[1].setFromPointsField(i,"y"),c[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),Ge.prototype.intersectsBox=function(){const r=new gt;return function(t){this.needsUpdate&&this.update();const n=t.min,i=t.max,o=this.satBounds,s=this.satAxes,a=this.alignedSatBounds;if(r.min=n.x,r.max=i.x,a[0].isSeparated(r)||(r.min=n.y,r.max=i.y,a[1].isSeparated(r))||(r.min=n.z,r.max=i.z,a[2].isSeparated(r)))return!1;for(let c=0;c<3;c++){const d=s[c],f=o[c];if(r.setFromBox(d,t),f.isSeparated(r))return!1}return!0}}(),Ge.prototype.intersectsTriangle=function(){const r=new st,e=new Array(3),t=new gt,n=new gt,i=new h.Vector3;return function(s){this.needsUpdate&&this.update(),s.isExtendedTriangle?s.needsUpdate&&s.update():(r.copy(s),r.update(),s=r);const a=this.satBounds,c=this.satAxes;e[0]=s.a,e[1]=s.b,e[2]=s.c;for(let l=0;l<3;l++){const g=a[l],y=c[l];if(t.setFromPoints(y,e),g.isSeparated(t))return!1}const d=s.satBounds,f=s.satAxes,u=this.points;for(let l=0;l<3;l++){const g=d[l],y=f[l];if(t.setFromPoints(y,u),g.isSeparated(t))return!1}for(let l=0;l<3;l++){const g=c[l];for(let y=0;y<4;y++){const b=f[y];if(i.crossVectors(g,b),t.setFromPoints(i,e),n.setFromPoints(i,u),t.isSeparated(n))return!1}}return!0}}(),Ge.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}}(),Ge.prototype.distanceToPoint=function(){const r=new h.Vector3;return function(t){return this.closestPointToPoint(t,r),t.distanceTo(r)}}(),Ge.prototype.distanceToBox=function(){const r=["x","y","z"],e=new Array(12).fill().map(()=>new h.Line3),t=new Array(12).fill().map(()=>new h.Line3),n=new h.Vector3,i=new h.Vector3;return function(s,a=0,c=null,d=null){if(this.needsUpdate&&this.update(),this.intersectsBox(s))return(c||d)&&(s.getCenter(i),this.closestPointToPoint(i,n),s.closestPointToPoint(n,i),c&&c.copy(n),d&&d.copy(i)),0;const f=a*a,u=s.min,l=s.max,g=this.points;let y=1/0;for(let m=0;m<8;m++){const _=g[m];i.copy(_).clamp(u,l);const x=_.distanceToSquared(i);if(x<y&&(y=x,c&&c.copy(_),d&&d.copy(i),x<f))return Math.sqrt(x)}let b=0;for(let m=0;m<3;m++)for(let _=0;_<=1;_++)for(let x=0;x<=1;x++){const w=(m+1)%3,S=(m+2)%3,M=_<<w|x<<S,I=1<<m|_<<w|x<<S,C=g[M],D=g[I];e[b].set(C,D);const R=r[m],N=r[w],O=r[S],B=t[b],z=B.start,X=B.end;z[R]=u[R],z[N]=_?u[N]:l[N],z[O]=x?u[O]:l[N],X[R]=l[R],X[N]=_?u[N]:l[N],X[O]=x?u[O]:l[N],b++}for(let m=0;m<=1;m++)for(let _=0;_<=1;_++)for(let x=0;x<=1;x++){i.x=m?l.x:u.x,i.y=_?l.y:u.y,i.z=x?l.z:u.z,this.closestPointToPoint(i,n);const w=i.distanceToSquared(n);if(w<y&&(y=w,c&&c.copy(n),d&&d.copy(i),w<f))return Math.sqrt(w)}for(let m=0;m<12;m++){const _=e[m];for(let x=0;x<12;x++){const w=t[x];Gi(_,w,n,i);const S=n.distanceToSquared(i);if(S<y&&(y=S,c&&c.copy(n),d&&d.copy(i),S<f))return Math.sqrt(S)}}return Math.sqrt(y)}}();class Ha extends ki{constructor(){super(()=>new st)}}const Qe=new Ha,dn=new h.Vector3,Vi=new h.Vector3;function ec(r,e,t={},n=0,i=1/0){const o=n*n,s=i*i;let a=1/0,c=null;if(r.shapecast({boundsTraverseOrder:f=>(dn.copy(e).clamp(f.min,f.max),dn.distanceToSquared(e)),intersectsBounds:(f,u,l)=>l<a&&l<s,intersectsTriangle:(f,u)=>{f.closestPointToPoint(e,dn);const l=e.distanceToSquared(dn);return l<a&&(Vi.copy(dn),a=l,c=u),l<o}}),a===1/0)return null;const d=Math.sqrt(a);return t.point?t.point.copy(Vi):t.point=Vi.clone(),t.distance=d,t.faceIndex=c,t}const Gn=parseInt(h.REVISION)>=169,tc=parseInt(h.REVISION)<=161,Ot=new h.Vector3,Lt=new h.Vector3,Nt=new h.Vector3,Vn=new h.Vector2,Wn=new h.Vector2,jn=new h.Vector2,$r=new h.Vector3,Qr=new h.Vector3,Jr=new h.Vector3,fn=new h.Vector3;function nc(r,e,t,n,i,o,s,a){let c;if(o===h.BackSide?c=r.intersectTriangle(n,t,e,!0,i):c=r.intersectTriangle(e,t,n,o!==h.DoubleSide,i),c===null)return null;const d=r.origin.distanceTo(i);return d<s||d>a?null:{distance:d,point:i.clone()}}function Hr(r,e,t,n,i,o,s,a,c,d,f){Ot.fromBufferAttribute(e,o),Lt.fromBufferAttribute(e,s),Nt.fromBufferAttribute(e,a);const u=nc(r,Ot,Lt,Nt,fn,c,d,f);if(u){if(n){Vn.fromBufferAttribute(n,o),Wn.fromBufferAttribute(n,s),jn.fromBufferAttribute(n,a),u.uv=new h.Vector2;const g=h.Triangle.getInterpolation(fn,Ot,Lt,Nt,Vn,Wn,jn,u.uv);Gn||(u.uv=g)}if(i){Vn.fromBufferAttribute(i,o),Wn.fromBufferAttribute(i,s),jn.fromBufferAttribute(i,a),u.uv1=new h.Vector2;const g=h.Triangle.getInterpolation(fn,Ot,Lt,Nt,Vn,Wn,jn,u.uv1);Gn||(u.uv1=g),tc&&(u.uv2=u.uv1)}if(t){$r.fromBufferAttribute(t,o),Qr.fromBufferAttribute(t,s),Jr.fromBufferAttribute(t,a),u.normal=new h.Vector3;const g=h.Triangle.getInterpolation(fn,Ot,Lt,Nt,$r,Qr,Jr,u.normal);u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1),Gn||(u.normal=g)}const l={a:o,b:s,c:a,normal:new h.Vector3,materialIndex:0};if(h.Triangle.getNormal(Ot,Lt,Nt,l.normal),u.face=l,u.faceIndex=o,Gn){const g=new h.Vector3;h.Triangle.getBarycoord(fn,Ot,Lt,Nt,g),u.barycoord=g}}return u}function es(r){return r&&r.isMaterial?r.side:r}function qn(r,e,t,n,i,o,s){const a=n*3;let c=a+0,d=a+1,f=a+2;const{index:u,groups:l}=r;r.index&&(c=u.getX(c),d=u.getX(d),f=u.getX(f));const{position:g,normal:y,uv:b,uv1:m}=r.attributes;if(Array.isArray(e)){const _=n*3;for(let x=0,w=l.length;x<w;x++){const{start:S,count:M,materialIndex:I}=l[x];if(_>=S&&_<S+M){const C=es(e[I]),D=Hr(t,g,y,b,m,c,d,f,C,o,s);if(D)if(D.faceIndex=n,D.face.materialIndex=I,i)i.push(D);else return D}}}else{const _=es(e),x=Hr(t,g,y,b,m,c,d,f,_,o,s);if(x)if(x.faceIndex=n,x.face.materialIndex=0,i)i.push(x);else return x}return null}function Ie(r,e,t,n){const i=r.a,o=r.b,s=r.c;let a=e,c=e+1,d=e+2;t&&(a=t.getX(a),c=t.getX(c),d=t.getX(d)),i.x=n.getX(a),i.y=n.getY(a),i.z=n.getZ(a),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c),s.x=n.getX(d),s.y=n.getY(d),s.z=n.getZ(d)}function ic(r,e,t,n,i,o,s,a){const{geometry:c,_indirectBuffer:d}=r;for(let f=n,u=n+i;f<u;f++)qn(c,e,t,f,o,s,a)}function rc(r,e,t,n,i,o,s){const{geometry:a,_indirectBuffer:c}=r;let d=1/0,f=null;for(let u=n,l=n+i;u<l;u++){let g;g=qn(a,e,t,u,null,o,s),g&&g.distance<d&&(f=g,d=g.distance)}return f}function sc(r,e,t,n,i,o,s){const{geometry:a}=t,{index:c}=a,d=a.attributes.position;for(let f=r,u=e+r;f<u;f++){let l;if(l=f,Ie(s,l*3,c,d),s.needsUpdate=!0,n(s,l,i,o))return!0}return!1}function oc(r,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=r.geometry,n=t.index?t.index.array:null,i=t.attributes.position;let o,s,a,c,d=0;const f=r._roots;for(let l=0,g=f.length;l<g;l++)o=f[l],s=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,d),d+=o.byteLength;function u(l,g,y=!1){const b=l*2;if(Ae(b,a)){const m=Be(l,s),_=ze(b,a);let x=1/0,w=1/0,S=1/0,M=-1/0,I=-1/0,C=-1/0;for(let D=3*m,L=3*(m+_);D<L;D++){let R=n[D];const N=i.getX(R),O=i.getY(R),B=i.getZ(R);N<x&&(x=N),N>M&&(M=N),O<w&&(w=O),O>I&&(I=O),B<S&&(S=B),B>C&&(C=B)}return c[l+0]!==x||c[l+1]!==w||c[l+2]!==S||c[l+3]!==M||c[l+4]!==I||c[l+5]!==C?(c[l+0]=x,c[l+1]=w,c[l+2]=S,c[l+3]=M,c[l+4]=I,c[l+5]=C,!0):!1}else{const m=Le(l),_=Ne(l,s);let x=y,w=!1,S=!1;if(e){if(!x){const R=m/De+g/Oe,N=_/De+g/Oe;w=e.has(R),S=e.has(N),x=!w&&!S}}else w=!0,S=!0;const M=x||w,I=x||S;let C=!1;M&&(C=u(m,g,x));let D=!1;I&&(D=u(_,g,x));const L=C||D;if(L)for(let R=0;R<3;R++){const N=m+R,O=_+R,B=c[N],z=c[N+3],X=c[O],J=c[O+3];c[l+R]=B<X?B:X,c[l+R+3]=z>J?z:J}return L}}}function Tt(r,e,t,n,i){let o,s,a,c,d,f;const u=1/t.direction.x,l=1/t.direction.y,g=1/t.direction.z,y=t.origin.x,b=t.origin.y,m=t.origin.z;let _=e[r],x=e[r+3],w=e[r+1],S=e[r+3+1],M=e[r+2],I=e[r+3+2];return u>=0?(o=(_-y)*u,s=(x-y)*u):(o=(x-y)*u,s=(_-y)*u),l>=0?(a=(w-b)*l,c=(S-b)*l):(a=(S-b)*l,c=(w-b)*l),o>c||a>s||((a>o||isNaN(o))&&(o=a),(c<s||isNaN(s))&&(s=c),g>=0?(d=(M-m)*g,f=(I-m)*g):(d=(I-m)*g,f=(M-m)*g),o>f||d>s)?!1:((d>o||o!==o)&&(o=d),(f<s||s!==s)&&(s=f),o<=i&&s>=n)}function ac(r,e,t,n,i,o,s,a){const{geometry:c,_indirectBuffer:d}=r;for(let f=n,u=n+i;f<u;f++){let l=d?d[f]:f;qn(c,e,t,l,o,s,a)}}function cc(r,e,t,n,i,o,s){const{geometry:a,_indirectBuffer:c}=r;let d=1/0,f=null;for(let u=n,l=n+i;u<l;u++){let g;g=qn(a,e,t,c?c[u]:u,null,o,s),g&&g.distance<d&&(f=g,d=g.distance)}return f}function lc(r,e,t,n,i,o,s){const{geometry:a}=t,{index:c}=a,d=a.attributes.position;for(let f=r,u=e+r;f<u;f++){let l;if(l=t.resolveTriangleIndex(f),Ie(s,l*3,c,d),s.needsUpdate=!0,n(s,l,i,o))return!0}return!1}function uc(r,e,t,n,i,o,s){ye.setBuffer(r._roots[e]),Wi(0,r,t,n,i,o,s),ye.clearBuffer()}function Wi(r,e,t,n,i,o,s){const{float32Array:a,uint16Array:c,uint32Array:d}=ye,f=r*2;if(Ae(f,c)){const l=Be(r,d),g=ze(f,c);ic(e,t,n,l,g,i,o,s)}else{const l=Le(r);Tt(l,a,n,o,s)&&Wi(l,e,t,n,i,o,s);const g=Ne(r,d);Tt(g,a,n,o,s)&&Wi(g,e,t,n,i,o,s)}}const hc=["x","y","z"];function dc(r,e,t,n,i,o){ye.setBuffer(r._roots[e]);const s=ji(0,r,t,n,i,o);return ye.clearBuffer(),s}function ji(r,e,t,n,i,o){const{float32Array:s,uint16Array:a,uint32Array:c}=ye;let d=r*2;if(Ae(d,a)){const u=Be(r,c),l=ze(d,a);return rc(e,t,n,u,l,i,o)}else{const u=Ln(r,c),l=hc[u],y=n.direction[l]>=0;let b,m;y?(b=Le(r),m=Ne(r,c)):(b=Ne(r,c),m=Le(r));const x=Tt(b,s,n,i,o)?ji(b,e,t,n,i,o):null;if(x){const M=x.point[l];if(y?M<=s[m+u]:M>=s[m+u+3])return x}const S=Tt(m,s,n,i,o)?ji(m,e,t,n,i,o):null;return x&&S?x.distance<=S.distance?x:S:x||S||null}}const Zn=new h.Box3,Xt=new st,$t=new st,pn=new h.Matrix4,ts=new Ge,Yn=new Ge;function fc(r,e,t,n){ye.setBuffer(r._roots[e]);const i=qi(0,r,t,n);return ye.clearBuffer(),i}function qi(r,e,t,n,i=null){const{float32Array:o,uint16Array:s,uint32Array:a}=ye;let c=r*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),ts.set(t.boundingBox.min,t.boundingBox.max,n),i=ts),Ae(c,s)){const f=e.geometry,u=f.index,l=f.attributes.position,g=t.index,y=t.attributes.position,b=Be(r,a),m=ze(c,s);if(pn.copy(n).invert(),t.boundsTree)return _e(r,o,Yn),Yn.matrix.copy(pn),Yn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Yn.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(n),x.b.applyMatrix4(n),x.c.applyMatrix4(n),x.needsUpdate=!0;for(let w=b*3,S=(m+b)*3;w<S;w+=3)if(Ie($t,w,u,l),$t.needsUpdate=!0,x.intersectsTriangle($t))return!0;return!1}});{const _=En(t);for(let x=b*3,w=(m+b)*3;x<w;x+=3){Ie(Xt,x,u,l),Xt.a.applyMatrix4(pn),Xt.b.applyMatrix4(pn),Xt.c.applyMatrix4(pn),Xt.needsUpdate=!0;for(let S=0,M=_*3;S<M;S+=3)if(Ie($t,S,g,y),$t.needsUpdate=!0,Xt.intersectsTriangle($t))return!0}}}else{const f=Le(r),u=Ne(r,a);return _e(f,o,Zn),!!(i.intersectsBox(Zn)&&qi(f,e,t,n,i)||(_e(u,o,Zn),i.intersectsBox(Zn)&&qi(u,e,t,n,i)))}}const Kn=new h.Matrix4,Zi=new Ge,mn=new Ge,pc=new h.Vector3,mc=new h.Vector3,gc=new h.Vector3,yc=new h.Vector3;function vc(r,e,t,n={},i={},o=0,s=1/0){e.boundingBox||e.computeBoundingBox(),Zi.set(e.boundingBox.min,e.boundingBox.max,t),Zi.needsUpdate=!0;const a=r.geometry,c=a.attributes.position,d=a.index,f=e.attributes.position,u=e.index,l=Qe.getPrimitive(),g=Qe.getPrimitive();let y=pc,b=mc,m=null,_=null;i&&(m=gc,_=yc);let x=1/0,w=null,S=null;return Kn.copy(t).invert(),mn.matrix.copy(Kn),r.shapecast({boundsTraverseOrder:M=>Zi.distanceToBox(M),intersectsBounds:(M,I,C)=>C<x&&C<s?(I&&(mn.min.copy(M.min),mn.max.copy(M.max),mn.needsUpdate=!0),!0):!1,intersectsRange:(M,I)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:D=>mn.distanceToBox(D),intersectsBounds:(D,L,R)=>R<x&&R<s,intersectsRange:(D,L)=>{for(let R=D,N=D+L;R<N;R++){Ie(g,3*R,u,f),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let O=M,B=M+I;O<B;O++){Ie(l,3*O,d,c),l.needsUpdate=!0;const z=l.distanceToTriangle(g,y,m);if(z<x&&(b.copy(y),_&&_.copy(m),x=z,w=O,S=R),z<o)return!0}}}});{const C=En(e);for(let D=0,L=C;D<L;D++){Ie(g,3*D,u,f),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let R=M,N=M+I;R<N;R++){Ie(l,3*R,d,c),l.needsUpdate=!0;const O=l.distanceToTriangle(g,y,m);if(O<x&&(b.copy(y),_&&_.copy(m),x=O,w=R,S=D),O<o)return!0}}}}}),Qe.releasePrimitive(l),Qe.releasePrimitive(g),x===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=x,n.faceIndex=w,i&&(i.point?i.point.copy(_):i.point=_.clone(),i.point.applyMatrix4(Kn),b.applyMatrix4(Kn),i.distance=b.sub(i.point).length(),i.faceIndex=S),n)}function xc(r,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=r.geometry,n=t.index?t.index.array:null,i=t.attributes.position;let o,s,a,c,d=0;const f=r._roots;for(let l=0,g=f.length;l<g;l++)o=f[l],s=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,d),d+=o.byteLength;function u(l,g,y=!1){const b=l*2;if(Ae(b,a)){const m=Be(l,s),_=ze(b,a);let x=1/0,w=1/0,S=1/0,M=-1/0,I=-1/0,C=-1/0;for(let D=m,L=m+_;D<L;D++){const R=3*r.resolveTriangleIndex(D);for(let N=0;N<3;N++){let O=R+N;O=n?n[O]:O;const B=i.getX(O),z=i.getY(O),X=i.getZ(O);B<x&&(x=B),B>M&&(M=B),z<w&&(w=z),z>I&&(I=z),X<S&&(S=X),X>C&&(C=X)}}return c[l+0]!==x||c[l+1]!==w||c[l+2]!==S||c[l+3]!==M||c[l+4]!==I||c[l+5]!==C?(c[l+0]=x,c[l+1]=w,c[l+2]=S,c[l+3]=M,c[l+4]=I,c[l+5]=C,!0):!1}else{const m=Le(l),_=Ne(l,s);let x=y,w=!1,S=!1;if(e){if(!x){const R=m/De+g/Oe,N=_/De+g/Oe;w=e.has(R),S=e.has(N),x=!w&&!S}}else w=!0,S=!0;const M=x||w,I=x||S;let C=!1;M&&(C=u(m,g,x));let D=!1;I&&(D=u(_,g,x));const L=C||D;if(L)for(let R=0;R<3;R++){const N=m+R,O=_+R,B=c[N],z=c[N+3],X=c[O],J=c[O+3];c[l+R]=B<X?B:X,c[l+R+3]=z>J?z:J}return L}}}function bc(r,e,t,n,i,o,s){ye.setBuffer(r._roots[e]),Yi(0,r,t,n,i,o,s),ye.clearBuffer()}function Yi(r,e,t,n,i,o,s){const{float32Array:a,uint16Array:c,uint32Array:d}=ye,f=r*2;if(Ae(f,c)){const l=Be(r,d),g=ze(f,c);ac(e,t,n,l,g,i,o,s)}else{const l=Le(r);Tt(l,a,n,o,s)&&Yi(l,e,t,n,i,o,s);const g=Ne(r,d);Tt(g,a,n,o,s)&&Yi(g,e,t,n,i,o,s)}}const wc=["x","y","z"];function _c(r,e,t,n,i,o){ye.setBuffer(r._roots[e]);const s=Ki(0,r,t,n,i,o);return ye.clearBuffer(),s}function Ki(r,e,t,n,i,o){const{float32Array:s,uint16Array:a,uint32Array:c}=ye;let d=r*2;if(Ae(d,a)){const u=Be(r,c),l=ze(d,a);return cc(e,t,n,u,l,i,o)}else{const u=Ln(r,c),l=wc[u],y=n.direction[l]>=0;let b,m;y?(b=Le(r),m=Ne(r,c)):(b=Ne(r,c),m=Le(r));const x=Tt(b,s,n,i,o)?Ki(b,e,t,n,i,o):null;if(x){const M=x.point[l];if(y?M<=s[m+u]:M>=s[m+u+3])return x}const S=Tt(m,s,n,i,o)?Ki(m,e,t,n,i,o):null;return x&&S?x.distance<=S.distance?x:S:x||S||null}}const Xn=new h.Box3,Qt=new st,Jt=new st,gn=new h.Matrix4,ns=new Ge,$n=new Ge;function Sc(r,e,t,n){ye.setBuffer(r._roots[e]);const i=Xi(0,r,t,n);return ye.clearBuffer(),i}function Xi(r,e,t,n,i=null){const{float32Array:o,uint16Array:s,uint32Array:a}=ye;let c=r*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),ns.set(t.boundingBox.min,t.boundingBox.max,n),i=ns),Ae(c,s)){const f=e.geometry,u=f.index,l=f.attributes.position,g=t.index,y=t.attributes.position,b=Be(r,a),m=ze(c,s);if(gn.copy(n).invert(),t.boundsTree)return _e(r,o,$n),$n.matrix.copy(gn),$n.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>$n.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(n),x.b.applyMatrix4(n),x.c.applyMatrix4(n),x.needsUpdate=!0;for(let w=b,S=m+b;w<S;w++)if(Ie(Jt,3*e.resolveTriangleIndex(w),u,l),Jt.needsUpdate=!0,x.intersectsTriangle(Jt))return!0;return!1}});{const _=En(t);for(let x=b,w=m+b;x<w;x++){const S=e.resolveTriangleIndex(x);Ie(Qt,3*S,u,l),Qt.a.applyMatrix4(gn),Qt.b.applyMatrix4(gn),Qt.c.applyMatrix4(gn),Qt.needsUpdate=!0;for(let M=0,I=_*3;M<I;M+=3)if(Ie(Jt,M,g,y),Jt.needsUpdate=!0,Qt.intersectsTriangle(Jt))return!0}}}else{const f=Le(r),u=Ne(r,a);return _e(f,o,Xn),!!(i.intersectsBox(Xn)&&Xi(f,e,t,n,i)||(_e(u,o,Xn),i.intersectsBox(Xn)&&Xi(u,e,t,n,i)))}}const Qn=new h.Matrix4,$i=new Ge,yn=new Ge,Tc=new h.Vector3,Mc=new h.Vector3,Ac=new h.Vector3,Ic=new h.Vector3;function Cc(r,e,t,n={},i={},o=0,s=1/0){e.boundingBox||e.computeBoundingBox(),$i.set(e.boundingBox.min,e.boundingBox.max,t),$i.needsUpdate=!0;const a=r.geometry,c=a.attributes.position,d=a.index,f=e.attributes.position,u=e.index,l=Qe.getPrimitive(),g=Qe.getPrimitive();let y=Tc,b=Mc,m=null,_=null;i&&(m=Ac,_=Ic);let x=1/0,w=null,S=null;return Qn.copy(t).invert(),yn.matrix.copy(Qn),r.shapecast({boundsTraverseOrder:M=>$i.distanceToBox(M),intersectsBounds:(M,I,C)=>C<x&&C<s?(I&&(yn.min.copy(M.min),yn.max.copy(M.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(M,I)=>{if(e.boundsTree){const C=e.boundsTree;return C.shapecast({boundsTraverseOrder:D=>yn.distanceToBox(D),intersectsBounds:(D,L,R)=>R<x&&R<s,intersectsRange:(D,L)=>{for(let R=D,N=D+L;R<N;R++){const O=C.resolveTriangleIndex(R);Ie(g,3*O,u,f),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let B=M,z=M+I;B<z;B++){const X=r.resolveTriangleIndex(B);Ie(l,3*X,d,c),l.needsUpdate=!0;const J=l.distanceToTriangle(g,y,m);if(J<x&&(b.copy(y),_&&_.copy(m),x=J,w=B,S=R),J<o)return!0}}}})}else{const C=En(e);for(let D=0,L=C;D<L;D++){Ie(g,3*D,u,f),g.a.applyMatrix4(t),g.b.applyMatrix4(t),g.c.applyMatrix4(t),g.needsUpdate=!0;for(let R=M,N=M+I;R<N;R++){const O=r.resolveTriangleIndex(R);Ie(l,3*O,d,c),l.needsUpdate=!0;const B=l.distanceToTriangle(g,y,m);if(B<x&&(b.copy(y),_&&_.copy(m),x=B,w=R,S=D),B<o)return!0}}}}}),Qe.releasePrimitive(l),Qe.releasePrimitive(g),x===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=x,n.faceIndex=w,i&&(i.point?i.point.copy(_):i.point=_.clone(),i.point.applyMatrix4(Qn),b.applyMatrix4(Qn),i.distance=b.sub(i.point).length(),i.faceIndex=S),n)}function is(r,e,t){return r===null?null:(r.point.applyMatrix4(e.matrixWorld),r.distance=r.point.distanceTo(t.ray.origin),r.object=e,r)}const Jn=new Ge,Hn=new h.Ray,rs=new h.Vector3,ss=new h.Matrix4,os=new h.Vector3,Qi=["getX","getY","getZ"];class ei extends Xa{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,i=e._roots,o=e._indirectBuffer,s=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=i.map(c=>c.slice()),a.index=s?s.array.slice():null,a.indirectBuffer=o?o.slice():null):(a.roots=i,a.index=s?s.array:null,a.indirectBuffer=o),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:i,roots:o,indirectBuffer:s}=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(o));const a=new ei(t,{...n,[Di]:!0});if(a._roots=o,a._indirectBuffer=s||null,n.setIndex){const d=t.getIndex();if(d===null){const f=new h.BufferAttribute(e.index,1,!1);t.setIndex(f)}else d.array!==i&&(d.array.set(i),d.needsUpdate=!0)}return a;function c(d){for(let f=0;f<d.length;f++){const u=d[f],l=new Uint32Array(u),g=new Uint16Array(u);for(let y=0,b=u.byteLength/Oe;y<b;y++){const m=De*y,_=2*m;Ae(_,g)||(l[m+6]=l[m+6]/De-y)}}}}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 i=this.geometry,o=this._indirectBuffer,s=i.attributes.position,a=i.index?i.index.array:null,d=(o?o[e]:e)*3;let f=d+0,u=d+1,l=d+2;a&&(f=a[f],u=a[u],l=a[l]);for(let g=0;g<3;g++){const y=s[Qi[g]](f),b=s[Qi[g]](u),m=s[Qi[g]](l);let _=y;b<_&&(_=b),m<_&&(_=m);let x=y;b>x&&(x=b),m>x&&(x=m),t[n+g]=_,t[n+g+3]=x}return t}computePrimitiveBounds(e,t,n){const i=this.geometry,o=this._indirectBuffer,s=i.attributes.position,a=i.index?i.index.array:null,c=s.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const d=s.array,f=s.offset||0;let u=3;s.isInterleavedBufferAttribute&&(u=s.data.stride);const l=["getX","getY","getZ"],g=n.offset;for(let y=e,b=e+t;y<b;y++){const _=(o?o[y]:y)*3,x=(y-g)*6;let w=_+0,S=_+1,M=_+2;a&&(w=a[w],S=a[S],M=a[M]),c||(w=w*u+f,S=S*u+f,M=M*u+f);for(let I=0;I<3;I++){let C,D,L;c?(C=s[l[I]](w),D=s[l[I]](S),L=s[l[I]](M)):(C=d[w+I],D=d[S+I],L=d[M+I]);let R=C;D<R&&(R=D),L<R&&(R=L);let N=C;D>N&&(N=D),L>N&&(N=L);const O=(N-R)/2,B=I*2;n[x+B+0]=R+O,n[x+B+1]=O+(Math.abs(R)+O)*Rn}}return n}raycastObject3D(e,t,n=[]){const{material:i}=e;if(i===void 0)return;ss.copy(e.matrixWorld).invert(),Hn.copy(t.ray).applyMatrix4(ss),os.setFromMatrixScale(e.matrixWorld),rs.copy(Hn.direction).multiply(os);const o=rs.length(),s=t.near/o,a=t.far/o;if(t.firstHitOnly===!0){let c=this.raycastFirst(Hn,i,s,a);c=is(c,e,t),c&&n.push(c)}else{const c=this.raycast(Hn,i,s,a);for(let d=0,f=c.length;d<f;d++){const u=is(c[d],e,t);u&&n.push(u)}}return n}refit(e=null){return(this.indirect?xc:oc)(this,e)}raycast(e,t=h.FrontSide,n=0,i=1/0){const o=this._roots,s=[],a=this.indirect?bc:uc;for(let c=0,d=o.length;c<d;c++)a(this,c,t,e,s,n,i);return s}raycastFirst(e,t=h.FrontSide,n=0,i=1/0){const o=this._roots;let s=null;const a=this.indirect?_c:dc;for(let c=0,d=o.length;c<d;c++){const f=a(this,c,t,e,n,i);f!=null&&(s==null||f.distance<s.distance)&&(s=f)}return s}intersectsGeometry(e,t){let n=!1;const i=this._roots,o=this.indirect?Sc:fc;for(let s=0,a=i.length;s<a&&(n=o(this,s,e,t),!n);s++);return n}shapecast(e){const t=Qe.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?lc:sc});return Qe.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:i,intersectsTriangles:o}=n;const s=Qe.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,d=this.indirect?y=>{const b=this.resolveTriangleIndex(y);Ie(s,b*3,a,c)}:y=>{Ie(s,y*3,a,c)},f=Qe.getPrimitive(),u=e.geometry.index,l=e.geometry.attributes.position,g=e.indirect?y=>{const b=e.resolveTriangleIndex(y);Ie(f,b*3,u,l)}:y=>{Ie(f,y*3,u,l)};if(o){if(!(e instanceof ei))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const y=(b,m,_,x,w,S,M,I)=>{for(let C=_,D=_+x;C<D;C++){g(C),f.a.applyMatrix4(t),f.b.applyMatrix4(t),f.c.applyMatrix4(t),f.needsUpdate=!0;for(let L=b,R=b+m;L<R;L++)if(d(L),s.needsUpdate=!0,o(s,f,L,C,w,S,M,I))return!0}return!1};if(i){const b=i;i=function(m,_,x,w,S,M,I,C){return b(m,_,x,w,S,M,I,C)?!0:y(m,_,x,w,S,M,I,C)}}else i=y}return super.bvhcast(e,t,{intersectsRanges:i})}intersectsBox(e,t){return Jn.set(e.min,e.max,t),Jn.needsUpdate=!0,this.shapecast({intersectsBounds:n=>Jn.intersectsBox(n),intersectsTriangle:n=>Jn.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},i={},o=0,s=1/0){return(this.indirect?Cc:vc)(this,e,t,n,i,o,s)}closestPointToPoint(e,t={},n=0,i=1/0){return ec(this,e,t,n,i)}}function Pc(r){switch(r){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function Dc(r){switch(r){case 1:return h.RedFormat;case 2:return h.RGFormat;case 3:return h.RGBAFormat;case 4:return h.RGBAFormat}}function as(r){switch(r){case 1:return h.RedIntegerFormat;case 2:return h.RGIntegerFormat;case 3:return h.RGBAIntegerFormat;case 4:return h.RGBAIntegerFormat}}class cs extends h.DataTexture{constructor(){super(),this.minFilter=h.NearestFilter,this.magFilter=h.NearestFilter,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(e){const t=this.overrideItemSize,n=e.itemSize,i=e.count;if(t!==null){if(n*i%t!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");e.itemSize=t,e.count=i*n/t}const o=e.itemSize,s=e.count,a=e.normalized,c=e.array.constructor,d=c.BYTES_PER_ELEMENT;let f=this._forcedType,u=o;if(f===null)switch(c){case Float32Array:f=h.FloatType;break;case Uint8Array:case Uint16Array:case Uint32Array:f=h.UnsignedIntType;break;case Int8Array:case Int16Array:case Int32Array:f=h.IntType;break}let l,g,y,b,m=Pc(o);switch(f){case h.FloatType:y=1,g=Dc(o),a&&d===1?(b=c,m+="8",c===Uint8Array?l=h.UnsignedByteType:(l=h.ByteType,m+="_SNORM")):(b=Float32Array,m+="32F",l=h.FloatType);break;case h.IntType:m+=d*8+"I",y=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,g=as(o),d===1?(b=Int8Array,l=h.ByteType):d===2?(b=Int16Array,l=h.ShortType):(b=Int32Array,l=h.IntType);break;case h.UnsignedIntType:m+=d*8+"UI",y=a?Math.pow(2,c.BYTES_PER_ELEMENT*8-1):1,g=as(o),d===1?(b=Uint8Array,l=h.UnsignedByteType):d===2?(b=Uint16Array,l=h.UnsignedShortType):(b=Uint32Array,l=h.UnsignedIntType);break}u===3&&(g===h.RGBAFormat||g===h.RGBAIntegerFormat)&&(u=4);const _=Math.ceil(Math.sqrt(s))||1,x=u*_*_,w=new b(x),S=e.normalized;e.normalized=!1;for(let M=0;M<s;M++){const I=u*M;w[I]=e.getX(M)/y,o>=2&&(w[I+1]=e.getY(M)/y),o>=3&&(w[I+2]=e.getZ(M)/y,u===4&&(w[I+3]=1)),o>=4&&(w[I+3]=e.getW(M)/y)}e.normalized=S,this.internalFormat=m,this.format=g,this.type=l,this.image.width=_,this.image.height=_,this.image.data=w,this.needsUpdate=!0,this.dispose(),e.itemSize=n,e.count=i}}class ls extends cs{constructor(){super(),this._forcedType=h.UnsignedIntType}}class us extends cs{constructor(){super(),this._forcedType=h.FloatType}}class Fc{constructor(){this.index=new ls,this.position=new us,this.bvhBounds=new h.DataTexture,this.bvhContents=new h.DataTexture,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(Oc(e,this.bvhBounds,this.bvhContents),this.position.updateFrom(t.attributes.position),e.indirect){const n=e._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==n.length)if(t.index)this._cachedIndexAttr=t.index.clone();else{const i=Yr(Un(t));this._cachedIndexAttr=new h.BufferAttribute(i,1,!1)}Rc(t,n,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(t.index)}dispose(){const{index:e,position:t,bvhBounds:n,bvhContents:i}=this;e&&e.dispose(),t&&t.dispose(),n&&n.dispose(),i&&i.dispose()}}function Rc(r,e,t){const n=t.array,i=r.index?r.index.array:null;for(let o=0,s=e.length;o<s;o++){const a=3*o,c=3*e[o];for(let d=0;d<3;d++)n[a+d]=i?i[c+d]:c+d}}function Oc(r,e,t){const n=r._roots;if(n.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const i=n[0],o=new Uint16Array(i),s=new Uint32Array(i),a=new Float32Array(i),c=i.byteLength/Oe,d=2*Math.ceil(Math.sqrt(c/2)),f=new Float32Array(4*d*d),u=Math.ceil(Math.sqrt(c)),l=new Uint32Array(2*u*u);for(let g=0;g<c;g++){const y=g*Oe/4,b=y*2,m=y;for(let _=0;_<3;_++)f[8*g+0+_]=a[m+0+_],f[8*g+4+_]=a[m+3+_];if(Ae(b,o)){const _=ze(b,o),x=Be(y,s),w=Fa|_;l[g*2+0]=w,l[g*2+1]=x}else{const _=s[y+6],x=Ln(y,s);l[g*2+0]=x,l[g*2+1]=_}}e.image.data=f,e.image.width=d,e.image.height=d,e.format=h.RGBAFormat,e.type=h.FloatType,e.internalFormat="RGBA32F",e.minFilter=h.NearestFilter,e.magFilter=h.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose(),t.image.data=l,t.image.width=u,t.image.height=u,t.format=h.RGIntegerFormat,t.type=h.UnsignedIntType,t.internalFormat="RG32UI",t.minFilter=h.NearestFilter,t.magFilter=h.NearestFilter,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose()}const Lc=`
|
|
2
2
|
|
|
3
3
|
// A stack of uint32 indices can can store the indices for
|
|
4
4
|
// a perfectly balanced tree with a depth up to 31. Lower stack
|
|
@@ -80,7 +80,7 @@ void ndcToCameraRay(
|
|
|
80
80
|
rayDirection = direction.xyz;
|
|
81
81
|
|
|
82
82
|
}
|
|
83
|
-
`,
|
|
83
|
+
`,Nc=`
|
|
84
84
|
|
|
85
85
|
#ifndef TRI_INTERSECT_EPSILON
|
|
86
86
|
#define TRI_INTERSECT_EPSILON 1e-5
|
|
@@ -222,16 +222,16 @@ bool _bvhIntersectFirstHit(
|
|
|
222
222
|
|
|
223
223
|
// stack needs to be twice as long as the deepest tree we expect because
|
|
224
224
|
// we push both the left and right child onto the stack every traversal
|
|
225
|
-
int
|
|
225
|
+
int pointer = 0;
|
|
226
226
|
uint stack[ BVH_STACK_DEPTH ];
|
|
227
227
|
stack[ 0 ] = 0u;
|
|
228
228
|
|
|
229
229
|
float triangleDistance = INFINITY;
|
|
230
230
|
bool found = false;
|
|
231
|
-
while (
|
|
231
|
+
while ( pointer > - 1 && pointer < BVH_STACK_DEPTH ) {
|
|
232
232
|
|
|
233
|
-
uint currNodeIndex = stack[
|
|
234
|
-
|
|
233
|
+
uint currNodeIndex = stack[ pointer ];
|
|
234
|
+
pointer --;
|
|
235
235
|
|
|
236
236
|
// check if we intersect the current bounds
|
|
237
237
|
float boundsHitDistance;
|
|
@@ -262,7 +262,7 @@ bool _bvhIntersectFirstHit(
|
|
|
262
262
|
|
|
263
263
|
uint leftIndex = currNodeIndex + 1u;
|
|
264
264
|
uint splitAxis = boundsInfo.x & 0x0000ffffu;
|
|
265
|
-
uint rightIndex = boundsInfo.y;
|
|
265
|
+
uint rightIndex = currNodeIndex + boundsInfo.y;
|
|
266
266
|
|
|
267
267
|
bool leftToRight = rayDirection[ splitAxis ] >= 0.0;
|
|
268
268
|
uint c1 = leftToRight ? leftIndex : rightIndex;
|
|
@@ -271,11 +271,11 @@ bool _bvhIntersectFirstHit(
|
|
|
271
271
|
// set c2 in the stack so we traverse it later. We need to keep track of a pointer in
|
|
272
272
|
// the stack while we traverse. The second pointer added is the one that will be
|
|
273
273
|
// traversed first
|
|
274
|
-
|
|
275
|
-
stack[
|
|
274
|
+
pointer ++;
|
|
275
|
+
stack[ pointer ] = c2;
|
|
276
276
|
|
|
277
|
-
|
|
278
|
-
stack[
|
|
277
|
+
pointer ++;
|
|
278
|
+
stack[ pointer ] = c1;
|
|
279
279
|
|
|
280
280
|
}
|
|
281
281
|
|
|
@@ -284,7 +284,7 @@ bool _bvhIntersectFirstHit(
|
|
|
284
284
|
return found;
|
|
285
285
|
|
|
286
286
|
}
|
|
287
|
-
`,
|
|
287
|
+
`,kc=`
|
|
288
288
|
struct BVH {
|
|
289
289
|
|
|
290
290
|
usampler2D index;
|
|
@@ -294,7 +294,7 @@ struct BVH {
|
|
|
294
294
|
usampler2D bvhContents;
|
|
295
295
|
|
|
296
296
|
};
|
|
297
|
-
`;function ji(s,e,t=0){if(s.isInterleavedBufferAttribute){const n=s.itemSize;for(let r=0,o=s.count;r<o;r++){const i=r+t;e.setX(i,s.getX(r)),n>=2&&e.setY(i,s.getY(r)),n>=3&&e.setZ(i,s.getZ(r)),n>=4&&e.setW(i,s.getW(r))}}else{const n=e.array,r=n.constructor,o=n.BYTES_PER_ELEMENT*s.itemSize*t;new r(n.buffer,o,s.array.length).set(s.array)}}function un(s,e=null){const t=s.array.constructor,n=s.normalized,r=s.itemSize,o=e===null?s.count:e;return new h.BufferAttribute(new t(r*o),r,n)}function qt(s,e){if(!s&&!e)return!0;if(!!s!=!!e)return!1;const t=s.count===e.count,n=s.normalized===e.normalized,r=s.array.constructor===e.array.constructor,o=s.itemSize===e.itemSize;return!(!t||!n||!r||!o)}function fc(s){const e=s[0].index!==null,t=new Set(Object.keys(s[0].attributes));if(!s[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let n=0;n<s.length;++n){const r=s[n];let o=0;if(e!==(r.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const i in r.attributes){if(!t.has(i))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+i+'" attribute exists among all geometries, or in none of them.');o++}if(o!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function dc(s){let e=0;for(let t=0,n=s.length;t<n;t++)e+=s[t].getIndex().count;return e}function pc(s){let e=0;for(let t=0,n=s.length;t<n;t++)e+=s[t].getAttribute("position").count;return e}function mc(s,e,t){s.index&&s.index.count!==e&&s.setIndex(null);const n=s.attributes;for(const r in n)n[r].count!==t&&s.deleteAttribute(r)}function gc(s,e={},t=new h.BufferGeometry){const{useGroups:n=!1,forceUpdate:r=!1,skipAssigningAttributes:o=[],overwriteIndex:i=!0}=e;fc(s);const a=s[0].index!==null,c=a?dc(s):-1,f=pc(s);if(mc(t,c,f),n){let u=0;for(let l=0,g=s.length;l<g;l++){const y=s[l];let w;a?w=y.getIndex().count:w=y.getAttribute("position").count,t.addGroup(u,w,l),u+=w}}if(a){let u=!1;if(t.index||(t.setIndex(new h.BufferAttribute(new Uint32Array(c),1,!1)),u=!0),u||i){let l=0,g=0;const y=t.getIndex();for(let w=0,m=s.length;w<m;w++){const x=s[w],b=x.getIndex();if(!(!r&&!u&&o[w]))for(let M=0;M<b.count;++M)y.setX(l+M,b.getX(M)+g);l+=b.count,g+=x.getAttribute("position").count}}}const d=Object.keys(s[0].attributes);for(let u=0,l=d.length;u<l;u++){let g=!1;const y=d[u];if(!t.getAttribute(y)){const x=s[0].getAttribute(y);t.setAttribute(y,un(x,f)),g=!0}let w=0;const m=t.getAttribute(y);for(let x=0,b=s.length;x<b;x++){const T=s[x],M=!r&&!g&&o[x],A=T.getAttribute(y);M||ji(A,m,w),w+=A.count}}}function vc(s,e,t){const n=s.index,o=s.attributes.position.count,i=n?n.count:o;let a=s.groups;a.length===0&&(a=[{count:i,start:0,materialIndex:0}]);let c=s.getAttribute("materialIndex");if(!c||c.count!==o){let d;t.length<=255?d=new Uint8Array(o):d=new Uint16Array(o),c=new h.BufferAttribute(d,1,!1),s.deleteAttribute("materialIndex"),s.setAttribute("materialIndex",c)}const f=c.array;for(let d=0;d<a.length;d++){const u=a[d],l=u.start,g=u.count,y=Math.min(g,i-l),w=Array.isArray(e)?e[u.materialIndex]:e,m=t.indexOf(w);for(let x=0;x<y;x++){let b=l+x;n&&(b=n.getX(b)),f[b]=m}}}function yc(s,e){if(!s.index){const t=s.attributes.position.count,n=new Array(t);for(let r=0;r<t;r++)n[r]=r;s.setIndex(n)}if(!s.attributes.normal&&e&&e.includes("normal")&&s.computeVertexNormals(),!s.attributes.uv&&e&&e.includes("uv")){const t=s.attributes.position.count;s.setAttribute("uv",new h.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.uv2&&e&&e.includes("uv2")){const t=s.attributes.position.count;s.setAttribute("uv2",new h.BufferAttribute(new Float32Array(t*2),2,!1))}if(!s.attributes.tangent&&e&&e.includes("tangent"))if(s.attributes.uv&&s.attributes.normal)s.computeTangents();else{const t=s.attributes.position.count;s.setAttribute("tangent",new h.BufferAttribute(new Float32Array(t*4),4,!1))}if(!s.attributes.color&&e&&e.includes("color")){const t=s.attributes.position.count,n=new Float32Array(t*4);n.fill(1),s.setAttribute("color",new h.BufferAttribute(n,4))}}function Br(s){let e=0;if(s.byteLength!==0){const t=new Uint8Array(s);for(let n=0;n<s.byteLength;n++){const r=t[n];e=(e<<5)-e+r,e|=0}}return e}function qi(s){let e=s.uuid;const t=Object.values(s.attributes);s.index&&(t.push(s.index),e+=`index|${s.index.version}`);const n=Object.keys(t).sort();for(const r of n){const o=t[r];e+=`${r}_${o.version}|`}return e}function Zi(s){const e=s.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Br(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class xc{constructor(e=null){this.matrixWorld=new h.Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=qi(t),this.primitiveCount=n,this.skeletonHash=Zi(e)}didChange(e){const t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===qi(t)&&this.skeletonHash===Zi(e)&&this.primitiveCount===n)}}const It=new h.Vector3,Ct=new h.Vector3,Pt=new h.Vector3,Yi=new h.Vector4,Gn=new h.Vector3,Ur=new h.Vector3,Ki=new h.Vector4,Xi=new h.Vector4,Vn=new h.Matrix4,$i=new h.Matrix4;function Qi(s,e,t){const n=s.skeleton,r=s.geometry,o=n.bones,i=n.boneInverses;Ki.fromBufferAttribute(r.attributes.skinIndex,e),Xi.fromBufferAttribute(r.attributes.skinWeight,e),Vn.elements.fill(0);for(let a=0;a<4;a++){const c=Xi.getComponent(a);if(c!==0){const f=Ki.getComponent(a);$i.multiplyMatrices(o[f].matrixWorld,i[f]),bc(Vn,$i,c)}}return Vn.multiply(s.bindMatrix).premultiply(s.bindMatrixInverse),t.transformDirection(Vn),t}function Er(s,e,t,n,r){Gn.set(0,0,0);for(let o=0,i=s.length;o<i;o++){const a=e[o],c=s[o];a!==0&&(Ur.fromBufferAttribute(c,n),t?Gn.addScaledVector(Ur,a):Gn.addScaledVector(Ur.sub(r),a))}r.add(Gn)}function bc(s,e,t){const n=s.elements,r=e.elements;for(let o=0,i=r.length;o<i;o++)n[o]+=r[o]*t}function wc(s){const{index:e,attributes:t}=s;if(e)for(let n=0,r=e.count;n<r;n+=3){const o=e.getX(n),i=e.getX(n+2);e.setX(n,i),e.setX(n+2,o)}else for(const n in t){const r=t[n],o=r.itemSize;for(let i=0,a=r.count;i<a;i+=3)for(let c=0;c<o;c++){const f=r.getComponent(i,c),d=r.getComponent(i+2,c);r.setComponent(i,c,d),r.setComponent(i+2,c,f)}}return s}function _c(s,e={},t=new h.BufferGeometry){e={applyWorldTransforms:!0,attributes:[],...e};const n=s.geometry,r=e.applyWorldTransforms,o=e.attributes.includes("normal"),i=e.attributes.includes("tangent"),a=n.attributes,c=t.attributes;for(const b in t.attributes)(!e.attributes.includes(b)||!(b in n.attributes))&&t.deleteAttribute(b);!t.index&&n.index&&(t.index=n.index.clone()),c.position||t.setAttribute("position",un(a.position)),o&&!c.normal&&a.normal&&t.setAttribute("normal",un(a.normal)),i&&!c.tangent&&a.tangent&&t.setAttribute("tangent",un(a.tangent)),qt(n.index,t.index),qt(a.position,c.position),o&&qt(a.normal,c.normal),i&&qt(a.tangent,c.tangent);const f=a.position,d=o?a.normal:null,u=i?a.tangent:null,l=n.morphAttributes.position,g=n.morphAttributes.normal,y=n.morphAttributes.tangent,w=n.morphTargetsRelative,m=s.morphTargetInfluences,x=new h.Matrix3;x.getNormalMatrix(s.matrixWorld),n.index&&t.index.array.set(n.index.array);for(let b=0,T=a.position.count;b<T;b++)It.fromBufferAttribute(f,b),d&&Ct.fromBufferAttribute(d,b),u&&(Yi.fromBufferAttribute(u,b),Pt.fromBufferAttribute(u,b)),m&&(l&&Er(l,m,w,b,It),g&&Er(g,m,w,b,Ct),y&&Er(y,m,w,b,Pt)),s.isSkinnedMesh&&(s.applyBoneTransform(b,It),d&&Qi(s,b,Ct),u&&Qi(s,b,Pt)),r&&It.applyMatrix4(s.matrixWorld),c.position.setXYZ(b,It.x,It.y,It.z),d&&(r&&Ct.applyNormalMatrix(x),c.normal.setXYZ(b,Ct.x,Ct.y,Ct.z)),u&&(r&&Pt.transformDirection(s.matrixWorld),c.tangent.setXYZW(b,Pt.x,Pt.y,Pt.z,Yi.w));for(const b in e.attributes){const T=e.attributes[b];T==="position"||T==="tangent"||T==="normal"||!(T in a)||(c[T]||t.setAttribute(T,un(a[T])),qt(a[T],c[T]),ji(a[T],c[T]))}return s.matrixWorld.determinant()<0&&wc(t),t}class Tc extends h.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new xc}isCompatible(e,t){const n=e.geometry;for(let r=0;r<t.length;r++){const o=t[r],i=n.attributes[o],a=this.attributes[o];if(i&&!qt(i,a))return!1}return!0}updateFrom(e,t){const n=this._diff;return n.didChange(e)?(_c(e,t,this),n.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const Gr=0,Ji=1,Hi=2;function Sc(s,e){for(let t=0,n=s.length;t<n;t++)s[t].traverseVisible(o=>{o.isMesh&&e(o)})}function Mc(s){const e=[];for(let t=0,n=s.length;t<n;t++){const r=s[t];Array.isArray(r.material)?e.push(...r.material):e.push(r.material)}return e}function Ac(s,e,t){if(s.length===0){e.setIndex(null);const n=e.attributes;for(const r in n)e.deleteAttribute(r);for(const r in t.attributes)e.setAttribute(t.attributes[r],new h.BufferAttribute(new Float32Array(0),4,!1))}else gc(s,t,e);for(const n in e.attributes)e.attributes[n].needsUpdate=!0}class Ic{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new h.MeshBasicMaterial,t=new h.BufferGeometry;t.setAttribute("position",new h.BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new h.Mesh(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return Sc(this.objects,t=>{e.push(t)}),e.sort((t,n)=>t.uuid>n.uuid?1:t.uuid<n.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),n=new Set(e.keys()),r={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let o=0,i=t.length;o<i;o++){const a=t[o],c=a.uuid;n.delete(c);let f=e.get(c);(!f||!f.isCompatible(a,this.attributes))&&(f&&f.dispose(),f=new Tc,e.set(c,f)),f.updateFrom(a,r)&&this.generateMissingAttributes&&yc(f,this.attributes)}n.forEach(o=>{e.delete(o)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new h.BufferGeometry){const{useGroups:t,overwriteIndex:n,_intermediateGeometry:r,_geometryMergeSets:o}=this,i=this._getMeshes(),a=[],c=[],f=o.get(e)||[];this._updateIntermediateGeometries();let d=!1;i.length!==f.length&&(d=!0);for(let l=0,g=i.length;l<g;l++){const y=i[l],w=r.get(y.uuid);c.push(w);const m=f[l];!m||m.uuid!==w.uuid?(a.push(!1),d=!0):m.version!==w.version?a.push(!1):a.push(!0)}Ac(c,e,{useGroups:t,forceUpdate:d,skipAssigningAttributes:a,overwriteIndex:n}),d&&e.dispose(),o.set(e,c.map(l=>({version:l.version,uuid:l.uuid})));let u=Gr;return d?u=Hi:a.includes(!1)&&(u=Ji),{changeType:u,materials:Mc(i),geometry:e}}}function Cc(s){const e=new Set;for(let t=0,n=s.length;t<n;t++){const r=s[t];for(const o in r){const i=r[o];i&&i.isTexture&&e.add(i)}}return Array.from(e)}function Pc(s){const e=[],t=new Set;for(let r=0,o=s.length;r<o;r++)s[r].traverse(i=>{i.visible&&(i.isRectAreaLight||i.isSpotLight||i.isPointLight||i.isDirectionalLight)&&(e.push(i),i.iesMap&&t.add(i.iesMap))});const n=Array.from(t).sort((r,o)=>r.uuid<o.uuid?1:r.uuid>o.uuid?-1:0);return{lights:e,iesTextures:n}}class Dc{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new h.BufferGeometry,this.staticGeometryGenerator=new Ic(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:n,attributes:r}=this,o=t.objects;t.attributes=r,o.forEach(u=>{u.traverse(l=>{l.isSkinnedMesh&&l.skeleton&&l.skeleton.update()})});const i=t.generate(n),a=i.materials,c=Cc(a),{lights:f,iesTextures:d}=Pc(o);if(i.changeType!==Gr&&vc(n,a,a),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(i.changeType===Hi){const u={strategy:_i,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(n,u):this.bvh=new zr(n,u)}else i.changeType===Ji&&this.bvh.refit()}return{bvhChanged:i.changeType!==Gr,bvh:this.bvh,lights:f,iesTextures:d,geometry:n,materials:a,textures:c,objects:o}}}const Fc=new h.OrthographicCamera(-1,1,1,-1,0,1);class Rc extends h.BufferGeometry{constructor(){super(),this.setAttribute("position",new h.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new h.Float32BufferAttribute([0,2,0,0,2,0],2))}}const Oc=new Rc;class Zt{constructor(e){this._mesh=new h.Mesh(Oc,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Fc)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class Vr extends h.ShaderMaterial{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(n){this.uniforms[t].value=n}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class Lc extends Vr{constructor(e){super({blending:h.NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
|
|
297
|
+
`;function hs(r,e,t=0){if(r.isInterleavedBufferAttribute){const n=r.itemSize;for(let i=0,o=r.count;i<o;i++){const s=i+t;e.setX(s,r.getX(i)),n>=2&&e.setY(s,r.getY(i)),n>=3&&e.setZ(s,r.getZ(i)),n>=4&&e.setW(s,r.getW(i))}}else{const n=e.array,i=n.constructor,o=n.BYTES_PER_ELEMENT*r.itemSize*t;new i(n.buffer,o,r.array.length).set(r.array)}}function vn(r,e=null){const t=r.array.constructor,n=r.normalized,i=r.itemSize,o=e===null?r.count:e;return new h.BufferAttribute(new t(i*o),i,n)}function Ht(r,e){if(!r&&!e)return!0;if(!!r!=!!e)return!1;const t=r.count===e.count,n=r.normalized===e.normalized,i=r.array.constructor===e.array.constructor,o=r.itemSize===e.itemSize;return!(!t||!n||!i||!o)}function Bc(r){const e=r[0].index!==null,t=new Set(Object.keys(r[0].attributes));if(!r[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let n=0;n<r.length;++n){const i=r[n];let o=0;if(e!==(i.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const s in i.attributes){if(!t.has(s))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+s+'" attribute exists among all geometries, or in none of them.');o++}if(o!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function zc(r){let e=0;for(let t=0,n=r.length;t<n;t++)e+=r[t].getIndex().count;return e}function Uc(r){let e=0;for(let t=0,n=r.length;t<n;t++)e+=r[t].getAttribute("position").count;return e}function Ec(r,e,t){r.index&&r.index.count!==e&&r.setIndex(null);const n=r.attributes;for(const i in n)n[i].count!==t&&r.deleteAttribute(i)}function Gc(r,e={},t=new h.BufferGeometry){const{useGroups:n=!1,forceUpdate:i=!1,skipAssigningAttributes:o=[],overwriteIndex:s=!0}=e;Bc(r);const a=r[0].index!==null,c=a?zc(r):-1,d=Uc(r);if(Ec(t,c,d),n){let u=0;for(let l=0,g=r.length;l<g;l++){const y=r[l];let b;a?b=y.getIndex().count:b=y.getAttribute("position").count,t.addGroup(u,b,l),u+=b}}if(a){let u=!1;if(t.index||(t.setIndex(new h.BufferAttribute(new Uint32Array(c),1,!1)),u=!0),u||s){let l=0,g=0;const y=t.getIndex();for(let b=0,m=r.length;b<m;b++){const _=r[b],x=_.getIndex();if(!(!i&&!u&&o[b]))for(let S=0;S<x.count;++S)y.setX(l+S,x.getX(S)+g);l+=x.count,g+=_.getAttribute("position").count}}}const f=Object.keys(r[0].attributes);for(let u=0,l=f.length;u<l;u++){let g=!1;const y=f[u];if(!t.getAttribute(y)){const _=r[0].getAttribute(y);t.setAttribute(y,vn(_,d)),g=!0}let b=0;const m=t.getAttribute(y);for(let _=0,x=r.length;_<x;_++){const w=r[_],S=!i&&!g&&o[_],M=w.getAttribute(y);S||hs(M,m,b),b+=M.count}}}function Vc(r,e,t){const n=r.index,o=r.attributes.position.count,s=n?n.count:o;let a=r.groups;a.length===0&&(a=[{count:s,start:0,materialIndex:0}]);let c=r.getAttribute("materialIndex");if(!c||c.count!==o){let f;t.length<=255?f=new Uint8Array(o):f=new Uint16Array(o),c=new h.BufferAttribute(f,1,!1),r.deleteAttribute("materialIndex"),r.setAttribute("materialIndex",c)}const d=c.array;for(let f=0;f<a.length;f++){const u=a[f],l=u.start,g=u.count,y=Math.min(g,s-l),b=Array.isArray(e)?e[u.materialIndex]:e,m=t.indexOf(b);for(let _=0;_<y;_++){let x=l+_;n&&(x=n.getX(x)),d[x]=m}}}function Wc(r,e){if(!r.index){const t=r.attributes.position.count,n=new Array(t);for(let i=0;i<t;i++)n[i]=i;r.setIndex(n)}if(!r.attributes.normal&&e&&e.includes("normal")&&r.computeVertexNormals(),!r.attributes.uv&&e&&e.includes("uv")){const t=r.attributes.position.count;r.setAttribute("uv",new h.BufferAttribute(new Float32Array(t*2),2,!1))}if(!r.attributes.uv2&&e&&e.includes("uv2")){const t=r.attributes.position.count;r.setAttribute("uv2",new h.BufferAttribute(new Float32Array(t*2),2,!1))}if(!r.attributes.tangent&&e&&e.includes("tangent"))if(r.attributes.uv&&r.attributes.normal)r.computeTangents();else{const t=r.attributes.position.count;r.setAttribute("tangent",new h.BufferAttribute(new Float32Array(t*4),4,!1))}if(!r.attributes.color&&e&&e.includes("color")){const t=r.attributes.position.count,n=new Float32Array(t*4);n.fill(1),r.setAttribute("color",new h.BufferAttribute(n,4))}}function Ji(r){let e=0;if(r.byteLength!==0){const t=new Uint8Array(r);for(let n=0;n<r.byteLength;n++){const i=t[n];e=(e<<5)-e+i,e|=0}}return e}function ds(r){let e=r.uuid;const t=Object.values(r.attributes);r.index&&(t.push(r.index),e+=`index|${r.index.version}`);const n=Object.keys(t).sort();for(const i of n){const o=t[i];e+=`${i}_${o.version}|`}return e}function fs(r){const e=r.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Ji(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class jc{constructor(e=null){this.matrixWorld=new h.Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=ds(t),this.primitiveCount=n,this.skeletonHash=fs(e)}didChange(e){const t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===ds(t)&&this.skeletonHash===fs(e)&&this.primitiveCount===n)}}const kt=new h.Vector3,Bt=new h.Vector3,zt=new h.Vector3,ps=new h.Vector4,ti=new h.Vector3,Hi=new h.Vector3,ms=new h.Vector4,gs=new h.Vector4,ni=new h.Matrix4,ys=new h.Matrix4;function vs(r,e,t){const n=r.skeleton,i=r.geometry,o=n.bones,s=n.boneInverses;ms.fromBufferAttribute(i.attributes.skinIndex,e),gs.fromBufferAttribute(i.attributes.skinWeight,e),ni.elements.fill(0);for(let a=0;a<4;a++){const c=gs.getComponent(a);if(c!==0){const d=ms.getComponent(a);ys.multiplyMatrices(o[d].matrixWorld,s[d]),qc(ni,ys,c)}}return ni.multiply(r.bindMatrix).premultiply(r.bindMatrixInverse),t.transformDirection(ni),t}function er(r,e,t,n,i){ti.set(0,0,0);for(let o=0,s=r.length;o<s;o++){const a=e[o],c=r[o];a!==0&&(Hi.fromBufferAttribute(c,n),t?ti.addScaledVector(Hi,a):ti.addScaledVector(Hi.sub(i),a))}i.add(ti)}function qc(r,e,t){const n=r.elements,i=e.elements;for(let o=0,s=i.length;o<s;o++)n[o]+=i[o]*t}function Zc(r){const{index:e,attributes:t}=r;if(e)for(let n=0,i=e.count;n<i;n+=3){const o=e.getX(n),s=e.getX(n+2);e.setX(n,s),e.setX(n+2,o)}else for(const n in t){const i=t[n],o=i.itemSize;for(let s=0,a=i.count;s<a;s+=3)for(let c=0;c<o;c++){const d=i.getComponent(s,c),f=i.getComponent(s+2,c);i.setComponent(s,c,f),i.setComponent(s+2,c,d)}}return r}function Yc(r,e={},t=new h.BufferGeometry){e={applyWorldTransforms:!0,attributes:[],...e};const n=r.geometry,i=e.applyWorldTransforms,o=e.attributes.includes("normal"),s=e.attributes.includes("tangent"),a=n.attributes,c=t.attributes;for(const x in t.attributes)(!e.attributes.includes(x)||!(x in n.attributes))&&t.deleteAttribute(x);!t.index&&n.index&&(t.index=n.index.clone()),c.position||t.setAttribute("position",vn(a.position)),o&&!c.normal&&a.normal&&t.setAttribute("normal",vn(a.normal)),s&&!c.tangent&&a.tangent&&t.setAttribute("tangent",vn(a.tangent)),Ht(n.index,t.index),Ht(a.position,c.position),o&&Ht(a.normal,c.normal),s&&Ht(a.tangent,c.tangent);const d=a.position,f=o?a.normal:null,u=s?a.tangent:null,l=n.morphAttributes.position,g=n.morphAttributes.normal,y=n.morphAttributes.tangent,b=n.morphTargetsRelative,m=r.morphTargetInfluences,_=new h.Matrix3;_.getNormalMatrix(r.matrixWorld),n.index&&t.index.array.set(n.index.array);for(let x=0,w=a.position.count;x<w;x++)kt.fromBufferAttribute(d,x),f&&Bt.fromBufferAttribute(f,x),u&&(ps.fromBufferAttribute(u,x),zt.fromBufferAttribute(u,x)),m&&(l&&er(l,m,b,x,kt),g&&er(g,m,b,x,Bt),y&&er(y,m,b,x,zt)),r.isSkinnedMesh&&(r.applyBoneTransform(x,kt),f&&vs(r,x,Bt),u&&vs(r,x,zt)),i&&kt.applyMatrix4(r.matrixWorld),c.position.setXYZ(x,kt.x,kt.y,kt.z),f&&(i&&Bt.applyNormalMatrix(_),c.normal.setXYZ(x,Bt.x,Bt.y,Bt.z)),u&&(i&&zt.transformDirection(r.matrixWorld),c.tangent.setXYZW(x,zt.x,zt.y,zt.z,ps.w));for(const x in e.attributes){const w=e.attributes[x];w==="position"||w==="tangent"||w==="normal"||!(w in a)||(c[w]||t.setAttribute(w,vn(a[w])),Ht(a[w],c[w]),hs(a[w],c[w]))}return r.matrixWorld.determinant()<0&&Zc(t),t}class Kc extends h.BufferGeometry{constructor(){super(),this.version=0,this.hash=null,this._diff=new jc}isCompatible(e,t){const n=e.geometry;for(let i=0;i<t.length;i++){const o=t[i],s=n.attributes[o],a=this.attributes[o];if(s&&!Ht(s,a))return!1}return!0}updateFrom(e,t){const n=this._diff;return n.didChange(e)?(Yc(e,t,this),n.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const tr=0,xs=1,bs=2;function Xc(r,e){for(let t=0,n=r.length;t<n;t++)r[t].traverseVisible(o=>{o.isMesh&&e(o)})}function $c(r){const e=[];for(let t=0,n=r.length;t<n;t++){const i=r[t];Array.isArray(i.material)?e.push(...i.material):e.push(i.material)}return e}function Qc(r,e,t){if(r.length===0){e.setIndex(null);const n=e.attributes;for(const i in n)e.deleteAttribute(i);for(const i in t.attributes)e.setAttribute(t.attributes[i],new h.BufferAttribute(new Float32Array(0),4,!1))}else Gc(r,t,e);for(const n in e.attributes)e.attributes[n].needsUpdate=!0}class Jc{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new h.MeshBasicMaterial,t=new h.BufferGeometry;t.setAttribute("position",new h.BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new h.Mesh(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return Xc(this.objects,t=>{e.push(t)}),e.sort((t,n)=>t.uuid>n.uuid?1:t.uuid<n.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),n=new Set(e.keys()),i={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let o=0,s=t.length;o<s;o++){const a=t[o],c=a.uuid;n.delete(c);let d=e.get(c);(!d||!d.isCompatible(a,this.attributes))&&(d&&d.dispose(),d=new Kc,e.set(c,d)),d.updateFrom(a,i)&&this.generateMissingAttributes&&Wc(d,this.attributes)}n.forEach(o=>{e.delete(o)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new h.BufferGeometry){const{useGroups:t,overwriteIndex:n,_intermediateGeometry:i,_geometryMergeSets:o}=this,s=this._getMeshes(),a=[],c=[],d=o.get(e)||[];this._updateIntermediateGeometries();let f=!1;s.length!==d.length&&(f=!0);for(let l=0,g=s.length;l<g;l++){const y=s[l],b=i.get(y.uuid);c.push(b);const m=d[l];!m||m.uuid!==b.uuid?(a.push(!1),f=!0):m.version!==b.version?a.push(!1):a.push(!0)}Qc(c,e,{useGroups:t,forceUpdate:f,skipAssigningAttributes:a,overwriteIndex:n}),f&&e.dispose(),o.set(e,c.map(l=>({version:l.version,uuid:l.uuid})));let u=tr;return f?u=bs:a.includes(!1)&&(u=xs),{changeType:u,materials:$c(s),geometry:e}}}function Hc(r){const e=new Set;for(let t=0,n=r.length;t<n;t++){const i=r[t];for(const o in i){const s=i[o];s&&s.isTexture&&e.add(s)}}return Array.from(e)}function el(r){const e=[],t=new Set;for(let i=0,o=r.length;i<o;i++)r[i].traverse(s=>{s.visible&&(s.isRectAreaLight||s.isSpotLight||s.isPointLight||s.isDirectionalLight)&&(e.push(s),s.iesMap&&t.add(s.iesMap))});const n=Array.from(t).sort((i,o)=>i.uuid<o.uuid?1:i.uuid>o.uuid?-1:0);return{lights:e,iesTextures:n}}class tl{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new h.BufferGeometry,this.staticGeometryGenerator=new Jc(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:n,attributes:i}=this,o=t.objects;t.attributes=i,o.forEach(u=>{u.traverse(l=>{l.isSkinnedMesh&&l.skeleton&&l.skeleton.update()})});const s=t.generate(n),a=s.materials,c=Hc(a),{lights:d,iesTextures:f}=el(o);if(s.changeType!==tr&&Vc(n,a,a),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(s.changeType===bs){const u={strategy:Br,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(n,u):this.bvh=new ei(n,u)}else s.changeType===xs&&this.bvh.refit()}return{bvhChanged:s.changeType!==tr,bvh:this.bvh,lights:d,iesTextures:f,geometry:n,materials:a,textures:c,objects:o}}}const nl=new h.OrthographicCamera(-1,1,1,-1,0,1);class il extends h.BufferGeometry{constructor(){super(),this.setAttribute("position",new h.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new h.Float32BufferAttribute([0,2,0,0,2,0],2))}}const rl=new il;class en{constructor(e){this._mesh=new h.Mesh(rl,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,nl)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class nr extends h.ShaderMaterial{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(n){this.uniforms[t].value=n}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class sl extends nr{constructor(e){super({blending:h.NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
|
|
298
298
|
|
|
299
299
|
varying vec2 vUv;
|
|
300
300
|
|
|
@@ -331,7 +331,7 @@ struct BVH {
|
|
|
331
331
|
|
|
332
332
|
}
|
|
333
333
|
|
|
334
|
-
}`}),this.setValues(e)}}function
|
|
334
|
+
}`}),this.setValues(e)}}function ii(r=1){let e="uint";return r>1&&(e="uvec"+r),`
|
|
335
335
|
${e} sobolReverseBits( ${e} x ) {
|
|
336
336
|
|
|
337
337
|
x = ( ( ( x & 0xaaaaaaaau ) >> 1 ) | ( ( x & 0x55555555u ) << 1 ) );
|
|
@@ -366,7 +366,7 @@ struct BVH {
|
|
|
366
366
|
return x;
|
|
367
367
|
|
|
368
368
|
}
|
|
369
|
-
`}function
|
|
369
|
+
`}function ri(r=1){let e="uint",t="float",n="",i=".r",o="1u";return r>1&&(e="uvec"+r,t="vec"+r,n=r+"",r===2?(i=".rg",o="uvec2( 1u, 2u )"):r===3?(i=".rgb",o="uvec3( 1u, 2u, 3u )"):(i="",o="uvec4( 1u, 2u, 3u, 4u )")),`
|
|
370
370
|
|
|
371
371
|
${t} sobol${n}( int effect ) {
|
|
372
372
|
|
|
@@ -375,7 +375,7 @@ struct BVH {
|
|
|
375
375
|
|
|
376
376
|
uint shuffle_seed = sobolHashCombine( seed, 0u );
|
|
377
377
|
uint shuffled_index = nestedUniformScrambleBase2( sobolReverseBits( index ), shuffle_seed );
|
|
378
|
-
${t} sobol_pt = sobolGetTexturePoint( shuffled_index )${
|
|
378
|
+
${t} sobol_pt = sobolGetTexturePoint( shuffled_index )${i};
|
|
379
379
|
${e} result = ${e}( sobol_pt * 16777216.0 );
|
|
380
380
|
|
|
381
381
|
${e} seed2 = sobolHashCombine( seed, ${o} );
|
|
@@ -384,16 +384,16 @@ struct BVH {
|
|
|
384
384
|
return SOBOL_FACTOR * ${t}( result >> 8 );
|
|
385
385
|
|
|
386
386
|
}
|
|
387
|
-
`}const
|
|
387
|
+
`}const ws=`
|
|
388
388
|
|
|
389
389
|
// Utils
|
|
390
390
|
const float SOBOL_FACTOR = 1.0 / 16777216.0;
|
|
391
391
|
const uint SOBOL_MAX_POINTS = 256u * 256u;
|
|
392
392
|
|
|
393
|
-
${
|
|
394
|
-
${
|
|
395
|
-
${
|
|
396
|
-
${
|
|
393
|
+
${ii(1)}
|
|
394
|
+
${ii(2)}
|
|
395
|
+
${ii(3)}
|
|
396
|
+
${ii(4)}
|
|
397
397
|
|
|
398
398
|
uint sobolHash( uint x ) {
|
|
399
399
|
|
|
@@ -407,7 +407,7 @@ struct BVH {
|
|
|
407
407
|
|
|
408
408
|
}
|
|
409
409
|
|
|
410
|
-
`,
|
|
410
|
+
`,ol=`
|
|
411
411
|
|
|
412
412
|
const uint SOBOL_DIRECTIONS_1[ 32 ] = uint[ 32 ](
|
|
413
413
|
0x80000000u, 0xc0000000u, 0xa0000000u, 0xf0000000u,
|
|
@@ -485,7 +485,7 @@ struct BVH {
|
|
|
485
485
|
|
|
486
486
|
}
|
|
487
487
|
|
|
488
|
-
`,
|
|
488
|
+
`,al=`
|
|
489
489
|
|
|
490
490
|
// Seeds
|
|
491
491
|
uniform sampler2D sobolTexture;
|
|
@@ -523,12 +523,12 @@ struct BVH {
|
|
|
523
523
|
|
|
524
524
|
}
|
|
525
525
|
|
|
526
|
-
${
|
|
527
|
-
${
|
|
528
|
-
${
|
|
529
|
-
${
|
|
526
|
+
${ri(1)}
|
|
527
|
+
${ri(2)}
|
|
528
|
+
${ri(3)}
|
|
529
|
+
${ri(4)}
|
|
530
530
|
|
|
531
|
-
`;class
|
|
531
|
+
`;class cl extends nr{constructor(){super({blending:h.NoBlending,uniforms:{resolution:{value:new h.Vector2}},vertexShader:`
|
|
532
532
|
|
|
533
533
|
varying vec2 vUv;
|
|
534
534
|
void main() {
|
|
@@ -539,8 +539,8 @@ struct BVH {
|
|
|
539
539
|
}
|
|
540
540
|
`,fragmentShader:`
|
|
541
541
|
|
|
542
|
-
${
|
|
543
|
-
${
|
|
542
|
+
${ws}
|
|
543
|
+
${ol}
|
|
544
544
|
|
|
545
545
|
varying vec2 vUv;
|
|
546
546
|
uniform vec2 resolution;
|
|
@@ -550,7 +550,7 @@ struct BVH {
|
|
|
550
550
|
gl_FragColor = generateSobolPoint( index );
|
|
551
551
|
|
|
552
552
|
}
|
|
553
|
-
`})}}class Bc{generate(e,t=256){const n=new h.WebGLRenderTarget(t,t,{type:h.FloatType,format:h.RGBAFormat,minFilter:h.NearestFilter,magFilter:h.NearestFilter,generateMipmaps:!1}),r=e.getRenderTarget();e.setRenderTarget(n);const o=new Zt(new zc);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(r),o.dispose(),n}}class Uc extends h.PerspectiveCamera{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class Ec{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof Uc?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function Wr(s){const e=new Uint16Array(s.length);for(let t=0,n=s.length;t<n;++t)e[t]=h.DataUtils.toHalfFloat(s[t]);return e}function ts(s,e,t=0,n=s.length){let r=t,o=t+n-1;for(;r<o;){const i=r+o>>1;s[i]<e?r=i+1:o=i}return r-t}function Gc(s,e,t){return .2126*s+.7152*e+.0722*t}function Vc(s,e=h.HalfFloatType){const t=s.clone();t.source=new h.Source({...t.image});const{width:n,height:r,data:o}=t.image;let i=o;if(t.type!==e){e===h.HalfFloatType?i=new Uint16Array(o.length):i=new Float32Array(o.length);let a;o instanceof Int8Array||o instanceof Int16Array||o instanceof Int32Array?a=2**(8*o.BYTES_PER_ELEMENT-1)-1:a=2**(8*o.BYTES_PER_ELEMENT)-1;for(let c=0,f=o.length;c<f;c++){let d=o[c];t.type===h.HalfFloatType&&(d=h.DataUtils.fromHalfFloat(o[c])),t.type!==h.FloatType&&t.type!==h.HalfFloatType&&(d/=a),e===h.HalfFloatType&&(i[c]=h.DataUtils.toHalfFloat(d))}t.image.data=i,t.type=e}if(t.flipY){const a=i;i=i.slice();for(let c=0;c<r;c++)for(let f=0;f<n;f++){const d=r-c-1,u=4*(c*n+f),l=4*(d*n+f);i[l+0]=a[u+0],i[l+1]=a[u+1],i[l+2]=a[u+2],i[l+3]=a[u+3]}t.flipY=!1,t.image.data=i}return t}class Wc{constructor(){const e=new h.DataTexture(Wr(new Float32Array([0,0,0,0])),1,1);e.type=h.HalfFloatType,e.format=h.RGBAFormat,e.minFilter=h.LinearFilter,e.magFilter=h.LinearFilter,e.wrapS=h.RepeatWrapping,e.wrapT=h.RepeatWrapping,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new h.DataTexture(Wr(new Float32Array([0,1])),1,2);t.type=h.HalfFloatType,t.format=h.RedFormat,t.minFilter=h.LinearFilter,t.magFilter=h.LinearFilter,t.generateMipmaps=!1,t.needsUpdate=!0;const n=new h.DataTexture(Wr(new Float32Array([0,0,1,1])),2,2);n.type=h.HalfFloatType,n.format=h.RedFormat,n.minFilter=h.LinearFilter,n.magFilter=h.LinearFilter,n.generateMipmaps=!1,n.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=n,this.totalSum=0}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=Vc(e);t.wrapS=h.RepeatWrapping,t.wrapT=h.ClampToEdgeWrapping;const{width:n,height:r,data:o}=t.image,i=new Float32Array(n*r),a=new Float32Array(n*r),c=new Float32Array(r),f=new Float32Array(r);let d=0,u=0;for(let m=0;m<r;m++){let x=0;for(let b=0;b<n;b++){const T=m*n+b,M=h.DataUtils.fromHalfFloat(o[4*T+0]),A=h.DataUtils.fromHalfFloat(o[4*T+1]),I=h.DataUtils.fromHalfFloat(o[4*T+2]),P=Gc(M,A,I);x+=P,d+=P,i[T]=P,a[T]=x}if(x!==0)for(let b=m*n,T=m*n+n;b<T;b++)i[b]/=x,a[b]/=x;u+=x,c[m]=x,f[m]=u}if(u!==0)for(let m=0,x=c.length;m<x;m++)c[m]/=u,f[m]/=u;const l=new Uint16Array(r),g=new Uint16Array(n*r);for(let m=0;m<r;m++){const x=(m+1)/r,b=ts(f,x);l[m]=h.DataUtils.toHalfFloat((b+.5)/r)}for(let m=0;m<r;m++)for(let x=0;x<n;x++){const b=m*n+x,T=(x+1)/n,M=ts(a,T,m*n,n);g[b]=h.DataUtils.toHalfFloat((M+.5)/n)}this.dispose();const{marginalWeights:y,conditionalWeights:w}=this;y.image={width:r,height:1,data:l},y.needsUpdate=!0,w.image={width:n,height:r,data:g},w.needsUpdate=!0,this.totalSum=d,this.map=t}}const jr=6,jc=0,qc=1,Zc=2,Yc=3,Kc=4,He=new h.Vector3,ke=new h.Vector3,ns=new h.Matrix4,Yt=new h.Quaternion,rs=new h.Vector3,Kt=new h.Vector3,Xc=new h.Vector3(0,1,0);class $c{constructor(){const e=new h.DataTexture(new Float32Array(4),1,1);e.format=h.RGBAFormat,e.type=h.FloatType,e.wrapS=h.ClampToEdgeWrapping,e.wrapT=h.ClampToEdgeWrapping,e.generateMipmaps=!1,e.minFilter=h.NearestFilter,e.magFilter=h.NearestFilter,this.tex=e,this.count=0}updateFrom(e,t=[]){const n=this.tex,r=Math.max(e.length*jr,1),o=Math.ceil(Math.sqrt(r));n.image.width!==o&&(n.dispose(),n.image.data=new Float32Array(o*o*4),n.image.width=o,n.image.height=o);const i=n.image.data;for(let c=0,f=e.length;c<f;c++){const d=e[c],u=c*jr*4;let l=0;for(let y=0;y<jr*4;y++)i[u+y]=0;d.getWorldPosition(ke),i[u+l++]=ke.x,i[u+l++]=ke.y,i[u+l++]=ke.z;let g=jc;if(d.isRectAreaLight&&d.isCircular?g=qc:d.isSpotLight?g=Zc:d.isDirectionalLight?g=Yc:d.isPointLight&&(g=Kc),i[u+l++]=g,i[u+l++]=d.color.r,i[u+l++]=d.color.g,i[u+l++]=d.color.b,i[u+l++]=d.intensity,d.getWorldQuaternion(Yt),d.isRectAreaLight)He.set(d.width,0,0).applyQuaternion(Yt),i[u+l++]=He.x,i[u+l++]=He.y,i[u+l++]=He.z,l++,ke.set(0,d.height,0).applyQuaternion(Yt),i[u+l++]=ke.x,i[u+l++]=ke.y,i[u+l++]=ke.z,i[u+l++]=He.cross(ke).length()*(d.isCircular?Math.PI/4:1);else if(d.isSpotLight){const y=d.radius||0;rs.setFromMatrixPosition(d.matrixWorld),Kt.setFromMatrixPosition(d.target.matrixWorld),ns.lookAt(rs,Kt,Xc),Yt.setFromRotationMatrix(ns),He.set(1,0,0).applyQuaternion(Yt),i[u+l++]=He.x,i[u+l++]=He.y,i[u+l++]=He.z,l++,ke.set(0,1,0).applyQuaternion(Yt),i[u+l++]=ke.x,i[u+l++]=ke.y,i[u+l++]=ke.z,i[u+l++]=Math.PI*y*y,i[u+l++]=y,i[u+l++]=d.decay,i[u+l++]=d.distance,i[u+l++]=Math.cos(d.angle),i[u+l++]=Math.cos(d.angle*(1-d.penumbra)),i[u+l++]=d.iesMap?t.indexOf(d.iesMap):-1}else if(d.isPointLight){const y=He.setFromMatrixPosition(d.matrixWorld);i[u+l++]=y.x,i[u+l++]=y.y,i[u+l++]=y.z,l++,l+=4,l+=1,i[u+l++]=d.decay,i[u+l++]=d.distance}else if(d.isDirectionalLight){const y=He.setFromMatrixPosition(d.matrixWorld),w=ke.setFromMatrixPosition(d.target.matrixWorld);Kt.subVectors(y,w).normalize(),i[u+l++]=Kt.x,i[u+l++]=Kt.y,i[u+l++]=Kt.z}}this.count=e.length;const a=Br(i.buffer);return this.hash!==a?(this.hash=a,n.needsUpdate=!0,!0):!1}}function is(s,e,t,n,r){if(e>n)throw new Error;const o=s.length/e,i=s.constructor.BYTES_PER_ELEMENT*8;let a=1;switch(s.constructor){case Uint8Array:case Uint16Array:case Uint32Array:a=2**i-1;break;case Int8Array:case Int16Array:case Int32Array:a=2**(i-1)-1;break}for(let c=0;c<o;c++){const f=4*c,d=e*c;for(let u=0;u<n;u++)t[r+f+u]=e>=u+1?s[d+u]/a:0}}class Qc extends h.DataArrayTexture{constructor(){super(),this._textures=[],this.type=h.FloatType,this.format=h.RGBAFormat,this.internalFormat="RGBA32F"}updateAttribute(e,t){const n=this._textures[e];n.updateFrom(t);const r=n.image,o=this.image;if(r.width!==o.width||r.height!==o.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:i,height:a,data:c}=o,d=i*a*4*e;let u=t.itemSize;u===3&&(u=4),is(n.image.data,u,c,4,d),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,n=e.length;for(let u=0,l=n;u<l;u++)if(e[u].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const r=this._textures;for(;r.length<n;){const u=new Wi;r.push(u)}for(;r.length>n;)r.pop();for(let u=0,l=n;u<l;u++)r[u].updateFrom(e[u]);const i=r[0].image,a=this.image;(i.width!==a.width||i.height!==a.height||i.depth!==n)&&(a.width=i.width,a.height=i.height,a.depth=n,a.data=new Float32Array(a.width*a.height*a.depth*4));const{data:c,width:f,height:d}=a;for(let u=0,l=n;u<l;u++){const g=r[u],w=f*d*4*u;let m=e[u].itemSize;m===3&&(m=4),is(g.image.data,m,c,4,w)}this.dispose(),this.needsUpdate=!0}}class Jc extends Qc{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,n,r){this.setAttributes([e,t,n,r])}}function qr(s,e){return s.uuid<e.uuid?1:s.uuid>e.uuid?-1:0}function Zr(s){return`${s.source.uuid}:${s.colorSpace}`}function Hc(s){const e=new Set,t=[];for(let n=0,r=s.length;n<r;n++){const o=s[n],i=Zr(o);e.has(i)||(e.add(i),t.push(o))}return t}function el(s){const e=s.map(n=>n.iesMap||null).filter(n=>n),t=new Set(e);return Array.from(t).sort(qr)}function tl(s){const e=new Set;for(let n=0,r=s.length;n<r;n++){const o=s[n];for(const i in o){const a=o[i];a&&a.isTexture&&e.add(a)}}const t=Array.from(e);return Hc(t).sort(qr)}function nl(s){const e=[];return s.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(qr)}const ss=45,os=ss*4;class rl{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class il extends h.DataTexture{constructor(){super(new Float32Array(4),1,1),this.format=h.RGBAFormat,this.type=h.FloatType,this.wrapS=h.ClampToEdgeWrapping,this.wrapT=h.ClampToEdgeWrapping,this.minFilter=h.NearestFilter,this.magFilter=h.NearestFilter,this.generateMipmaps=!1,this.features=new rl}updateFrom(e,t){function n(y,w,m=-1){if(w in y&&y[w]){const x=Zr(y[w]);return u[x]}else return m}function r(y,w,m){return w in y?y[w]:m}function o(y,w,m,x){const b=y[w]&&y[w].isTexture?y[w]:null;if(b){b.matrixAutoUpdate&&b.updateMatrix();const T=b.matrix.elements;let M=0;m[x+M++]=T[0],m[x+M++]=T[3],m[x+M++]=T[6],M++,m[x+M++]=T[1],m[x+M++]=T[4],m[x+M++]=T[7],M++}return 8}let i=0;const a=e.length*ss,c=Math.ceil(Math.sqrt(a))||1,{image:f,features:d}=this,u={};for(let y=0,w=t.length;y<w;y++)u[Zr(t[y])]=y;f.width!==c&&(this.dispose(),f.data=new Float32Array(c*c*4),f.width=c,f.height=c);const l=f.data;d.reset();for(let y=0,w=e.length;y<w;y++){const m=e[y];if(m.isFogVolumeMaterial){d.setUsed("FOG");for(let T=0;T<os;T++)l[i+T]=0;l[i+0*4+0]=m.color.r,l[i+0*4+1]=m.color.g,l[i+0*4+2]=m.color.b,l[i+2*4+3]=r(m,"emissiveIntensity",0),l[i+3*4+0]=m.emissive.r,l[i+3*4+1]=m.emissive.g,l[i+3*4+2]=m.emissive.b,l[i+13*4+1]=m.density,l[i+13*4+3]=0,l[i+14*4+2]=4,i+=os;continue}l[i++]=m.color.r,l[i++]=m.color.g,l[i++]=m.color.b,l[i++]=n(m,"map"),l[i++]=r(m,"metalness",0),l[i++]=n(m,"metalnessMap"),l[i++]=r(m,"roughness",0),l[i++]=n(m,"roughnessMap"),l[i++]=r(m,"ior",1.5),l[i++]=r(m,"transmission",0),l[i++]=n(m,"transmissionMap"),l[i++]=r(m,"emissiveIntensity",0),"emissive"in m?(l[i++]=m.emissive.r,l[i++]=m.emissive.g,l[i++]=m.emissive.b):(l[i++]=0,l[i++]=0,l[i++]=0),l[i++]=n(m,"emissiveMap"),l[i++]=n(m,"normalMap"),"normalScale"in m?(l[i++]=m.normalScale.x,l[i++]=m.normalScale.y):(l[i++]=1,l[i++]=1),l[i++]=r(m,"clearcoat",0),l[i++]=n(m,"clearcoatMap"),l[i++]=r(m,"clearcoatRoughness",0),l[i++]=n(m,"clearcoatRoughnessMap"),l[i++]=n(m,"clearcoatNormalMap"),"clearcoatNormalScale"in m?(l[i++]=m.clearcoatNormalScale.x,l[i++]=m.clearcoatNormalScale.y):(l[i++]=1,l[i++]=1),i++,l[i++]=r(m,"sheen",0),"sheenColor"in m?(l[i++]=m.sheenColor.r,l[i++]=m.sheenColor.g,l[i++]=m.sheenColor.b):(l[i++]=0,l[i++]=0,l[i++]=0),l[i++]=n(m,"sheenColorMap"),l[i++]=r(m,"sheenRoughness",0),l[i++]=n(m,"sheenRoughnessMap"),l[i++]=n(m,"iridescenceMap"),l[i++]=n(m,"iridescenceThicknessMap"),l[i++]=r(m,"iridescence",0),l[i++]=r(m,"iridescenceIOR",1.3);const x=r(m,"iridescenceThicknessRange",[100,400]);l[i++]=x[0],l[i++]=x[1],"specularColor"in m?(l[i++]=m.specularColor.r,l[i++]=m.specularColor.g,l[i++]=m.specularColor.b):(l[i++]=1,l[i++]=1,l[i++]=1),l[i++]=n(m,"specularColorMap"),l[i++]=r(m,"specularIntensity",1),l[i++]=n(m,"specularIntensityMap");const b=r(m,"thickness",0)===0&&r(m,"attenuationDistance",1/0)===1/0;if(l[i++]=Number(b),i++,"attenuationColor"in m?(l[i++]=m.attenuationColor.r,l[i++]=m.attenuationColor.g,l[i++]=m.attenuationColor.b):(l[i++]=1,l[i++]=1,l[i++]=1),l[i++]=r(m,"attenuationDistance",1/0),l[i++]=n(m,"alphaMap"),l[i++]=m.opacity,l[i++]=m.alphaTest,!b&&m.transmission>0)l[i++]=0;else switch(m.side){case h.FrontSide:l[i++]=1;break;case h.BackSide:l[i++]=-1;break;case h.DoubleSide:l[i++]=0;break}l[i++]=Number(r(m,"matte",!1)),l[i++]=Number(r(m,"castShadow",!0)),l[i++]=Number(m.vertexColors)|Number(m.flatShading)<<1,l[i++]=Number(m.transparent),i+=o(m,"map",l,i),i+=o(m,"metalnessMap",l,i),i+=o(m,"roughnessMap",l,i),i+=o(m,"transmissionMap",l,i),i+=o(m,"emissiveMap",l,i),i+=o(m,"normalMap",l,i),i+=o(m,"clearcoatMap",l,i),i+=o(m,"clearcoatNormalMap",l,i),i+=o(m,"clearcoatRoughnessMap",l,i),i+=o(m,"sheenColorMap",l,i),i+=o(m,"sheenRoughnessMap",l,i),i+=o(m,"iridescenceMap",l,i),i+=o(m,"iridescenceThicknessMap",l,i),i+=o(m,"specularColorMap",l,i),i+=o(m,"specularIntensityMap",l,i)}const g=Br(l.buffer);return this.hash!==g?(this.hash=g,this.needsUpdate=!0,!0):!1}}const as=new h.Color;function sl(s){return s?`${s.uuid}:${s.version}`:null}function ol(s,e){for(const t in e)t in s&&(s[t]=e[t])}class cs extends h.WebGLArrayRenderTarget{constructor(e,t,n){const r={format:h.RGBAFormat,type:h.UnsignedByteType,minFilter:h.LinearFilter,magFilter:h.LinearFilter,wrapS:h.RepeatWrapping,wrapT:h.RepeatWrapping,generateMipmaps:!1,...n};super(e,t,1,r),ol(this.texture,r),this.texture.setTextures=(...i)=>{this.setTextures(...i)},this.hashes=[null];const o=new Zt(new al);this.fsQuad=o}setTextures(e,t,n=this.width,r=this.height){const o=e.getRenderTarget(),i=e.toneMapping,a=e.getClearAlpha();e.getClearColor(as);const c=t.length||1;(n!==this.width||r!==this.height||this.depth!==c)&&(this.setSize(n,r,c),this.hashes=new Array(c).fill(null)),e.setClearColor(0,0),e.toneMapping=h.NoToneMapping;const f=this.fsQuad,d=this.hashes;let u=!1;for(let l=0,g=c;l<g;l++){const y=t[l],w=sl(y);y&&(d[l]!==w||y.isWebGLRenderTarget)&&(y.matrixAutoUpdate=!1,y.matrix.identity(),f.material.map=y,e.setRenderTarget(this,l),f.render(e),y.updateMatrix(),y.matrixAutoUpdate=!0,d[l]=w,u=!0)}return f.material.map=null,e.setClearColor(as,a),e.setRenderTarget(o),e.toneMapping=i,u}dispose(){super.dispose(),this.fsQuad.dispose()}}class al extends h.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
|
|
553
|
+
`})}}class ll{generate(e,t=256){const n=new h.WebGLRenderTarget(t,t,{type:h.FloatType,format:h.RGBAFormat,minFilter:h.NearestFilter,magFilter:h.NearestFilter,generateMipmaps:!1}),i=e.getRenderTarget();e.setRenderTarget(n);const o=new en(new cl);return o.material.resolution.set(t,t),o.render(e),e.setRenderTarget(i),o.dispose(),n}}class ul extends h.PerspectiveCamera{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class hl{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof ul?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function ir(r){const e=new Uint16Array(r.length);for(let t=0,n=r.length;t<n;++t)e[t]=h.DataUtils.toHalfFloat(r[t]);return e}function _s(r,e,t=0,n=r.length){let i=t,o=t+n-1;for(;i<o;){const s=i+o>>1;r[s]<e?i=s+1:o=s}return i-t}function dl(r,e,t){return .2126*r+.7152*e+.0722*t}function fl(r,e=h.HalfFloatType){const t=r.clone();t.source=new h.Source({...t.image});const{width:n,height:i,data:o}=t.image;let s=o;if(t.type!==e){e===h.HalfFloatType?s=new Uint16Array(o.length):s=new Float32Array(o.length);let a;o instanceof Int8Array||o instanceof Int16Array||o instanceof Int32Array?a=2**(8*o.BYTES_PER_ELEMENT-1)-1:a=2**(8*o.BYTES_PER_ELEMENT)-1;for(let c=0,d=o.length;c<d;c++){let f=o[c];t.type===h.HalfFloatType&&(f=h.DataUtils.fromHalfFloat(o[c])),t.type!==h.FloatType&&t.type!==h.HalfFloatType&&(f/=a),e===h.HalfFloatType&&(s[c]=h.DataUtils.toHalfFloat(f))}t.image.data=s,t.type=e}if(t.flipY){const a=s;s=s.slice();for(let c=0;c<i;c++)for(let d=0;d<n;d++){const f=i-c-1,u=4*(c*n+d),l=4*(f*n+d);s[l+0]=a[u+0],s[l+1]=a[u+1],s[l+2]=a[u+2],s[l+3]=a[u+3]}t.flipY=!1,t.image.data=s}return t}class pl{constructor(){const e=new h.DataTexture(ir(new Float32Array([0,0,0,0])),1,1);e.type=h.HalfFloatType,e.format=h.RGBAFormat,e.minFilter=h.LinearFilter,e.magFilter=h.LinearFilter,e.wrapS=h.RepeatWrapping,e.wrapT=h.RepeatWrapping,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new h.DataTexture(ir(new Float32Array([0,1])),1,2);t.type=h.HalfFloatType,t.format=h.RedFormat,t.minFilter=h.LinearFilter,t.magFilter=h.LinearFilter,t.generateMipmaps=!1,t.needsUpdate=!0;const n=new h.DataTexture(ir(new Float32Array([0,0,1,1])),2,2);n.type=h.HalfFloatType,n.format=h.RedFormat,n.minFilter=h.LinearFilter,n.magFilter=h.LinearFilter,n.generateMipmaps=!1,n.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=n,this.totalSum=0}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=fl(e);t.wrapS=h.RepeatWrapping,t.wrapT=h.ClampToEdgeWrapping;const{width:n,height:i,data:o}=t.image,s=new Float32Array(n*i),a=new Float32Array(n*i),c=new Float32Array(i),d=new Float32Array(i);let f=0,u=0;for(let m=0;m<i;m++){let _=0;for(let x=0;x<n;x++){const w=m*n+x,S=h.DataUtils.fromHalfFloat(o[4*w+0]),M=h.DataUtils.fromHalfFloat(o[4*w+1]),I=h.DataUtils.fromHalfFloat(o[4*w+2]),C=dl(S,M,I);_+=C,f+=C,s[w]=C,a[w]=_}if(_!==0)for(let x=m*n,w=m*n+n;x<w;x++)s[x]/=_,a[x]/=_;u+=_,c[m]=_,d[m]=u}if(u!==0)for(let m=0,_=c.length;m<_;m++)c[m]/=u,d[m]/=u;const l=new Uint16Array(i),g=new Uint16Array(n*i);for(let m=0;m<i;m++){const _=(m+1)/i,x=_s(d,_);l[m]=h.DataUtils.toHalfFloat((x+.5)/i)}for(let m=0;m<i;m++)for(let _=0;_<n;_++){const x=m*n+_,w=(_+1)/n,S=_s(a,w,m*n,n);g[x]=h.DataUtils.toHalfFloat((S+.5)/n)}this.dispose();const{marginalWeights:y,conditionalWeights:b}=this;y.image={width:i,height:1,data:l},y.needsUpdate=!0,b.image={width:n,height:i,data:g},b.needsUpdate=!0,this.totalSum=f,this.map=t}}const rr=6,ml=0,gl=1,yl=2,vl=3,xl=4,ot=new h.Vector3,Ze=new h.Vector3,Ss=new h.Matrix4,tn=new h.Quaternion,Ts=new h.Vector3,nn=new h.Vector3,bl=new h.Vector3(0,1,0);class wl{constructor(){const e=new h.DataTexture(new Float32Array(4),1,1);e.format=h.RGBAFormat,e.type=h.FloatType,e.wrapS=h.ClampToEdgeWrapping,e.wrapT=h.ClampToEdgeWrapping,e.generateMipmaps=!1,e.minFilter=h.NearestFilter,e.magFilter=h.NearestFilter,this.tex=e,this.count=0}updateFrom(e,t=[]){const n=this.tex,i=Math.max(e.length*rr,1),o=Math.ceil(Math.sqrt(i));n.image.width!==o&&(n.dispose(),n.image.data=new Float32Array(o*o*4),n.image.width=o,n.image.height=o);const s=n.image.data;for(let c=0,d=e.length;c<d;c++){const f=e[c],u=c*rr*4;let l=0;for(let y=0;y<rr*4;y++)s[u+y]=0;f.getWorldPosition(Ze),s[u+l++]=Ze.x,s[u+l++]=Ze.y,s[u+l++]=Ze.z;let g=ml;if(f.isRectAreaLight&&f.isCircular?g=gl:f.isSpotLight?g=yl:f.isDirectionalLight?g=vl:f.isPointLight&&(g=xl),s[u+l++]=g,s[u+l++]=f.color.r,s[u+l++]=f.color.g,s[u+l++]=f.color.b,s[u+l++]=f.intensity,f.getWorldQuaternion(tn),f.isRectAreaLight)ot.set(f.width,0,0).applyQuaternion(tn),s[u+l++]=ot.x,s[u+l++]=ot.y,s[u+l++]=ot.z,l++,Ze.set(0,f.height,0).applyQuaternion(tn),s[u+l++]=Ze.x,s[u+l++]=Ze.y,s[u+l++]=Ze.z,s[u+l++]=ot.cross(Ze).length()*(f.isCircular?Math.PI/4:1);else if(f.isSpotLight){const y=f.radius||0;Ts.setFromMatrixPosition(f.matrixWorld),nn.setFromMatrixPosition(f.target.matrixWorld),Ss.lookAt(Ts,nn,bl),tn.setFromRotationMatrix(Ss),ot.set(1,0,0).applyQuaternion(tn),s[u+l++]=ot.x,s[u+l++]=ot.y,s[u+l++]=ot.z,l++,Ze.set(0,1,0).applyQuaternion(tn),s[u+l++]=Ze.x,s[u+l++]=Ze.y,s[u+l++]=Ze.z,s[u+l++]=Math.PI*y*y,s[u+l++]=y,s[u+l++]=f.decay,s[u+l++]=f.distance,s[u+l++]=Math.cos(f.angle),s[u+l++]=Math.cos(f.angle*(1-f.penumbra)),s[u+l++]=f.iesMap?t.indexOf(f.iesMap):-1}else if(f.isPointLight){const y=ot.setFromMatrixPosition(f.matrixWorld);s[u+l++]=y.x,s[u+l++]=y.y,s[u+l++]=y.z,l++,l+=4,l+=1,s[u+l++]=f.decay,s[u+l++]=f.distance}else if(f.isDirectionalLight){const y=ot.setFromMatrixPosition(f.matrixWorld),b=Ze.setFromMatrixPosition(f.target.matrixWorld);nn.subVectors(y,b).normalize(),s[u+l++]=nn.x,s[u+l++]=nn.y,s[u+l++]=nn.z}}this.count=e.length;const a=Ji(s.buffer);return this.hash!==a?(this.hash=a,n.needsUpdate=!0,!0):!1}}function Ms(r,e,t,n,i){if(e>n)throw new Error;const o=r.length/e,s=r.constructor.BYTES_PER_ELEMENT*8;let a=1;switch(r.constructor){case Uint8Array:case Uint16Array:case Uint32Array:a=2**s-1;break;case Int8Array:case Int16Array:case Int32Array:a=2**(s-1)-1;break}for(let c=0;c<o;c++){const d=4*c,f=e*c;for(let u=0;u<n;u++)t[i+d+u]=e>=u+1?r[f+u]/a:0}}class _l extends h.DataArrayTexture{constructor(){super(),this._textures=[],this.type=h.FloatType,this.format=h.RGBAFormat,this.internalFormat="RGBA32F"}updateAttribute(e,t){const n=this._textures[e];n.updateFrom(t);const i=n.image,o=this.image;if(i.width!==o.width||i.height!==o.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:s,height:a,data:c}=o,f=s*a*4*e;let u=t.itemSize;u===3&&(u=4),Ms(n.image.data,u,c,4,f),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,n=e.length;for(let u=0,l=n;u<l;u++)if(e[u].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const i=this._textures;for(;i.length<n;){const u=new us;i.push(u)}for(;i.length>n;)i.pop();for(let u=0,l=n;u<l;u++)i[u].updateFrom(e[u]);const s=i[0].image,a=this.image;(s.width!==a.width||s.height!==a.height||s.depth!==n)&&(a.width=s.width,a.height=s.height,a.depth=n,a.data=new Float32Array(a.width*a.height*a.depth*4));const{data:c,width:d,height:f}=a;for(let u=0,l=n;u<l;u++){const g=i[u],b=d*f*4*u;let m=e[u].itemSize;m===3&&(m=4),Ms(g.image.data,m,c,4,b)}this.dispose(),this.needsUpdate=!0}}class Sl extends _l{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,n,i){this.setAttributes([e,t,n,i])}}function sr(r,e){return r.uuid<e.uuid?1:r.uuid>e.uuid?-1:0}function or(r){return`${r.source.uuid}:${r.colorSpace}`}function Tl(r){const e=new Set,t=[];for(let n=0,i=r.length;n<i;n++){const o=r[n],s=or(o);e.has(s)||(e.add(s),t.push(o))}return t}function Ml(r){const e=r.map(n=>n.iesMap||null).filter(n=>n),t=new Set(e);return Array.from(t).sort(sr)}function Al(r){const e=new Set;for(let n=0,i=r.length;n<i;n++){const o=r[n];for(const s in o){const a=o[s];a&&a.isTexture&&e.add(a)}}const t=Array.from(e);return Tl(t).sort(sr)}function Il(r){const e=[];return r.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t)}),e.sort(sr)}const As=45,Is=As*4;class Cl{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class Pl extends h.DataTexture{constructor(){super(new Float32Array(4),1,1),this.format=h.RGBAFormat,this.type=h.FloatType,this.wrapS=h.ClampToEdgeWrapping,this.wrapT=h.ClampToEdgeWrapping,this.minFilter=h.NearestFilter,this.magFilter=h.NearestFilter,this.generateMipmaps=!1,this.features=new Cl}updateFrom(e,t){function n(y,b,m=-1){if(b in y&&y[b]){const _=or(y[b]);return u[_]}else return m}function i(y,b,m){return b in y?y[b]:m}function o(y,b,m,_){const x=y[b]&&y[b].isTexture?y[b]:null;if(x){x.matrixAutoUpdate&&x.updateMatrix();const w=x.matrix.elements;let S=0;m[_+S++]=w[0],m[_+S++]=w[3],m[_+S++]=w[6],S++,m[_+S++]=w[1],m[_+S++]=w[4],m[_+S++]=w[7],S++}return 8}let s=0;const a=e.length*As,c=Math.ceil(Math.sqrt(a))||1,{image:d,features:f}=this,u={};for(let y=0,b=t.length;y<b;y++)u[or(t[y])]=y;d.width!==c&&(this.dispose(),d.data=new Float32Array(c*c*4),d.width=c,d.height=c);const l=d.data;f.reset();for(let y=0,b=e.length;y<b;y++){const m=e[y];if(m.isFogVolumeMaterial){f.setUsed("FOG");for(let w=0;w<Is;w++)l[s+w]=0;l[s+0*4+0]=m.color.r,l[s+0*4+1]=m.color.g,l[s+0*4+2]=m.color.b,l[s+2*4+3]=i(m,"emissiveIntensity",0),l[s+3*4+0]=m.emissive.r,l[s+3*4+1]=m.emissive.g,l[s+3*4+2]=m.emissive.b,l[s+13*4+1]=m.density,l[s+13*4+3]=0,l[s+14*4+2]=4,s+=Is;continue}l[s++]=m.color.r,l[s++]=m.color.g,l[s++]=m.color.b,l[s++]=n(m,"map"),l[s++]=i(m,"metalness",0),l[s++]=n(m,"metalnessMap"),l[s++]=i(m,"roughness",0),l[s++]=n(m,"roughnessMap"),l[s++]=i(m,"ior",1.5),l[s++]=i(m,"transmission",0),l[s++]=n(m,"transmissionMap"),l[s++]=i(m,"emissiveIntensity",0),"emissive"in m?(l[s++]=m.emissive.r,l[s++]=m.emissive.g,l[s++]=m.emissive.b):(l[s++]=0,l[s++]=0,l[s++]=0),l[s++]=n(m,"emissiveMap"),l[s++]=n(m,"normalMap"),"normalScale"in m?(l[s++]=m.normalScale.x,l[s++]=m.normalScale.y):(l[s++]=1,l[s++]=1),l[s++]=i(m,"clearcoat",0),l[s++]=n(m,"clearcoatMap"),l[s++]=i(m,"clearcoatRoughness",0),l[s++]=n(m,"clearcoatRoughnessMap"),l[s++]=n(m,"clearcoatNormalMap"),"clearcoatNormalScale"in m?(l[s++]=m.clearcoatNormalScale.x,l[s++]=m.clearcoatNormalScale.y):(l[s++]=1,l[s++]=1),s++,l[s++]=i(m,"sheen",0),"sheenColor"in m?(l[s++]=m.sheenColor.r,l[s++]=m.sheenColor.g,l[s++]=m.sheenColor.b):(l[s++]=0,l[s++]=0,l[s++]=0),l[s++]=n(m,"sheenColorMap"),l[s++]=i(m,"sheenRoughness",0),l[s++]=n(m,"sheenRoughnessMap"),l[s++]=n(m,"iridescenceMap"),l[s++]=n(m,"iridescenceThicknessMap"),l[s++]=i(m,"iridescence",0),l[s++]=i(m,"iridescenceIOR",1.3);const _=i(m,"iridescenceThicknessRange",[100,400]);l[s++]=_[0],l[s++]=_[1],"specularColor"in m?(l[s++]=m.specularColor.r,l[s++]=m.specularColor.g,l[s++]=m.specularColor.b):(l[s++]=1,l[s++]=1,l[s++]=1),l[s++]=n(m,"specularColorMap"),l[s++]=i(m,"specularIntensity",1),l[s++]=n(m,"specularIntensityMap");const x=i(m,"thickness",0)===0&&i(m,"attenuationDistance",1/0)===1/0;if(l[s++]=Number(x),s++,"attenuationColor"in m?(l[s++]=m.attenuationColor.r,l[s++]=m.attenuationColor.g,l[s++]=m.attenuationColor.b):(l[s++]=1,l[s++]=1,l[s++]=1),l[s++]=i(m,"attenuationDistance",1/0),l[s++]=n(m,"alphaMap"),l[s++]=m.opacity,l[s++]=m.alphaTest,!x&&m.transmission>0)l[s++]=0;else switch(m.side){case h.FrontSide:l[s++]=1;break;case h.BackSide:l[s++]=-1;break;case h.DoubleSide:l[s++]=0;break}l[s++]=Number(i(m,"matte",!1)),l[s++]=Number(i(m,"castShadow",!0)),l[s++]=Number(m.vertexColors)|Number(m.flatShading)<<1,l[s++]=Number(m.transparent),s+=o(m,"map",l,s),s+=o(m,"metalnessMap",l,s),s+=o(m,"roughnessMap",l,s),s+=o(m,"transmissionMap",l,s),s+=o(m,"emissiveMap",l,s),s+=o(m,"normalMap",l,s),s+=o(m,"clearcoatMap",l,s),s+=o(m,"clearcoatNormalMap",l,s),s+=o(m,"clearcoatRoughnessMap",l,s),s+=o(m,"sheenColorMap",l,s),s+=o(m,"sheenRoughnessMap",l,s),s+=o(m,"iridescenceMap",l,s),s+=o(m,"iridescenceThicknessMap",l,s),s+=o(m,"specularColorMap",l,s),s+=o(m,"specularIntensityMap",l,s)}const g=Ji(l.buffer);return this.hash!==g?(this.hash=g,this.needsUpdate=!0,!0):!1}}const Cs=new h.Color;function Dl(r){return r?`${r.uuid}:${r.version}`:null}function Fl(r,e){for(const t in e)t in r&&(r[t]=e[t])}class Ps extends h.WebGLArrayRenderTarget{constructor(e,t,n){const i={format:h.RGBAFormat,type:h.UnsignedByteType,minFilter:h.LinearFilter,magFilter:h.LinearFilter,wrapS:h.RepeatWrapping,wrapT:h.RepeatWrapping,generateMipmaps:!1,...n};super(e,t,1,i),Fl(this.texture,i),this.texture.setTextures=(...s)=>{this.setTextures(...s)},this.hashes=[null];const o=new en(new Rl);this.fsQuad=o}setTextures(e,t,n=this.width,i=this.height){const o=e.getRenderTarget(),s=e.toneMapping,a=e.getClearAlpha();e.getClearColor(Cs);const c=t.length||1;(n!==this.width||i!==this.height||this.depth!==c)&&(this.setSize(n,i,c),this.hashes=new Array(c).fill(null)),e.setClearColor(0,0),e.toneMapping=h.NoToneMapping;const d=this.fsQuad,f=this.hashes;let u=!1;for(let l=0,g=c;l<g;l++){const y=t[l],b=Dl(y);y&&(f[l]!==b||y.isWebGLRenderTarget)&&(y.matrixAutoUpdate=!1,y.matrix.identity(),d.material.map=y,e.setRenderTarget(this,l),d.render(e),y.updateMatrix(),y.matrixAutoUpdate=!0,f[l]=b,u=!0)}return d.material.map=null,e.setClearColor(Cs,a),e.setRenderTarget(o),e.toneMapping=s,u}dispose(){super.dispose(),this.fsQuad.dispose()}}class Rl extends h.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
|
|
554
554
|
varying vec2 vUv;
|
|
555
555
|
void main() {
|
|
556
556
|
|
|
@@ -566,7 +566,7 @@ struct BVH {
|
|
|
566
566
|
gl_FragColor = texture2D( map, vUv );
|
|
567
567
|
|
|
568
568
|
}
|
|
569
|
-
`})}}function
|
|
569
|
+
`})}}function Ol(r,e=Math.random()){for(let t=r.length-1;t>0;t--){const n=Math.floor(e()*(t+1)),i=r[t];r[t]=r[n],r[n]=i}return r}class Ll{constructor(e,t,n=Math.random){const i=e**t,o=new Uint16Array(i);let s=i;for(let a=0;a<i;a++)o[a]=a;this.samples=new Float32Array(t),this.strataCount=e,this.reset=function(){for(let a=0;a<i;a++)o[a]=a;s=0},this.reshuffle=function(){s=0},this.next=function(){const{samples:a}=this;s>=o.length&&(Ol(o,n),this.reshuffle());let c=o[s++];for(let d=0;d<t;d++)a[d]=(c%e+n())/e,c=Math.floor(c/e);return a}}}class Nl{constructor(e,t,n=Math.random){let i=0;for(const c of t)i+=c;const o=new Float32Array(i),s=[];let a=0;for(const c of t){const d=new Ll(e,c,n);d.samples=new Float32Array(o.buffer,a,d.samples.length),a+=d.samples.length*4,s.push(d)}this.samples=o,this.strataCount=e,this.next=function(){for(const c of s)c.next();return o},this.reshuffle=function(){for(const c of s)c.reshuffle()},this.reset=function(){for(const c of s)c.reset()}}}class kl{constructor(e=0){this.m=2147483648,this.a=1103515245,this.c=12345,this.seed=e}nextInt(){return this.seed=(this.a*this.seed+this.c)%this.m,this.seed}nextFloat(){return this.nextInt()/(this.m-1)}}class Bl extends h.DataTexture{constructor(e=1,t=1,n=8){super(new Float32Array(1),1,1,h.RGBAFormat,h.FloatType),this.minFilter=h.NearestFilter,this.magFilter=h.NearestFilter,this.strata=n,this.sampler=null,this.generator=new kl,this.stableNoise=!1,this.random=()=>this.stableNoise?this.generator.nextFloat():Math.random(),this.init(e,t,n)}init(e=this.image.height,t=this.image.width,n=this.strata){const{image:i}=this;if(i.width===t&&i.height===e&&this.sampler!==null)return;const o=new Array(e*t).fill(4),s=new Nl(n,o,this.random);i.width=t,i.height=e,i.data=s.samples,this.sampler=s,this.dispose(),this.next()}next(){this.sampler.next(),this.needsUpdate=!0}reset(){this.sampler.reset(),this.generator.seed=0}}function zl(r,e=Math.random){for(let t=r.length-1;t>0;t--){const n=~~((e()-1e-6)*t),i=r[t];r[t]=r[n],r[n]=i}}function Ul(r,e){r.fill(0);for(let t=0;t<e;t++)r[t]=1}class Ds{constructor(e){this.count=0,this.size=-1,this.sigma=-1,this.radius=-1,this.lookupTable=null,this.score=null,this.binaryPattern=null,this.resize(e),this.setSigma(1.5)}findVoid(){const{score:e,binaryPattern:t}=this;let n=1/0,i=-1;for(let o=0,s=t.length;o<s;o++){if(t[o]!==0)continue;const a=e[o];a<n&&(n=a,i=o)}return i}findCluster(){const{score:e,binaryPattern:t}=this;let n=-1/0,i=-1;for(let o=0,s=t.length;o<s;o++){if(t[o]!==1)continue;const a=e[o];a>n&&(n=a,i=o)}return i}setSigma(e){if(e===this.sigma)return;const t=~~(Math.sqrt(10*2*e**2)+1),n=2*t+1,i=new Float32Array(n*n),o=e*e;for(let s=-t;s<=t;s++)for(let a=-t;a<=t;a++){const c=(t+a)*n+s+t,d=s*s+a*a;i[c]=Math.E**(-d/(2*o))}this.lookupTable=i,this.sigma=e,this.radius=t}resize(e){this.size!==e&&(this.size=e,this.score=new Float32Array(e*e),this.binaryPattern=new Uint8Array(e*e))}invert(){const{binaryPattern:e,score:t,size:n}=this;t.fill(0);for(let i=0,o=e.length;i<o;i++)if(e[i]===0){const s=~~(i/n),a=i-s*n;this.updateScore(a,s,1),e[i]=1}else e[i]=0}updateScore(e,t,n){const{size:i,score:o,lookupTable:s}=this,a=this.radius,c=2*a+1;for(let d=-a;d<=a;d++)for(let f=-a;f<=a;f++){const u=(a+f)*c+d+a,l=s[u];let g=e+d;g=g<0?i+g:g%i;let y=t+f;y=y<0?i+y:y%i;const b=y*i+g;o[b]+=n*l}}addPointIndex(e){this.binaryPattern[e]=1;const t=this.size,n=~~(e/t),i=e-n*t;this.updateScore(i,n,1),this.count++}removePointIndex(e){this.binaryPattern[e]=0;const t=this.size,n=~~(e/t),i=e-n*t;this.updateScore(i,n,-1),this.count--}copy(e){this.resize(e.size),this.score.set(e.score),this.binaryPattern.set(e.binaryPattern),this.setSigma(e.sigma),this.count=e.count}}class El{constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new Ds(1),this.savedSamples=new Ds(1)}generate(){const{samples:e,savedSamples:t,sigma:n,majorityPointsRatio:i,size:o}=this;e.resize(o),e.setSigma(n);const s=Math.floor(o*o*i),a=e.binaryPattern;Ul(a,s),zl(a,this.random);for(let u=0,l=a.length;u<l;u++)a[u]===1&&e.addPointIndex(u);for(;;){const u=e.findCluster();e.removePointIndex(u);const l=e.findVoid();if(u===l){e.addPointIndex(u);break}e.addPointIndex(l)}const c=new Uint32Array(o*o);t.copy(e);let d;for(d=e.count-1;d>=0;){const u=e.findCluster();e.removePointIndex(u),c[u]=d,d--}const f=o*o;for(d=t.count;d<f/2;){const u=t.findVoid();t.addPointIndex(u),c[u]=d,d++}for(t.invert();d<f;){const u=t.findCluster();t.removePointIndex(u),c[u]=d,d++}return{data:c,maxValue:f}}}function Gl(r){return r>=3?4:r}function Vl(r){switch(r){case 1:return h.RedFormat;case 2:return h.RGFormat;default:return h.RGBAFormat}}class Wl extends h.DataTexture{constructor(e=64,t=1){super(new Float32Array(4),1,1,h.RGBAFormat,h.FloatType),this.minFilter=h.NearestFilter,this.magFilter=h.NearestFilter,this.size=e,this.channels=t,this.update()}update(){const e=this.channels,t=this.size,n=new El;n.channels=e,n.size=t;const i=Gl(e),o=Vl(i);(this.image.width!==t||o!==this.format)&&(this.image.width=t,this.image.height=t,this.image.data=new Float32Array(t**2*i),this.format=o,this.dispose());const s=this.image.data;for(let a=0,c=e;a<c;a++){const d=n.generate(),f=d.data,u=d.maxValue;for(let l=0,g=f.length;l<g;l++){const y=f[l]/u;s[l*i+a]=y}}this.needsUpdate=!0}}const jl=`
|
|
570
570
|
|
|
571
571
|
struct PhysicalCamera {
|
|
572
572
|
|
|
@@ -578,7 +578,7 @@ struct BVH {
|
|
|
578
578
|
|
|
579
579
|
};
|
|
580
580
|
|
|
581
|
-
`,
|
|
581
|
+
`,ql=`
|
|
582
582
|
|
|
583
583
|
struct EquirectHdrInfo {
|
|
584
584
|
|
|
@@ -590,7 +590,7 @@ struct BVH {
|
|
|
590
590
|
|
|
591
591
|
};
|
|
592
592
|
|
|
593
|
-
`,
|
|
593
|
+
`,Zl=`
|
|
594
594
|
|
|
595
595
|
#define RECT_AREA_LIGHT_TYPE 0
|
|
596
596
|
#define CIRC_AREA_LIGHT_TYPE 1
|
|
@@ -676,7 +676,7 @@ struct BVH {
|
|
|
676
676
|
|
|
677
677
|
}
|
|
678
678
|
|
|
679
|
-
`,
|
|
679
|
+
`,Yl=`
|
|
680
680
|
|
|
681
681
|
struct Material {
|
|
682
682
|
|
|
@@ -883,7 +883,7 @@ struct BVH {
|
|
|
883
883
|
|
|
884
884
|
}
|
|
885
885
|
|
|
886
|
-
`,
|
|
886
|
+
`,Kl=`
|
|
887
887
|
|
|
888
888
|
struct SurfaceRecord {
|
|
889
889
|
|
|
@@ -945,7 +945,7 @@ struct BVH {
|
|
|
945
945
|
vec3 color;
|
|
946
946
|
};
|
|
947
947
|
|
|
948
|
-
`,
|
|
948
|
+
`,Xl=`
|
|
949
949
|
|
|
950
950
|
// samples the the given environment map in the given direction
|
|
951
951
|
vec3 sampleEquirectColor( sampler2D envMap, vec3 direction ) {
|
|
@@ -1012,7 +1012,7 @@ struct BVH {
|
|
|
1012
1012
|
return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
|
|
1013
1013
|
|
|
1014
1014
|
}
|
|
1015
|
-
|
|
1015
|
+
`,$l=`
|
|
1016
1016
|
|
|
1017
1017
|
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
|
|
1018
1018
|
|
|
@@ -1227,7 +1227,7 @@ struct BVH {
|
|
|
1227
1227
|
|
|
1228
1228
|
}
|
|
1229
1229
|
|
|
1230
|
-
`,
|
|
1230
|
+
`,Ql=`
|
|
1231
1231
|
|
|
1232
1232
|
vec3 sampleHemisphere( vec3 n, vec2 uv ) {
|
|
1233
1233
|
|
|
@@ -1312,7 +1312,7 @@ struct BVH {
|
|
|
1312
1312
|
}
|
|
1313
1313
|
|
|
1314
1314
|
|
|
1315
|
-
`,
|
|
1315
|
+
`,Jl=`
|
|
1316
1316
|
|
|
1317
1317
|
bool totalInternalReflection( float cosTheta, float eta ) {
|
|
1318
1318
|
|
|
@@ -1415,7 +1415,7 @@ struct BVH {
|
|
|
1415
1415
|
|
|
1416
1416
|
}
|
|
1417
1417
|
|
|
1418
|
-
`,
|
|
1418
|
+
`,Hl=`
|
|
1419
1419
|
|
|
1420
1420
|
// Fast arccos approximation used to remove banding artifacts caused by numerical errors in acos.
|
|
1421
1421
|
// This is a cubic Lagrange interpolating polynomial for x = [-1, -1/2, 0, 1/2, 1].
|
|
@@ -1495,7 +1495,7 @@ struct BVH {
|
|
|
1495
1495
|
|
|
1496
1496
|
}
|
|
1497
1497
|
|
|
1498
|
-
`,
|
|
1498
|
+
`,eu=`
|
|
1499
1499
|
|
|
1500
1500
|
// Finds the point where the ray intersects the plane defined by u and v and checks if this point
|
|
1501
1501
|
// falls in the bounds of the rectangle on that same plane.
|
|
@@ -1556,7 +1556,7 @@ struct BVH {
|
|
|
1556
1556
|
|
|
1557
1557
|
}
|
|
1558
1558
|
|
|
1559
|
-
`,
|
|
1559
|
+
`,tu=`
|
|
1560
1560
|
|
|
1561
1561
|
// add texel fetch functions for texture arrays
|
|
1562
1562
|
vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
|
|
@@ -1579,7 +1579,7 @@ struct BVH {
|
|
|
1579
1579
|
|
|
1580
1580
|
}
|
|
1581
1581
|
|
|
1582
|
-
`,
|
|
1582
|
+
`,Fs=`
|
|
1583
1583
|
|
|
1584
1584
|
// TODO: possibly this should be renamed something related to material or path tracing logic
|
|
1585
1585
|
|
|
@@ -1694,7 +1694,7 @@ struct BVH {
|
|
|
1694
1694
|
return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
|
|
1695
1695
|
|
|
1696
1696
|
}
|
|
1697
|
-
`,
|
|
1697
|
+
`,Rs=`
|
|
1698
1698
|
|
|
1699
1699
|
// https://www.shadertoy.com/view/wltcRS
|
|
1700
1700
|
uvec4 WHITE_NOISE_SEED;
|
|
@@ -1750,7 +1750,7 @@ struct BVH {
|
|
|
1750
1750
|
return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
|
|
1751
1751
|
|
|
1752
1752
|
}
|
|
1753
|
-
`,
|
|
1753
|
+
`,nu=`
|
|
1754
1754
|
|
|
1755
1755
|
uniform sampler2D stratifiedTexture;
|
|
1756
1756
|
uniform sampler2D stratifiedOffsetTexture;
|
|
@@ -1799,7 +1799,7 @@ struct BVH {
|
|
|
1799
1799
|
|
|
1800
1800
|
}
|
|
1801
1801
|
|
|
1802
|
-
`,
|
|
1802
|
+
`,iu=`
|
|
1803
1803
|
|
|
1804
1804
|
// diffuse
|
|
1805
1805
|
float diffuseEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
|
|
@@ -2237,7 +2237,7 @@ struct BVH {
|
|
|
2237
2237
|
|
|
2238
2238
|
}
|
|
2239
2239
|
|
|
2240
|
-
`,
|
|
2240
|
+
`,ru=`
|
|
2241
2241
|
|
|
2242
2242
|
// returns the hit distance given the material density
|
|
2243
2243
|
float intersectFogVolume( Material material, float u ) {
|
|
@@ -2258,7 +2258,7 @@ struct BVH {
|
|
|
2258
2258
|
|
|
2259
2259
|
}
|
|
2260
2260
|
|
|
2261
|
-
`,
|
|
2261
|
+
`,su=`
|
|
2262
2262
|
|
|
2263
2263
|
// The GGX functions provide sampling and distribution information for normals as output so
|
|
2264
2264
|
// in order to get probability of scatter direction the half vector must be computed and provided.
|
|
@@ -2359,7 +2359,7 @@ struct BVH {
|
|
|
2359
2359
|
|
|
2360
2360
|
}
|
|
2361
2361
|
|
|
2362
|
-
`,
|
|
2362
|
+
`,ou=`
|
|
2363
2363
|
|
|
2364
2364
|
// XYZ to sRGB color space
|
|
2365
2365
|
const mat3 XYZ_TO_REC709 = mat3(
|
|
@@ -2493,7 +2493,7 @@ struct BVH {
|
|
|
2493
2493
|
|
|
2494
2494
|
}
|
|
2495
2495
|
|
|
2496
|
-
`,
|
|
2496
|
+
`,au=`
|
|
2497
2497
|
|
|
2498
2498
|
// See equation (2) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
|
|
2499
2499
|
float velvetD( float cosThetaH, float roughness ) {
|
|
@@ -2590,7 +2590,7 @@ struct BVH {
|
|
|
2590
2590
|
|
|
2591
2591
|
}
|
|
2592
2592
|
|
|
2593
|
-
`,
|
|
2593
|
+
`,cu=`
|
|
2594
2594
|
|
|
2595
2595
|
#ifndef FOG_CHECK_ITERATIONS
|
|
2596
2596
|
#define FOG_CHECK_ITERATIONS 30
|
|
@@ -2651,7 +2651,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
2651
2651
|
|
|
2652
2652
|
}
|
|
2653
2653
|
|
|
2654
|
-
`,
|
|
2654
|
+
`,lu=`
|
|
2655
2655
|
|
|
2656
2656
|
// step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
|
|
2657
2657
|
// returns true if a solid surface was hit
|
|
@@ -2828,7 +2828,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
2828
2828
|
|
|
2829
2829
|
}
|
|
2830
2830
|
|
|
2831
|
-
`,
|
|
2831
|
+
`,uu=`
|
|
2832
2832
|
|
|
2833
2833
|
vec3 ndcToRayOrigin( vec2 coord ) {
|
|
2834
2834
|
|
|
@@ -2911,7 +2911,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
2911
2911
|
|
|
2912
2912
|
}
|
|
2913
2913
|
|
|
2914
|
-
`,
|
|
2914
|
+
`,hu=`
|
|
2915
2915
|
|
|
2916
2916
|
vec3 directLightContribution( vec3 worldWo, SurfaceRecord surf, RenderState state, vec3 rayOrigin ) {
|
|
2917
2917
|
|
|
@@ -3007,7 +3007,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3007
3007
|
|
|
3008
3008
|
}
|
|
3009
3009
|
|
|
3010
|
-
`,
|
|
3010
|
+
`,du=`
|
|
3011
3011
|
|
|
3012
3012
|
#define SKIP_SURFACE 0
|
|
3013
3013
|
#define HIT_SURFACE 1
|
|
@@ -3329,7 +3329,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3329
3329
|
return HIT_SURFACE;
|
|
3330
3330
|
|
|
3331
3331
|
}
|
|
3332
|
-
`,
|
|
3332
|
+
`,fu=`
|
|
3333
3333
|
|
|
3334
3334
|
struct Ray {
|
|
3335
3335
|
|
|
@@ -3378,7 +3378,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3378
3378
|
|
|
3379
3379
|
}
|
|
3380
3380
|
|
|
3381
|
-
`,
|
|
3381
|
+
`,pu=`
|
|
3382
3382
|
|
|
3383
3383
|
#define NO_HIT 0
|
|
3384
3384
|
#define SURFACE_HIT 1
|
|
@@ -3425,7 +3425,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3425
3425
|
|
|
3426
3426
|
}
|
|
3427
3427
|
|
|
3428
|
-
`;class
|
|
3428
|
+
`;class mu extends nr{onBeforeRender(){this.setDefine("FEATURE_DOF",this.physicalCamera.bokehSize===0?0:1),this.setDefine("FEATURE_BACKGROUND_MAP",this.backgroundMap?1:0),this.setDefine("FEATURE_FOG",this.materials.features.isUsed("FOG")?1:0)}constructor(e){super({transparent:!0,depthWrite:!1,defines:{FEATURE_MIS:1,FEATURE_RUSSIAN_ROULETTE:1,FEATURE_DOF:1,FEATURE_BACKGROUND_MAP:0,FEATURE_FOG:1,RANDOM_TYPE:2,CAMERA_TYPE:0,DEBUG_MODE:0,ATTR_NORMAL:0,ATTR_TANGENT:1,ATTR_UV:2,ATTR_COLOR:3},uniforms:{resolution:{value:new h.Vector2},opacity:{value:1},bounces:{value:10},transmissiveBounces:{value:10},filterGlossyFactor:{value:0},physicalCamera:{value:new hl},cameraWorldMatrix:{value:new h.Matrix4},invProjectionMatrix:{value:new h.Matrix4},bvh:{value:new Fc},attributesArray:{value:new Sl},materialIndexAttribute:{value:new ls},materials:{value:new Pl},textures:{value:new Ps().texture},lights:{value:new wl},iesProfiles:{value:new Ps(360,180,{type:h.HalfFloatType,wrapS:h.ClampToEdgeWrapping,wrapT:h.ClampToEdgeWrapping}).texture},environmentIntensity:{value:1},environmentRotation:{value:new h.Matrix4},envMapInfo:{value:new pl},backgroundBlur:{value:0},backgroundMap:{value:null},backgroundAlpha:{value:1},backgroundIntensity:{value:1},backgroundRotation:{value:new h.Matrix4},seed:{value:0},sobolTexture:{value:null},stratifiedTexture:{value:new Bl},stratifiedOffsetTexture:{value:new Wl(64,1)}},vertexShader:`
|
|
3429
3429
|
|
|
3430
3430
|
varying vec2 vUv;
|
|
3431
3431
|
void main() {
|
|
@@ -3449,27 +3449,27 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3449
3449
|
#include <common>
|
|
3450
3450
|
|
|
3451
3451
|
// bvh intersection
|
|
3452
|
-
${
|
|
3453
|
-
${
|
|
3454
|
-
${
|
|
3452
|
+
${Lc}
|
|
3453
|
+
${kc}
|
|
3454
|
+
${Nc}
|
|
3455
3455
|
|
|
3456
3456
|
// uniform structs
|
|
3457
|
-
${
|
|
3458
|
-
${
|
|
3459
|
-
${
|
|
3460
|
-
${
|
|
3461
|
-
${
|
|
3457
|
+
${jl}
|
|
3458
|
+
${Zl}
|
|
3459
|
+
${ql}
|
|
3460
|
+
${Yl}
|
|
3461
|
+
${Kl}
|
|
3462
3462
|
|
|
3463
3463
|
// random
|
|
3464
3464
|
#if RANDOM_TYPE == 2 // Stratified List
|
|
3465
3465
|
|
|
3466
|
-
${
|
|
3466
|
+
${nu}
|
|
3467
3467
|
|
|
3468
3468
|
#elif RANDOM_TYPE == 1 // Sobol
|
|
3469
3469
|
|
|
3470
|
-
${
|
|
3471
|
-
${
|
|
3472
|
-
${
|
|
3470
|
+
${Rs}
|
|
3471
|
+
${ws}
|
|
3472
|
+
${al}
|
|
3473
3473
|
|
|
3474
3474
|
#define rand(v) sobol(v)
|
|
3475
3475
|
#define rand2(v) sobol2(v)
|
|
@@ -3478,7 +3478,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3478
3478
|
|
|
3479
3479
|
#else // PCG
|
|
3480
3480
|
|
|
3481
|
-
${
|
|
3481
|
+
${Rs}
|
|
3482
3482
|
|
|
3483
3483
|
// Using the sobol functions seems to break the the compiler on MacOS
|
|
3484
3484
|
// - specifically the "sobolReverseBits" function.
|
|
@@ -3494,11 +3494,11 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3494
3494
|
#endif
|
|
3495
3495
|
|
|
3496
3496
|
// common
|
|
3497
|
-
${
|
|
3498
|
-
${
|
|
3499
|
-
${
|
|
3500
|
-
${
|
|
3501
|
-
${
|
|
3497
|
+
${tu}
|
|
3498
|
+
${Jl}
|
|
3499
|
+
${Fs}
|
|
3500
|
+
${Hl}
|
|
3501
|
+
${eu}
|
|
3502
3502
|
|
|
3503
3503
|
// environment
|
|
3504
3504
|
uniform EquirectHdrInfo envMapInfo;
|
|
@@ -3554,16 +3554,16 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3554
3554
|
float lightsDenom;
|
|
3555
3555
|
|
|
3556
3556
|
// sampling
|
|
3557
|
-
${
|
|
3558
|
-
${
|
|
3559
|
-
${
|
|
3557
|
+
${Ql}
|
|
3558
|
+
${Xl}
|
|
3559
|
+
${$l}
|
|
3560
3560
|
|
|
3561
|
-
${
|
|
3562
|
-
${
|
|
3563
|
-
${
|
|
3564
|
-
${
|
|
3565
|
-
${
|
|
3566
|
-
${
|
|
3561
|
+
${cu}
|
|
3562
|
+
${su}
|
|
3563
|
+
${au}
|
|
3564
|
+
${ou}
|
|
3565
|
+
${ru}
|
|
3566
|
+
${iu}
|
|
3567
3567
|
|
|
3568
3568
|
float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
|
|
3569
3569
|
|
|
@@ -3595,12 +3595,12 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3595
3595
|
|
|
3596
3596
|
}
|
|
3597
3597
|
|
|
3598
|
-
${
|
|
3599
|
-
${
|
|
3600
|
-
${
|
|
3601
|
-
${
|
|
3602
|
-
${
|
|
3603
|
-
${
|
|
3598
|
+
${fu}
|
|
3599
|
+
${uu}
|
|
3600
|
+
${pu}
|
|
3601
|
+
${lu}
|
|
3602
|
+
${hu}
|
|
3603
|
+
${du}
|
|
3604
3604
|
|
|
3605
3605
|
void main() {
|
|
3606
3606
|
|
|
@@ -3892,7 +3892,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3892
3892
|
|
|
3893
3893
|
}
|
|
3894
3894
|
|
|
3895
|
-
`}),this.setValues(e)}}function*
|
|
3895
|
+
`}),this.setValues(e)}}function*gu(){const{_renderer:r,_fsQuad:e,_blendQuad:t,_primaryTarget:n,_blendTargets:i,_sobolTarget:o,_subframe:s,alpha:a,material:c}=this,d=new h.Vector4,f=new h.Vector4,u=t.material;let[l,g]=i;for(;;){a?(u.opacity=this._opacityFactor/(this.samples+1),c.blending=h.NoBlending,c.opacity=1):(c.opacity=this._opacityFactor/(this.samples+1),c.blending=h.NormalBlending);const[y,b,m,_]=s,x=n.width,w=n.height;c.resolution.set(x*m,w*_),c.sobolTexture=o.texture,c.stratifiedTexture.init(20,c.bounces+c.transmissiveBounces+5),c.stratifiedTexture.next(),c.seed++;const S=this.tiles.x||1,M=this.tiles.y||1,I=S*M,C=Math.ceil(x*m),D=Math.ceil(w*_),L=Math.floor(y*x),R=Math.floor(b*w),N=Math.ceil(C/S),O=Math.ceil(D/M);for(let B=0;B<M;B++)for(let z=0;z<S;z++){const X=r.getRenderTarget(),J=r.autoClear,Me=r.getScissorTest();r.getScissor(d),r.getViewport(f);let Ve=z,Se=B;if(!this.stableTiles){const We=this._currentTile%(S*M);Ve=We%S,Se=~~(We/S),this._currentTile=We+1}const fe=M-Se-1;n.scissor.set(L+Ve*N,R+fe*O,Math.min(N,C-Ve*N),Math.min(O,D-fe*O)),n.viewport.set(L,R,C,D),r.setRenderTarget(n),r.setScissorTest(!0),r.autoClear=!1,e.render(r),r.setViewport(f),r.setScissor(d),r.setScissorTest(Me),r.setRenderTarget(X),r.autoClear=J,a&&(u.target1=l.texture,u.target2=n.texture,r.setRenderTarget(g),t.render(r),r.setRenderTarget(X)),this.samples+=1/I,z===S-1&&B===M-1&&(this.samples=Math.round(this.samples)),yield}[l,g]=[g,l]}}const Os=new h.Color;class Ls{get material(){return this._fsQuad.material}set material(e){this._fsQuad.material.removeEventListener("recompilation",this._compileFunction),e.addEventListener("recompilation",this._compileFunction),this._fsQuad.material=e}get target(){return this._alpha?this._blendTargets[1]:this._primaryTarget}set alpha(e){this._alpha!==e&&(e||(this._blendTargets[0].dispose(),this._blendTargets[1].dispose()),this._alpha=e,this.reset())}get alpha(){return this._alpha}get isCompiling(){return!!this._compilePromise}constructor(e){this.camera=null,this.tiles=new h.Vector2(3,3),this.stableNoise=!1,this.stableTiles=!0,this.samples=0,this._subframe=new h.Vector4(0,0,1,1),this._opacityFactor=1,this._renderer=e,this._alpha=!1,this._fsQuad=new en(new mu),this._blendQuad=new en(new sl),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new ll().generate(e),this._primaryTarget=new h.WebGLRenderTarget(1,1,{format:h.RGBAFormat,type:h.FloatType,magFilter:h.NearestFilter,minFilter:h.NearestFilter}),this._blendTargets=[new h.WebGLRenderTarget(1,1,{format:h.RGBAFormat,type:h.FloatType,magFilter:h.NearestFilter,minFilter:h.NearestFilter}),new h.WebGLRenderTarget(1,1,{format:h.RGBAFormat,type:h.FloatType,magFilter:h.NearestFilter,minFilter:h.NearestFilter})],this._compileFunction=()=>{const t=this.compileMaterial(this._fsQuad._mesh);t.then(()=>{this._compilePromise===t&&(this._compilePromise=null)}),this._compilePromise=t},this.material.addEventListener("recompilation",this._compileFunction)}compileMaterial(){return this._renderer.compileAsync(this._fsQuad._mesh)}setCamera(e){const{material:t}=this;t.cameraWorldMatrix.copy(e.matrixWorld),t.invProjectionMatrix.copy(e.projectionMatrixInverse),t.physicalCamera.updateFrom(e);let n=0;e.projectionMatrix.elements[15]>0&&(n=1),e.isEquirectCamera&&(n=2),t.setDefine("CAMERA_TYPE",n),this.camera=e}setSize(e,t){e=Math.ceil(e),t=Math.ceil(t),!(this._primaryTarget.width===e&&this._primaryTarget.height===t)&&(this._primaryTarget.setSize(e,t),this._blendTargets[0].setSize(e,t),this._blendTargets[1].setSize(e,t),this.reset())}getSize(e){e.x=this._primaryTarget.width,e.y=this._primaryTarget.height}dispose(){this._primaryTarget.dispose(),this._blendTargets[0].dispose(),this._blendTargets[1].dispose(),this._sobolTarget.dispose(),this._fsQuad.dispose(),this._blendQuad.dispose(),this._task=null}reset(){const{_renderer:e,_primaryTarget:t,_blendTargets:n}=this,i=e.getRenderTarget(),o=e.getClearAlpha();e.getClearColor(Os),e.setRenderTarget(t),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(n[0]),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(n[1]),e.setClearColor(0,0),e.clearColor(),e.setClearColor(Os,o),e.setRenderTarget(i),this.samples=0,this._task=null,this.material.stratifiedTexture.stableNoise=this.stableNoise,this.stableNoise&&(this.material.seed=0,this.material.stratifiedTexture.reset())}update(){this.material.onBeforeRender(),!this.isCompiling&&(this._task||(this._task=gu.call(this)),this._task.next())}}const Ut=new h.Vector2,Ns=new h.Vector2,si=new h.Spherical,oi=new h.Color;class yu extends h.DataTexture{constructor(e=512,t=512){super(new Float32Array(e*t*4),e,t,h.RGBAFormat,h.FloatType,h.EquirectangularReflectionMapping,h.RepeatWrapping,h.ClampToEdgeWrapping,h.LinearFilter,h.LinearFilter),this.generationCallback=null}update(){this.dispose(),this.needsUpdate=!0;const{data:e,width:t,height:n}=this.image;for(let i=0;i<t;i++)for(let o=0;o<n;o++){Ns.set(t,n),Ut.set(i/t,o/n),Ut.x-=.5,Ut.y=1-Ut.y,si.theta=Ut.x*2*Math.PI,si.phi=Ut.y*Math.PI,si.radius=1,this.generationCallback(si,Ut,Ns,oi);const a=4*(o*t+i);e[a+0]=oi.r,e[a+1]=oi.g,e[a+2]=oi.b,e[a+3]=1}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}}const ks=new h.Vector3;class vu extends yu{constructor(e=512){super(e,e),this.topColor=new h.Color().set(16777215),this.bottomColor=new h.Color().set(0),this.exponent=2,this.generationCallback=(t,n,i,o)=>{ks.setFromSpherical(t);const s=ks.y*.5+.5;o.lerpColors(this.bottomColor,this.topColor,s**this.exponent)}}copy(e){return super.copy(e),this.topColor.copy(e.topColor),this.bottomColor.copy(e.bottomColor),this}}class xu extends h.ShaderMaterial{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}constructor(e){super({uniforms:{map:{value:null},opacity:{value:1}},vertexShader:`
|
|
3896
3896
|
varying vec2 vUv;
|
|
3897
3897
|
void main() {
|
|
3898
3898
|
|
|
@@ -3949,7 +3949,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3949
3949
|
#include <premultiplied_alpha_fragment>
|
|
3950
3950
|
|
|
3951
3951
|
}
|
|
3952
|
-
`}),this.setValues(e)}}class
|
|
3952
|
+
`}),this.setValues(e)}}class bu extends h.ShaderMaterial{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
|
|
3953
3953
|
varying vec2 vUv;
|
|
3954
3954
|
void main() {
|
|
3955
3955
|
|
|
@@ -3966,7 +3966,7 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3966
3966
|
#include <common>
|
|
3967
3967
|
#include <cube_uv_reflection_fragment>
|
|
3968
3968
|
|
|
3969
|
-
${
|
|
3969
|
+
${Fs}
|
|
3970
3970
|
|
|
3971
3971
|
void main() {
|
|
3972
3972
|
|
|
@@ -3974,13 +3974,13 @@ bool bvhIntersectFogVolumeHit(
|
|
|
3974
3974
|
rayDirection.x *= flipEnvMap;
|
|
3975
3975
|
gl_FragColor = textureCube( envMap, rayDirection );
|
|
3976
3976
|
|
|
3977
|
-
}`}),this.depthWrite=!1,this.depthTest=!1}}class gs{constructor(e){this._renderer=e,this._quad=new Zt(new Xl)}generate(e,t=null,n=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const r=e.images[0],o=this._renderer,i=this._quad;t===null&&(t=4*r.height),n===null&&(n=2*r.height);const a=new h.WebGLRenderTarget(t,n,{type:h.FloatType,colorSpace:r.colorSpace}),c=r.height,f=Math.log2(c)-2,d=1/c,u=1/(3*Math.max(Math.pow(2,f),7*16));i.material.defines.CUBEUV_MAX_MIP=`${f}.0`,i.material.defines.CUBEUV_TEXEL_WIDTH=u,i.material.defines.CUBEUV_TEXEL_HEIGHT=d,i.material.uniforms.envMap.value=e,i.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,i.material.needsUpdate=!0;const l=o.getRenderTarget(),g=o.autoClear;o.autoClear=!0,o.setRenderTarget(a),i.render(o),o.setRenderTarget(l),o.autoClear=g;const y=new Uint16Array(t*n*4),w=new Float32Array(t*n*4);o.readRenderTargetPixels(a,0,0,t,n,w),a.dispose();for(let x=0,b=w.length;x<b;x++)y[x]=h.DataUtils.toHalfFloat(w[x]);const m=new h.DataTexture(y,t,n,h.RGBAFormat,h.HalfFloatType);return m.minFilter=h.LinearMipMapLinearFilter,m.magFilter=h.LinearFilter,m.wrapS=h.RepeatWrapping,m.wrapT=h.RepeatWrapping,m.mapping=h.EquirectangularReflectionMapping,m.needsUpdate=!0,m}dispose(){this._quad.dispose()}}function $l(s){return s.extensions.get("EXT_float_blend")}const Xt=new h.Vector2;class Ql{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new Dc,this._pathTracer=new ds(e),this._queueReset=!1,this._clock=new h.Clock,this._compilePromise=null,this._lowResPathTracer=new ds(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new Zt(new Kl({map:null,transparent:!0,blending:h.NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new h.Vector2(1024,1024),this.rasterizeSceneCallback=(t,n)=>{this._renderer.render(t,n)},this.renderToCanvasCallback=(t,n,r)=>{const o=n.autoClear;n.autoClear=!1,r.render(n),n.autoClear=o},this.setScene(new h.Scene,new h.PerspectiveCamera)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,n={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const r=this._generator;if(r.setObjects(e),this._buildAsync)return r.generateAsync(n.onProgress).then(o=>this._updateFromResults(e,t,o));{const o=r.generate();return this._updateFromResults(e,t,o)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,n=this._materials,r=this.textureSize,o=tl(n);e.textures.setTextures(t,o,r.x,r.y),e.materials.updateFrom(n,o),this.reset()}updateLights(){const e=this.scene,t=this._renderer,n=this._pathTracer.material,r=nl(e),o=el(r);n.lights.updateFrom(r,o),n.iesProfiles.setTextures(t,o),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new Yl(16);const n=this._colorBackground;n.topColor.equals(e.background)||(n.topColor.set(e.background),n.bottomColor.set(e.background),n.update()),t.backgroundMap=n,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const n=new gs(this._renderer).generate(e.background);this._internalBackground=n,t.backgroundMap=n,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environmentIntensity??1,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment)if(e.environment!==null)if(e.environment.isCubeTexture){const n=new gs(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(n)}else t.envMapInfo.updateFrom(e.environment);else t.environmentIntensity=0;this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,n){const{materials:r,geometry:o,bvh:i,bvhChanged:a}=n;this._materials=r;const f=this._pathTracer.material;return a&&(f.bvh.updateFrom(i),f.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),f.materialIndexAttribute.updateFrom(o.attributes.materialIndex)),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),n}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,n=this._renderer,r=this._clock,o=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,o.material.opacity=0,r.start());const i=r.getDelta()*1e3,a=r.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=a&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!$l(n),e.alpha=t.alpha,this.renderToCanvas){const c=this._renderer,f=this.minSamples;if(a>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?o.material.opacity=Math.min(o.material.opacity+i/this.fadeDuration,1):o.material.opacity=1),!this.enablePathTracing||this.samples<f||o.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const d=o.material.opacity;o.material.opacity=1-o.material.opacity,o.material.map=e.target.texture,o.render(c),o.material.opacity=d}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&o.material.opacity>0&&(o.material.opacity<1&&(o.material.blending=this.dynamicLowRes?h.AdditiveBlending:h.NormalBlending),o.material.map=t.target.texture,this.renderToCanvasCallback(t.target,c,o),o.material.blending=h.NoBlending)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._renderQuad.dispose(),this._renderQuad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(Xt);const e=Math.floor(this.renderScale*Xt.x),t=Math.floor(this.renderScale*Xt.y);if(this._pathTracer.getSize(Xt),Xt.x!==e||Xt.y!==t){const n=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*n),Math.floor(t*n))}}}}function vs(s){return typeof s=="object"&&s!==null&&"getInternalRenderer"in s&&typeof s.getInternalRenderer=="function"}let Jl=0;const ys=new Set;class Hl{constructor(){this.pathTracer=null,this.enabled=!1,this.renderer=null,this.sampleCount=0,this.createAttempts=0,this.maxCreateAttempts=10,this.sceneInitialized=!1,this.environmentWaitFrames=0,this.maxEnvironmentWaitFrames=300,this.disposed=!1,this.convertedEnvTexture=null,this.lastResetTime=0,this.pausedFrameBase64=null,this.imageOverlay=null,this.events=new xn,this.instanceId=++Jl,ys.add(this),this.settings={samples:300,bounces:4,transmissiveBounces:2,renderScale:.5,lowResScale:.5,dynamicLowRes:!0,enablePathTracing:!0}}convertToDataTexture(e){if(!e.image||!(e.image instanceof HTMLImageElement))return null;const t=e.image,n=document.createElement("canvas");n.width=t.width,n.height=t.height;const r=n.getContext("2d");if(!r)return null;r.drawImage(t,0,0);const o=r.getImageData(0,0,n.width,n.height),i=new Float32Array(o.data.length);for(let c=0;c<o.data.length;c++)i[c]=o.data[c]/255;const a=new S.DataTexture(i,n.width,n.height,S.RGBAFormat,S.FloatType);return a.mapping=e.mapping,a.wrapS=e.wrapS,a.wrapT=e.wrapT,a.magFilter=e.magFilter,a.minFilter=e.minFilter,a.anisotropy=e.anisotropy,a.needsUpdate=!0,a}async initialize(e){try{return this.renderer=e.renderer,this.enabled=e.enabled,this.isSupported()?W.ok(void 0):W.err(new H("Path tracing is not supported in this environment",te.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return W.err(new H("Failed to initialize path tracing",te.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return W.err(new H("Instance is disposed",te.INVALID_STATE));try{let e=null,t=0;for(;!e&&t<3;){if(st(this.renderer)&&(e=this.renderer.getInternalRenderer()),!e&&t<2)return W.err(new H("Renderer not ready, will retry",te.RENDERER_NOT_INITIALIZED));t++}return e?(this.pathTracer=new Ql(e),this.pathTracer.tiles&&"set"in this.pathTracer.tiles&&this.pathTracer.tiles.set(1,1),this.pathTracer.bounces=this.settings.bounces,this.settings.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=this.settings.transmissiveBounces),this.pathTracer.renderScale=this.settings.renderScale,this.pathTracer.dynamicLowRes=this.settings.dynamicLowRes,this.pathTracer.lowResScale=this.settings.lowResScale,this.pathTracer.environmentIntensity!==void 0&&(this.pathTracer.environmentIntensity=2),e.toneMapping!==S.ACESFilmicToneMapping&&(e.toneMapping=S.ACESFilmicToneMapping,e.toneMappingExposure=1.5),e.autoClear=!1,e.setRenderTarget(null),W.ok(void 0)):W.err(new H("Three.js renderer not available",te.RENDERER_NOT_INITIALIZED))}catch(e){return W.err(new H("Failed to create path tracer",te.PATH_TRACING_INIT_FAILED,{originalError:e}))}}setEnabled(e){if(this.enabled!==e&&(this.enabled=e,!e)){this.reset(),this.sceneInitialized=!1;const t=st(this.renderer)?this.renderer.getInternalRenderer():null;t&&(t.__pathTracingActive=!1,t.autoClear=!0)}}updateSettings(e){this.settings={...this.settings,...e},e.enablePathTracing!==void 0&&this.setEnabled(e.enablePathTracing),this.pathTracer&&(e.bounces!==void 0&&(this.pathTracer.bounces=e.bounces),e.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=e.transmissiveBounces),e.renderScale!==void 0&&(this.pathTracer.renderScale=e.renderScale),e.lowResScale!==void 0&&(this.pathTracer.lowResScale=e.lowResScale),e.dynamicLowRes!==void 0&&(this.pathTracer.dynamicLowRes=e.dynamicLowRes))}async render(e,t){var n,r;if(this.disposed||!this.renderer)return W.ok(void 0);if(!this.enabled){if(this.sampleCount>=this.settings.samples&&this.sampleCount>0)return this.pathTracer&&st(this.renderer)&&this.renderer.getInternalRenderer().setRenderTarget(null),W.ok(void 0);const o=this.renderer.render(e,t);return o.ok,o}if(!this.pathTracer){this.createAttempts++;const o=this.createPathTracer();if(!o.ok){if(this.createAttempts<this.maxCreateAttempts&&((n=o.error)==null?void 0:n.message)==="Renderer not ready, will retry")return this.renderer.render(e,t);{this.enabled=!1,this.createAttempts=0;const i=this.renderer.render(e,t);return i.ok,i}}this.createAttempts=0}try{let o=null,i=null;if(e&&vs(e)&&(o=e.getInternalRenderer()),t&&vs(t)&&(i=t.getInternalRenderer()),!o||!i)return W.err(new H("Could not extract Three.js scene or camera",te.INVALID_PARAMETER));if(!this.sceneInitialized)try{const a=o.__originalEnvironmentTexture;if(!o.environment&&!a)return this.environmentWaitFrames++,this.environmentWaitFrames>=this.maxEnvironmentWaitFrames&&(this.enabled=!1,this.environmentWaitFrames=0),this.renderer.render(e,t);this.environmentWaitFrames=0;let c=null;if(a&&a.mapping===S.EquirectangularReflectionMapping){if(c=a,a.image instanceof HTMLImageElement)if(this.convertedEnvTexture)c=this.convertedEnvTexture;else{const d=this.convertToDataTexture(a);if(d)this.convertedEnvTexture=d,c=d;else throw new Error("Failed to convert environment texture to DataTexture")}const f=o.environment;o.environment=c;try{a.image&&!a.image.data&&a.image instanceof HTMLImageElement&&!a.image.complete&&await new Promise(d=>{a.image.onload=()=>{a.needsUpdate=!0,d()},a.image.onerror=u=>{d()},a.image.complete&&d()}),this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0,o.environment=f}catch(d){throw o.environment=f,d}}else if(((r=o.environment)==null?void 0:r.mapping)===S.EquirectangularReflectionMapping)this.pathTracer&&this.pathTracer.setScene(o,i),this.sceneInitialized=!0;else return this.enabled=!1,this.renderer.render(e,t)}catch(a){return console.warn("Scene initialization error:",a),this.renderer.render(e,t)}if(this.sceneInitialized){if(this.sampleCount===0)try{this.pathTracer&&this.pathTracer.updateLights()}catch(f){console.warn("Failed to update lights for path tracing:",f)}const a=this.renderer.render(e,t);if(!a.ok)return a;const c=st(this.renderer)?this.renderer.getInternalRenderer():null;if(c){const f=c.autoClear,d=c.getRenderTarget();c.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),c.autoClear=f,c.setRenderTarget(d)}else throw new Error("Three.js renderer not available");if(this.sampleCount++,this.sampleCount===this.settings.samples){const f=st(this.renderer)?this.renderer.getInternalRenderer():null;if(f&&this.pathTracer)try{const d=f.autoClear;f.autoClear=!0,f.setRenderTarget(null),f.clear(!0,!0,!0);const u=this.pathTracer.copyQuad;u&&typeof u.render=="function"?u.render(f):(f.autoClear=!1,this.pathTracer.renderSample());const l=f.domElement,g=l.toDataURL("image/png");this.pausedFrameBase64=g,this.createImageOverlay(l,g),f.autoClear=d}catch(d){console.warn("Failed to capture path traced result:",d)}return this.enabled=!1,this.events.emit("pathtracing:paused",{samples:this.sampleCount}),setTimeout(()=>{this.disposePathTracingResources()},100),W.ok(void 0)}}else return this.renderer.render(e,t);return W.ok(void 0)}catch(o){return W.err(new H("Failed to render with path tracing",te.RENDER_FAILED,{originalError:o}))}}getSampleCount(){return this.sampleCount}isEnabled(){return this.enabled}isPathTracerDisposed(){return this.disposed}reset(){const e=performance.now();e-this.lastResetTime<50||(this.lastResetTime=e,this.sampleCount=0,this.pathTracer&&(this.pathTracer.reset(),this.sceneInitialized=!1))}createImageOverlay(e,t){const n=document.createElement("img");n.src=t,n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.style.zIndex="1000",this.imageOverlay=n;const r=e.parentElement;r?(window.getComputedStyle(r).position==="static"&&(r.style.position="relative"),n.onload=()=>{r.appendChild(n),e.style.visibility="hidden"},n.onerror=i=>{console.error("Failed to load path traced image overlay")}):console.warn("Cannot create image overlay: canvas has no parent element")}disposePathTracingResources(){if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer:",e)}this.pathTracer=null}if(this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.renderer){const e=st(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1,e.autoClear=!0)}this.sceneInitialized=!1,this.createAttempts=0}dispose(){if(this.disposed=!0,ys.delete(this),this.imageOverlay&&this.imageOverlay.parentElement&&(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null),this.renderer){const e=st(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1)}if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer during service disposal:",e)}this.pathTracer=null}this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.sampleCount=0,this.sceneInitialized=!1,this.createAttempts=0,this.renderer=null}isSupported(){return document.createElement("canvas").getContext("webgl2")!==null}getPausedFrameBase64(){return this.pausedFrameBase64}hasImageOverlay(){return this.imageOverlay!==null}removeImageOverlay(){if(this.imageOverlay&&this.imageOverlay.parentElement){if(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null,this.renderer){const e=st(this.renderer)?this.renderer.getInternalRenderer():null;e&&e.domElement&&(e.domElement.style.visibility="visible")}this.pausedFrameBase64=null}}}/*!
|
|
3977
|
+
}`}),this.depthWrite=!1,this.depthTest=!1}}class Bs{constructor(e){this._renderer=e,this._quad=new en(new bu)}generate(e,t=null,n=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const i=e.images[0],o=this._renderer,s=this._quad;t===null&&(t=4*i.height),n===null&&(n=2*i.height);const a=new h.WebGLRenderTarget(t,n,{type:h.FloatType,colorSpace:i.colorSpace}),c=i.height,d=Math.log2(c)-2,f=1/c,u=1/(3*Math.max(Math.pow(2,d),7*16));s.material.defines.CUBEUV_MAX_MIP=`${d}.0`,s.material.defines.CUBEUV_TEXEL_WIDTH=u,s.material.defines.CUBEUV_TEXEL_HEIGHT=f,s.material.uniforms.envMap.value=e,s.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,s.material.needsUpdate=!0;const l=o.getRenderTarget(),g=o.autoClear;o.autoClear=!0,o.setRenderTarget(a),s.render(o),o.setRenderTarget(l),o.autoClear=g;const y=new Uint16Array(t*n*4),b=new Float32Array(t*n*4);o.readRenderTargetPixels(a,0,0,t,n,b),a.dispose();for(let _=0,x=b.length;_<x;_++)y[_]=h.DataUtils.toHalfFloat(b[_]);const m=new h.DataTexture(y,t,n,h.RGBAFormat,h.HalfFloatType);return m.minFilter=h.LinearMipMapLinearFilter,m.magFilter=h.LinearFilter,m.wrapS=h.RepeatWrapping,m.wrapT=h.RepeatWrapping,m.mapping=h.EquirectangularReflectionMapping,m.needsUpdate=!0,m}dispose(){this._quad.dispose()}}function wu(r){return r.extensions.get("EXT_float_blend")}const rn=new h.Vector2;class _u{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new tl,this._pathTracer=new Ls(e),this._queueReset=!1,this._clock=new h.Clock,this._compilePromise=null,this._lowResPathTracer=new Ls(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new en(new xu({map:null,transparent:!0,blending:h.NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new h.Vector2(1024,1024),this.rasterizeSceneCallback=(t,n)=>{this._renderer.render(t,n)},this.renderToCanvasCallback=(t,n,i)=>{const o=n.autoClear;n.autoClear=!1,i.render(n),n.autoClear=o},this.setScene(new h.Scene,new h.PerspectiveCamera)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,n={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const i=this._generator;if(i.setObjects(e),this._buildAsync)return i.generateAsync(n.onProgress).then(o=>this._updateFromResults(e,t,o));{const o=i.generate();return this._updateFromResults(e,t,o)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,n=this._materials,i=this.textureSize,o=Al(n);e.textures.setTextures(t,o,i.x,i.y),e.materials.updateFrom(n,o),this.reset()}updateLights(){const e=this.scene,t=this._renderer,n=this._pathTracer.material,i=Il(e),o=Ml(i);n.lights.updateFrom(i,o),n.iesProfiles.setTextures(t,o),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new vu(16);const n=this._colorBackground;n.topColor.equals(e.background)||(n.topColor.set(e.background),n.bottomColor.set(e.background),n.update()),t.backgroundMap=n,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const n=new Bs(this._renderer).generate(e.background);this._internalBackground=n,t.backgroundMap=n,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environmentIntensity??1,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment)if(e.environment!==null)if(e.environment.isCubeTexture){const n=new Bs(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(n)}else t.envMapInfo.updateFrom(e.environment);else t.environmentIntensity=0;this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,n){const{materials:i,geometry:o,bvh:s,bvhChanged:a}=n;this._materials=i;const d=this._pathTracer.material;return a&&(d.bvh.updateFrom(s),d.attributesArray.updateFrom(o.attributes.normal,o.attributes.tangent,o.attributes.uv,o.attributes.color),d.materialIndexAttribute.updateFrom(o.attributes.materialIndex)),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),n}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,n=this._renderer,i=this._clock,o=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,o.material.opacity=0,i.start());const s=i.getDelta()*1e3,a=i.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=a&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!wu(n),e.alpha=t.alpha,this.renderToCanvas){const c=this._renderer,d=this.minSamples;if(a>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?o.material.opacity=Math.min(o.material.opacity+s/this.fadeDuration,1):o.material.opacity=1),!this.enablePathTracing||this.samples<d||o.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const f=o.material.opacity;o.material.opacity=1-o.material.opacity,o.material.map=e.target.texture,o.render(c),o.material.opacity=f}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&o.material.opacity>0&&(o.material.opacity<1&&(o.material.blending=this.dynamicLowRes?h.AdditiveBlending:h.NormalBlending),o.material.map=t.target.texture,this.renderToCanvasCallback(t.target,c,o),o.material.blending=h.NoBlending)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._renderQuad.dispose(),this._renderQuad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(rn);const e=Math.floor(this.renderScale*rn.x),t=Math.floor(this.renderScale*rn.y);if(this._pathTracer.getSize(rn),rn.x!==e||rn.y!==t){const n=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*n),Math.floor(t*n))}}}}function zs(r){return typeof r=="object"&&r!==null&&"getInternalRenderer"in r&&typeof r.getInternalRenderer=="function"}let Su=0;const Us=new Set;class Tu{constructor(){this.pathTracer=null,this.enabled=!1,this.renderer=null,this.sampleCount=0,this.createAttempts=0,this.maxCreateAttempts=10,this.sceneInitialized=!1,this.environmentWaitFrames=0,this.maxEnvironmentWaitFrames=300,this.disposed=!1,this.convertedEnvTexture=null,this.lastResetTime=0,this.pausedFrameBase64=null,this.imageOverlay=null,this.events=new In,this.instanceId=++Su,Us.add(this),this.settings={samples:300,bounces:4,transmissiveBounces:2,renderScale:.5,lowResScale:.5,dynamicLowRes:!0,enablePathTracing:!0}}convertToDataTexture(e){if(!e.image||!(e.image instanceof HTMLImageElement))return null;const t=e.image,n=document.createElement("canvas");n.width=t.width,n.height=t.height;const i=n.getContext("2d");if(!i)return null;i.drawImage(t,0,0);const o=i.getImageData(0,0,n.width,n.height),s=new Float32Array(o.data.length);for(let c=0;c<o.data.length;c++)s[c]=o.data[c]/255;const a=new A.DataTexture(s,n.width,n.height,A.RGBAFormat,A.FloatType);return a.mapping=e.mapping,a.wrapS=e.wrapS,a.wrapT=e.wrapT,a.magFilter=e.magFilter,a.minFilter=e.minFilter,a.anisotropy=e.anisotropy,a.needsUpdate=!0,a}async initialize(e){try{return this.renderer=e.renderer,this.enabled=e.enabled,this.isSupported()?q.ok(void 0):q.err(new H("Path tracing is not supported in this environment",te.PATH_TRACING_INIT_FAILED,{reason:"WebGL2 or required extensions not available"}))}catch(t){return q.err(new H("Failed to initialize path tracing",te.PATH_TRACING_INIT_FAILED,{originalError:t}))}}createPathTracer(){if(this.disposed)return q.err(new H("Instance is disposed",te.INVALID_STATE));try{let e=null,t=0;for(;!e&&t<3;){if(ft(this.renderer)&&(e=this.renderer.getInternalRenderer()),!e&&t<2)return q.err(new H("Renderer not ready, will retry",te.RENDERER_NOT_INITIALIZED));t++}return e?(this.pathTracer=new _u(e),this.pathTracer.tiles&&"set"in this.pathTracer.tiles&&this.pathTracer.tiles.set(1,1),this.pathTracer.bounces=this.settings.bounces,this.settings.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=this.settings.transmissiveBounces),this.pathTracer.renderScale=this.settings.renderScale,this.pathTracer.dynamicLowRes=this.settings.dynamicLowRes,this.pathTracer.lowResScale=this.settings.lowResScale,this.pathTracer.environmentIntensity!==void 0&&(this.pathTracer.environmentIntensity=2),e.toneMapping!==A.ACESFilmicToneMapping&&(e.toneMapping=A.ACESFilmicToneMapping,e.toneMappingExposure=1.5),e.autoClear=!1,e.setRenderTarget(null),q.ok(void 0)):q.err(new H("Three.js renderer not available",te.RENDERER_NOT_INITIALIZED))}catch(e){return q.err(new H("Failed to create path tracer",te.PATH_TRACING_INIT_FAILED,{originalError:e}))}}setEnabled(e){if(this.enabled!==e&&(this.enabled=e,!e)){this.reset(),this.sceneInitialized=!1;const t=ft(this.renderer)?this.renderer.getInternalRenderer():null;t&&(t.__pathTracingActive=!1,t.autoClear=!0)}}updateSettings(e){this.settings={...this.settings,...e},e.enablePathTracing!==void 0&&this.setEnabled(e.enablePathTracing),this.pathTracer&&(e.bounces!==void 0&&(this.pathTracer.bounces=e.bounces),e.transmissiveBounces!==void 0&&(this.pathTracer.transmissiveBounces=e.transmissiveBounces),e.renderScale!==void 0&&(this.pathTracer.renderScale=e.renderScale),e.lowResScale!==void 0&&(this.pathTracer.lowResScale=e.lowResScale),e.dynamicLowRes!==void 0&&(this.pathTracer.dynamicLowRes=e.dynamicLowRes))}async render(e,t){var n,i;if(this.disposed||!this.renderer)return q.ok(void 0);if(!this.enabled){if(this.sampleCount>=this.settings.samples&&this.sampleCount>0)return this.pathTracer&&ft(this.renderer)&&this.renderer.getInternalRenderer().setRenderTarget(null),q.ok(void 0);const o=this.renderer.render(e,t);return o.ok,o}if(!this.pathTracer){this.createAttempts++;const o=this.createPathTracer();if(!o.ok){if(this.createAttempts<this.maxCreateAttempts&&((n=o.error)==null?void 0:n.message)==="Renderer not ready, will retry")return this.renderer.render(e,t);{this.enabled=!1,this.createAttempts=0;const s=this.renderer.render(e,t);return s.ok,s}}this.createAttempts=0}try{let o=null,s=null;if(e&&zs(e)&&(o=e.getInternalRenderer()),t&&zs(t)&&(s=t.getInternalRenderer()),!o||!s)return q.err(new H("Could not extract Three.js scene or camera",te.INVALID_PARAMETER));if(!this.sceneInitialized)try{const a=o.__originalEnvironmentTexture;if(!o.environment&&!a)return this.environmentWaitFrames++,this.environmentWaitFrames>=this.maxEnvironmentWaitFrames&&(this.enabled=!1,this.environmentWaitFrames=0),this.renderer.render(e,t);this.environmentWaitFrames=0;let c=null;if(a&&a.mapping===A.EquirectangularReflectionMapping){if(c=a,a.image instanceof HTMLImageElement)if(this.convertedEnvTexture)c=this.convertedEnvTexture;else{const f=this.convertToDataTexture(a);if(f)this.convertedEnvTexture=f,c=f;else throw new Error("Failed to convert environment texture to DataTexture")}const d=o.environment;o.environment=c;try{const f=a.image;f&&!("data"in f&&f.data)&&f instanceof HTMLImageElement&&!f.complete&&await new Promise(u=>{f.onload=()=>{a.needsUpdate=!0,u()},f.onerror=l=>{u()},f.complete&&u()}),this.pathTracer&&this.pathTracer.setScene(o,s),this.sceneInitialized=!0,o.environment=d}catch(f){throw o.environment=d,f}}else if(((i=o.environment)==null?void 0:i.mapping)===A.EquirectangularReflectionMapping)this.pathTracer&&this.pathTracer.setScene(o,s),this.sceneInitialized=!0;else return this.enabled=!1,this.renderer.render(e,t)}catch(a){return console.warn("Scene initialization error:",a),this.renderer.render(e,t)}if(this.sceneInitialized){if(this.sampleCount===0)try{this.pathTracer&&this.pathTracer.updateLights()}catch(d){console.warn("Failed to update lights for path tracing:",d)}const a=this.renderer.render(e,t);if(!a.ok)return a;const c=ft(this.renderer)?this.renderer.getInternalRenderer():null;if(c){const d=c.autoClear,f=c.getRenderTarget();c.autoClear=!1,this.pathTracer&&this.pathTracer.renderSample(),c.autoClear=d,c.setRenderTarget(f)}else throw new Error("Three.js renderer not available");if(this.sampleCount++,this.sampleCount===this.settings.samples){const d=ft(this.renderer)?this.renderer.getInternalRenderer():null;if(d&&this.pathTracer)try{const f=d.autoClear;d.autoClear=!0,d.setRenderTarget(null),d.clear(!0,!0,!0);const u=this.pathTracer.copyQuad;u&&typeof u.render=="function"?u.render(d):(d.autoClear=!1,this.pathTracer.renderSample());const l=d.domElement,g=l.toDataURL("image/png");this.pausedFrameBase64=g,this.createImageOverlay(l,g),d.autoClear=f}catch(f){console.warn("Failed to capture path traced result:",f)}return this.enabled=!1,this.events.emit("pathtracing:paused",{samples:this.sampleCount}),setTimeout(()=>{this.disposePathTracingResources()},100),q.ok(void 0)}}else return this.renderer.render(e,t);return q.ok(void 0)}catch(o){return q.err(new H("Failed to render with path tracing",te.RENDER_FAILED,{originalError:o}))}}getSampleCount(){return this.sampleCount}isEnabled(){return this.enabled}isPathTracerDisposed(){return this.disposed}reset(){const e=performance.now();e-this.lastResetTime<50||(this.lastResetTime=e,this.sampleCount=0,this.pathTracer&&(this.pathTracer.reset(),this.sceneInitialized=!1))}createImageOverlay(e,t){const n=document.createElement("img");n.src=t,n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.style.zIndex="1000",this.imageOverlay=n;const i=e.parentElement;i?(window.getComputedStyle(i).position==="static"&&(i.style.position="relative"),n.onload=()=>{i.appendChild(n),e.style.visibility="hidden"},n.onerror=s=>{console.error("Failed to load path traced image overlay")}):console.warn("Cannot create image overlay: canvas has no parent element")}disposePathTracingResources(){if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer:",e)}this.pathTracer=null}if(this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.renderer){const e=ft(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1,e.autoClear=!0)}this.sceneInitialized=!1,this.createAttempts=0}dispose(){if(this.disposed=!0,Us.delete(this),this.imageOverlay&&this.imageOverlay.parentElement&&(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null),this.renderer){const e=ft(this.renderer)?this.renderer.getInternalRenderer():null;e&&(e.__pathTracingActive=!1)}if(this.pathTracer){try{this.pathTracer.dispose()}catch(e){console.warn("Failed to dispose path tracer during service disposal:",e)}this.pathTracer=null}this.convertedEnvTexture&&(this.convertedEnvTexture.dispose(),this.convertedEnvTexture=null),this.sampleCount=0,this.sceneInitialized=!1,this.createAttempts=0,this.renderer=null}isSupported(){return document.createElement("canvas").getContext("webgl2")!==null}getPausedFrameBase64(){return this.pausedFrameBase64}hasImageOverlay(){return this.imageOverlay!==null}removeImageOverlay(){if(this.imageOverlay&&this.imageOverlay.parentElement){if(this.imageOverlay.parentElement.removeChild(this.imageOverlay),this.imageOverlay=null,this.renderer){const e=ft(this.renderer)?this.renderer.getInternalRenderer():null;e&&e.domElement&&(e.domElement.style.visibility="visible")}this.pausedFrameBase64=null}}}/*!
|
|
3978
3978
|
fflate - fast JavaScript compression/decompression
|
|
3979
3979
|
<https://101arrowz.github.io/fflate>
|
|
3980
3980
|
Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
|
|
3981
3981
|
version 0.8.2
|
|
3982
|
-
*/var qe=Uint8Array,$t=Uint16Array,eu=Int32Array,xs=new qe([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]),bs=new qe([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]),tu=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ws=function(s,e){for(var t=new $t(31),n=0;n<31;++n)t[n]=e+=1<<s[n-1];for(var r=new eu(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)r[o]=o-t[n]<<5|n;return{b:t,r}},_s=ws(xs,2),Ts=_s.b,nu=_s.r;Ts[28]=258,nu[258]=28;for(var ru=ws(bs,0),iu=ru.b,Yr=new $t(32768),pe=0;pe<32768;++pe){var bt=(pe&43690)>>1|(pe&21845)<<1;bt=(bt&52428)>>2|(bt&13107)<<2,bt=(bt&61680)>>4|(bt&3855)<<4,Yr[pe]=((bt&65280)>>8|(bt&255)<<8)>>1}for(var hn=function(s,e,t){for(var n=s.length,r=0,o=new $t(e);r<n;++r)s[r]&&++o[s[r]-1];var i=new $t(e);for(r=1;r<e;++r)i[r]=i[r-1]+o[r-1]<<1;var a;if(t){a=new $t(1<<e);var c=15-e;for(r=0;r<n;++r)if(s[r])for(var f=r<<4|s[r],d=e-s[r],u=i[s[r]-1]++<<d,l=u|(1<<d)-1;u<=l;++u)a[Yr[u]>>c]=f}else for(a=new $t(n),r=0;r<n;++r)s[r]&&(a[r]=Yr[i[s[r]-1]++]>>15-s[r]);return a},fn=new qe(288),pe=0;pe<144;++pe)fn[pe]=8;for(var pe=144;pe<256;++pe)fn[pe]=9;for(var pe=256;pe<280;++pe)fn[pe]=7;for(var pe=280;pe<288;++pe)fn[pe]=8;for(var Ss=new qe(32),pe=0;pe<32;++pe)Ss[pe]=5;var su=hn(fn,9,1),ou=hn(Ss,5,1),Kr=function(s){for(var e=s[0],t=1;t<s.length;++t)s[t]>e&&(e=s[t]);return e},et=function(s,e,t){var n=e/8|0;return(s[n]|s[n+1]<<8)>>(e&7)&t},Xr=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},au=function(s){return(s+7)/8|0},cu=function(s,e,t){return(t==null||t>s.length)&&(t=s.length),new qe(s.subarray(e,t))},lu=["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"],tt=function(s,e,t){var n=new Error(e||lu[s]);if(n.code=s,Error.captureStackTrace&&Error.captureStackTrace(n,tt),!t)throw n;return n},uu=function(s,e,t,n){var r=s.length,o=0;if(!r||e.f&&!e.l)return t||new qe(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new qe(r*3));var f=function(mn){var er=t.length;if(mn>er){var gn=new qe(Math.max(er*2,mn));gn.set(t),t=gn}},d=e.f||0,u=e.p||0,l=e.b||0,g=e.l,y=e.d,w=e.m,m=e.n,x=r*8;do{if(!g){d=et(s,u,1);var b=et(s,u+1,3);if(u+=3,b)if(b==1)g=su,y=ou,w=9,m=5;else if(b==2){var I=et(s,u,31)+257,P=et(s,u+10,15)+4,D=I+et(s,u+5,31)+1;u+=14;for(var R=new qe(D),O=new qe(19),k=0;k<P;++k)O[tu[k]]=et(s,u+k*3,7);u+=P*3;for(var L=Kr(O),V=(1<<L)-1,G=hn(O,L,1),k=0;k<D;){var Q=G[et(s,u,V)];u+=Q&15;var T=Q>>4;if(T<16)R[k++]=T;else{var J=0,me=0;for(T==16?(me=3+et(s,u,3),u+=2,J=R[k-1]):T==17?(me=3+et(s,u,7),u+=3):T==18&&(me=11+et(s,u,127),u+=7);me--;)R[k++]=J}}var Ce=R.subarray(0,I),ge=R.subarray(I);w=Kr(Ce),m=Kr(ge),g=hn(Ce,w,1),y=hn(ge,m,1)}else tt(1);else{var T=au(u)+4,M=s[T-4]|s[T-3]<<8,A=T+M;if(A>r){c&&tt(0);break}a&&f(l+M),t.set(s.subarray(T,A),l),e.b=l+=M,e.p=u=A*8,e.f=d;continue}if(u>x){c&&tt(0);break}}a&&f(l+131072);for(var ye=(1<<w)-1,nt=(1<<m)-1,we=u;;we=u){var J=g[Xr(s,u)&ye],Te=J>>4;if(u+=J&15,u>x){c&&tt(0);break}if(J||tt(2),Te<256)t[l++]=Te;else if(Te==256){we=u,g=null;break}else{var ut=Te-254;if(Te>264){var k=Te-257,_t=xs[k];ut=et(s,u,(1<<_t)-1)+Ts[k],u+=_t}var ue=y[Xr(s,u)&nt],rt=ue>>4;ue||tt(3),u+=ue&15;var ge=iu[rt];if(rt>3){var _t=bs[rt];ge+=Xr(s,u)&(1<<_t)-1,u+=_t}if(u>x){c&&tt(0);break}a&&f(l+131072);var ht=l+ut;if(l<ge){var Hn=o-ge,ti=Math.min(ge,ht);for(Hn+l<0&&tt(3);l<ti;++l)t[l]=n[Hn+l]}for(;l<ht;++l)t[l]=t[l-ge]}}e.l=g,e.p=we,e.b=l,e.f=d,g&&(d=1,e.m=w,e.d=y,e.n=m)}while(!d);return l!=t.length&&i?cu(t,0,l):t.subarray(0,l)},hu=new qe(0),fu=function(s,e){return((s[0]&15)!=8||s[0]>>4>7||(s[0]<<8|s[1])%31)&&tt(6,"invalid zlib data"),(s[1]>>5&1)==1&&tt(6,"invalid zlib data: "+(s[1]&32?"need":"unexpected")+" dictionary"),(s[1]>>3&4)+2};function Yn(s,e){return uu(s.subarray(fu(s),-4),{i:2},e,e)}var du=typeof TextDecoder<"u"&&new TextDecoder,pu=0;try{du.decode(hu,{stream:!0}),pu=1}catch{}class mu extends h.DataTextureLoader{constructor(e){super(e),this.type=h.HalfFloatType}parse(e){const R=Math.pow(2.7182818,2.2);function O(p,v){let _=0;for(let N=0;N<65536;++N)(N==0||p[N>>3]&1<<(N&7))&&(v[_++]=N);const C=_-1;for(;_<65536;)v[_++]=0;return C}function k(p){for(let v=0;v<16384;v++)p[v]={},p[v].len=0,p[v].lit=0,p[v].p=null}const L={l:0,c:0,lc:0};function V(p,v,_,C,N){for(;_<p;)v=v<<8|Ws(C,N),_+=8;_-=p,L.l=v>>_&(1<<p)-1,L.c=v,L.lc=_}const G=new Array(59);function Q(p){for(let _=0;_<=58;++_)G[_]=0;for(let _=0;_<65537;++_)G[p[_]]+=1;let v=0;for(let _=58;_>0;--_){const C=v+G[_]>>1;G[_]=v,v=C}for(let _=0;_<65537;++_){const C=p[_];C>0&&(p[_]=C|G[C]++<<6)}}function J(p,v,_,C,N,F){const U=v;let j=0,E=0;for(;C<=N;C++){if(U.value-v.value>_)return!1;V(6,j,E,p,U);const B=L.l;if(j=L.c,E=L.lc,F[C]=B,B==63){if(U.value-v.value>_)throw new Error("Something wrong with hufUnpackEncTable");V(8,j,E,p,U);let z=L.l+6;if(j=L.c,E=L.lc,C+z>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;z--;)F[C++]=0;C--}else if(B>=59){let z=B-59+2;if(C+z>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;z--;)F[C++]=0;C--}}Q(F)}function me(p){return p&63}function Ce(p){return p>>6}function ge(p,v,_,C){for(;v<=_;v++){const N=Ce(p[v]),F=me(p[v]);if(N>>F)throw new Error("Invalid table entry");if(F>14){const U=C[N>>F-14];if(U.len)throw new Error("Invalid table entry");if(U.lit++,U.p){const j=U.p;U.p=new Array(U.lit);for(let E=0;E<U.lit-1;++E)U.p[E]=j[E]}else U.p=new Array(1);U.p[U.lit-1]=v}else if(F){let U=0;for(let j=1<<14-F;j>0;j--){const E=C[(N<<14-F)+U];if(E.len||E.p)throw new Error("Invalid table entry");E.len=F,E.lit=v,U++}}}return!0}const ye={c:0,lc:0};function nt(p,v,_,C){p=p<<8|Ws(_,C),v+=8,ye.c=p,ye.lc=v}const we={c:0,lc:0};function Te(p,v,_,C,N,F,U,j,E){if(p==v){C<8&&(nt(_,C,N,F),_=ye.c,C=ye.lc),C-=8;let B=_>>C;if(B=new Uint8Array([B])[0],j.value+B>E)return!1;const z=U[j.value-1];for(;B-- >0;)U[j.value++]=z}else if(j.value<E)U[j.value++]=p;else return!1;we.c=_,we.lc=C}function ut(p){return p&65535}function _t(p){const v=ut(p);return v>32767?v-65536:v}const ue={a:0,b:0};function rt(p,v){const _=_t(p),N=_t(v),F=_+(N&1)+(N>>1),U=F,j=F-N;ue.a=U,ue.b=j}function ht(p,v){const _=ut(p),C=ut(v),N=_-(C>>1)&65535,F=C+N-32768&65535;ue.a=F,ue.b=N}function Hn(p,v,_,C,N,F,U){const j=U<16384,E=_>N?N:_;let B=1,z,q;for(;B<=E;)B<<=1;for(B>>=1,z=B,B>>=1;B>=1;){q=0;const X=q+F*(N-z),Z=F*B,ee=F*z,Y=C*B,$=C*z;let re,he,xe,Ge;for(;q<=X;q+=ee){let ve=q;const oe=q+C*(_-z);for(;ve<=oe;ve+=$){const Ie=ve+Y,Ke=ve+Z,Pe=Ke+Y;j?(rt(p[ve+v],p[Ke+v]),re=ue.a,xe=ue.b,rt(p[Ie+v],p[Pe+v]),he=ue.a,Ge=ue.b,rt(re,he),p[ve+v]=ue.a,p[Ie+v]=ue.b,rt(xe,Ge),p[Ke+v]=ue.a,p[Pe+v]=ue.b):(ht(p[ve+v],p[Ke+v]),re=ue.a,xe=ue.b,ht(p[Ie+v],p[Pe+v]),he=ue.a,Ge=ue.b,ht(re,he),p[ve+v]=ue.a,p[Ie+v]=ue.b,ht(xe,Ge),p[Ke+v]=ue.a,p[Pe+v]=ue.b)}if(_&B){const Ie=ve+Z;j?rt(p[ve+v],p[Ie+v]):ht(p[ve+v],p[Ie+v]),re=ue.a,p[Ie+v]=ue.b,p[ve+v]=re}}if(N&B){let ve=q;const oe=q+C*(_-z);for(;ve<=oe;ve+=$){const Ie=ve+Y;j?rt(p[ve+v],p[Ie+v]):ht(p[ve+v],p[Ie+v]),re=ue.a,p[Ie+v]=ue.b,p[ve+v]=re}}z=B,B>>=1}return q}function ti(p,v,_,C,N,F,U,j,E){let B=0,z=0;const q=U,X=Math.trunc(C.value+(N+7)/8);for(;C.value<X;)for(nt(B,z,_,C),B=ye.c,z=ye.lc;z>=14;){const ee=B>>z-14&16383,Y=v[ee];if(Y.len)z-=Y.len,Te(Y.lit,F,B,z,_,C,j,E,q),B=we.c,z=we.lc;else{if(!Y.p)throw new Error("hufDecode issues");let $;for($=0;$<Y.lit;$++){const re=me(p[Y.p[$]]);for(;z<re&&C.value<X;)nt(B,z,_,C),B=ye.c,z=ye.lc;if(z>=re&&Ce(p[Y.p[$]])==(B>>z-re&(1<<re)-1)){z-=re,Te(Y.p[$],F,B,z,_,C,j,E,q),B=we.c,z=we.lc;break}}if($==Y.lit)throw new Error("hufDecode issues")}}const Z=8-N&7;for(B>>=Z,z-=Z;z>0;){const ee=v[B<<14-z&16383];if(ee.len)z-=ee.len,Te(ee.lit,F,B,z,_,C,j,E,q),B=we.c,z=we.lc;else throw new Error("hufDecode issues")}return!0}function mn(p,v,_,C,N,F){const U={value:0},j=_.value,E=Ye(v,_),B=Ye(v,_);_.value+=4;const z=Ye(v,_);if(_.value+=4,E<0||E>=65537||B<0||B>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const q=new Array(65537),X=new Array(16384);k(X);const Z=C-(_.value-j);if(J(p,_,Z,E,B,q),z>8*(C-(_.value-j)))throw new Error("Something wrong with hufUncompress");ge(q,E,B,X),ti(q,X,p,_,z,B,F,N,U)}function er(p,v,_){for(let C=0;C<_;++C)v[C]=p[v[C]]}function gn(p){for(let v=1;v<p.length;v++){const _=p[v-1]+p[v]-128;p[v]=_}}function Es(p,v){let _=0,C=Math.floor((p.length+1)/2),N=0;const F=p.length-1;for(;!(N>F||(v[N++]=p[_++],N>F));)v[N++]=p[C++]}function Gs(p){let v=p.byteLength;const _=new Array;let C=0;const N=new DataView(p);for(;v>0;){const F=N.getInt8(C++);if(F<0){const U=-F;v-=U+1;for(let j=0;j<U;j++)_.push(N.getUint8(C++))}else{const U=F;v-=2;const j=N.getUint8(C++);for(let E=0;E<U+1;E++)_.push(j)}}return _}function mh(p,v,_,C,N,F){let U=new DataView(F.buffer);const j=_[p.idx[0]].width,E=_[p.idx[0]].height,B=3,z=Math.floor(j/8),q=Math.ceil(j/8),X=Math.ceil(E/8),Z=j-(q-1)*8,ee=E-(X-1)*8,Y={value:0},$=new Array(B),re=new Array(B),he=new Array(B),xe=new Array(B),Ge=new Array(B);for(let oe=0;oe<B;++oe)Ge[oe]=v[p.idx[oe]],$[oe]=oe<1?0:$[oe-1]+q*X,re[oe]=new Float32Array(64),he[oe]=new Uint16Array(64),xe[oe]=new Uint16Array(q*64);for(let oe=0;oe<X;++oe){let Ie=8;oe==X-1&&(Ie=ee);let Ke=8;for(let ae=0;ae<q;++ae){ae==q-1&&(Ke=Z);for(let fe=0;fe<B;++fe)he[fe].fill(0),he[fe][0]=N[$[fe]++],gh(Y,C,he[fe]),vh(he[fe],re[fe]),yh(re[fe]);xh(re);for(let fe=0;fe<B;++fe)bh(re[fe],xe[fe],ae*64)}let Pe=0;for(let ae=0;ae<B;++ae){const fe=_[p.idx[ae]].type;for(let ft=8*oe;ft<8*oe+Ie;++ft){Pe=Ge[ae][ft];for(let yn=0;yn<z;++yn){const it=yn*64+(ft&7)*8;U.setUint16(Pe+0*2*fe,xe[ae][it+0],!0),U.setUint16(Pe+1*2*fe,xe[ae][it+1],!0),U.setUint16(Pe+2*2*fe,xe[ae][it+2],!0),U.setUint16(Pe+3*2*fe,xe[ae][it+3],!0),U.setUint16(Pe+4*2*fe,xe[ae][it+4],!0),U.setUint16(Pe+5*2*fe,xe[ae][it+5],!0),U.setUint16(Pe+6*2*fe,xe[ae][it+6],!0),U.setUint16(Pe+7*2*fe,xe[ae][it+7],!0),Pe+=8*2*fe}}if(z!=q)for(let ft=8*oe;ft<8*oe+Ie;++ft){const yn=Ge[ae][ft]+8*z*2*fe,it=z*64+(ft&7)*8;for(let nr=0;nr<Ke;++nr)U.setUint16(yn+nr*2*fe,xe[ae][it+nr],!0)}}}const ve=new Uint16Array(j);U=new DataView(F.buffer);for(let oe=0;oe<B;++oe){_[p.idx[oe]].decoded=!0;const Ie=_[p.idx[oe]].type;if(_[oe].type==2)for(let Ke=0;Ke<E;++Ke){const Pe=Ge[oe][Ke];for(let ae=0;ae<j;++ae)ve[ae]=U.getUint16(Pe+ae*2*Ie,!0);for(let ae=0;ae<j;++ae)U.setFloat32(Pe+ae*2*Ie,K(ve[ae]),!0)}}}function gh(p,v,_){let C,N=1;for(;N<64;)C=v[p.value],C==65280?N=64:C>>8==255?N+=C&255:(_[N]=C,N++),p.value++}function vh(p,v){v[0]=K(p[0]),v[1]=K(p[1]),v[2]=K(p[5]),v[3]=K(p[6]),v[4]=K(p[14]),v[5]=K(p[15]),v[6]=K(p[27]),v[7]=K(p[28]),v[8]=K(p[2]),v[9]=K(p[4]),v[10]=K(p[7]),v[11]=K(p[13]),v[12]=K(p[16]),v[13]=K(p[26]),v[14]=K(p[29]),v[15]=K(p[42]),v[16]=K(p[3]),v[17]=K(p[8]),v[18]=K(p[12]),v[19]=K(p[17]),v[20]=K(p[25]),v[21]=K(p[30]),v[22]=K(p[41]),v[23]=K(p[43]),v[24]=K(p[9]),v[25]=K(p[11]),v[26]=K(p[18]),v[27]=K(p[24]),v[28]=K(p[31]),v[29]=K(p[40]),v[30]=K(p[44]),v[31]=K(p[53]),v[32]=K(p[10]),v[33]=K(p[19]),v[34]=K(p[23]),v[35]=K(p[32]),v[36]=K(p[39]),v[37]=K(p[45]),v[38]=K(p[52]),v[39]=K(p[54]),v[40]=K(p[20]),v[41]=K(p[22]),v[42]=K(p[33]),v[43]=K(p[38]),v[44]=K(p[46]),v[45]=K(p[51]),v[46]=K(p[55]),v[47]=K(p[60]),v[48]=K(p[21]),v[49]=K(p[34]),v[50]=K(p[37]),v[51]=K(p[47]),v[52]=K(p[50]),v[53]=K(p[56]),v[54]=K(p[59]),v[55]=K(p[61]),v[56]=K(p[35]),v[57]=K(p[36]),v[58]=K(p[48]),v[59]=K(p[49]),v[60]=K(p[57]),v[61]=K(p[58]),v[62]=K(p[62]),v[63]=K(p[63])}function yh(p){const v=.5*Math.cos(.7853975),_=.5*Math.cos(3.14159/16),C=.5*Math.cos(3.14159/8),N=.5*Math.cos(3*3.14159/16),F=.5*Math.cos(5*3.14159/16),U=.5*Math.cos(3*3.14159/8),j=.5*Math.cos(7*3.14159/16),E=new Array(4),B=new Array(4),z=new Array(4),q=new Array(4);for(let X=0;X<8;++X){const Z=X*8;E[0]=C*p[Z+2],E[1]=U*p[Z+2],E[2]=C*p[Z+6],E[3]=U*p[Z+6],B[0]=_*p[Z+1]+N*p[Z+3]+F*p[Z+5]+j*p[Z+7],B[1]=N*p[Z+1]-j*p[Z+3]-_*p[Z+5]-F*p[Z+7],B[2]=F*p[Z+1]-_*p[Z+3]+j*p[Z+5]+N*p[Z+7],B[3]=j*p[Z+1]-F*p[Z+3]+N*p[Z+5]-_*p[Z+7],z[0]=v*(p[Z+0]+p[Z+4]),z[3]=v*(p[Z+0]-p[Z+4]),z[1]=E[0]+E[3],z[2]=E[1]-E[2],q[0]=z[0]+z[1],q[1]=z[3]+z[2],q[2]=z[3]-z[2],q[3]=z[0]-z[1],p[Z+0]=q[0]+B[0],p[Z+1]=q[1]+B[1],p[Z+2]=q[2]+B[2],p[Z+3]=q[3]+B[3],p[Z+4]=q[3]-B[3],p[Z+5]=q[2]-B[2],p[Z+6]=q[1]-B[1],p[Z+7]=q[0]-B[0]}for(let X=0;X<8;++X)E[0]=C*p[16+X],E[1]=U*p[16+X],E[2]=C*p[48+X],E[3]=U*p[48+X],B[0]=_*p[8+X]+N*p[24+X]+F*p[40+X]+j*p[56+X],B[1]=N*p[8+X]-j*p[24+X]-_*p[40+X]-F*p[56+X],B[2]=F*p[8+X]-_*p[24+X]+j*p[40+X]+N*p[56+X],B[3]=j*p[8+X]-F*p[24+X]+N*p[40+X]-_*p[56+X],z[0]=v*(p[X]+p[32+X]),z[3]=v*(p[X]-p[32+X]),z[1]=E[0]+E[3],z[2]=E[1]-E[2],q[0]=z[0]+z[1],q[1]=z[3]+z[2],q[2]=z[3]-z[2],q[3]=z[0]-z[1],p[0+X]=q[0]+B[0],p[8+X]=q[1]+B[1],p[16+X]=q[2]+B[2],p[24+X]=q[3]+B[3],p[32+X]=q[3]-B[3],p[40+X]=q[2]-B[2],p[48+X]=q[1]-B[1],p[56+X]=q[0]-B[0]}function xh(p){for(let v=0;v<64;++v){const _=p[0][v],C=p[1][v],N=p[2][v];p[0][v]=_+1.5747*N,p[1][v]=_-.1873*C-.4682*N,p[2][v]=_+1.8556*C}}function bh(p,v,_){for(let C=0;C<64;++C)v[_+C]=h.DataUtils.toHalfFloat(wh(p[C]))}function wh(p){return p<=1?Math.sign(p)*Math.pow(Math.abs(p),2.2):Math.sign(p)*Math.pow(R,Math.abs(p)-1)}function ni(p){return new DataView(p.array.buffer,p.offset.value,p.size)}function _h(p){const v=p.viewer.buffer.slice(p.offset.value,p.offset.value+p.size),_=new Uint8Array(Gs(v)),C=new Uint8Array(_.length);return gn(_),Es(_,C),new DataView(C.buffer)}function ri(p){const v=p.array.slice(p.offset.value,p.offset.value+p.size),_=Yn(v),C=new Uint8Array(_.length);return gn(_),Es(_,C),new DataView(C.buffer)}function Th(p){const v=p.viewer,_={value:p.offset.value},C=new Uint16Array(p.columns*p.lines*(p.inputChannels.length*p.type)),N=new Uint8Array(8192);let F=0;const U=new Array(p.inputChannels.length);for(let ee=0,Y=p.inputChannels.length;ee<Y;ee++)U[ee]={},U[ee].start=F,U[ee].end=U[ee].start,U[ee].nx=p.columns,U[ee].ny=p.lines,U[ee].size=p.type,F+=U[ee].nx*U[ee].ny*U[ee].size;const j=vn(v,_),E=vn(v,_);if(E>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(j<=E)for(let ee=0;ee<E-j+1;ee++)N[ee+j]=Tt(v,_);const B=new Uint16Array(65536),z=O(N,B),q=Ye(v,_);mn(p.array,v,_,q,C,F);for(let ee=0;ee<p.inputChannels.length;++ee){const Y=U[ee];for(let $=0;$<U[ee].size;++$)Hn(C,Y.start+$,Y.nx,Y.size,Y.ny,Y.nx*Y.size,z)}er(B,C,F);let X=0;const Z=new Uint8Array(C.buffer.byteLength);for(let ee=0;ee<p.lines;ee++)for(let Y=0;Y<p.inputChannels.length;Y++){const $=U[Y],re=$.nx*$.size,he=new Uint8Array(C.buffer,$.end*2,re*2);Z.set(he,X),X+=re*2,$.end+=re}return new DataView(Z.buffer)}function Sh(p){const v=p.array.slice(p.offset.value,p.offset.value+p.size),_=Yn(v),C=p.inputChannels.length*p.lines*p.columns*p.totalBytes,N=new ArrayBuffer(C),F=new DataView(N);let U=0,j=0;const E=new Array(4);for(let B=0;B<p.lines;B++)for(let z=0;z<p.inputChannels.length;z++){let q=0;switch(p.inputChannels[z].pixelType){case 1:E[0]=U,E[1]=E[0]+p.columns,U=E[1]+p.columns;for(let Z=0;Z<p.columns;++Z){const ee=_[E[0]++]<<8|_[E[1]++];q+=ee,F.setUint16(j,q,!0),j+=2}break;case 2:E[0]=U,E[1]=E[0]+p.columns,E[2]=E[1]+p.columns,U=E[2]+p.columns;for(let Z=0;Z<p.columns;++Z){const ee=_[E[0]++]<<24|_[E[1]++]<<16|_[E[2]++]<<8;q+=ee,F.setUint32(j,q,!0),j+=4}break}}return F}function Vs(p){const v=p.viewer,_={value:p.offset.value},C=new Uint8Array(p.columns*p.lines*(p.inputChannels.length*p.type*2)),N={version:Ee(v,_),unknownUncompressedSize:Ee(v,_),unknownCompressedSize:Ee(v,_),acCompressedSize:Ee(v,_),dcCompressedSize:Ee(v,_),rleCompressedSize:Ee(v,_),rleUncompressedSize:Ee(v,_),rleRawSize:Ee(v,_),totalAcUncompressedCount:Ee(v,_),totalDcUncompressedCount:Ee(v,_),acCompression:Ee(v,_)};if(N.version<2)throw new Error("EXRLoader.parse: "+Ft.compression+" version "+N.version+" is unsupported");const F=new Array;let U=vn(v,_)-2;for(;U>0;){const Y=tr(v.buffer,_),$=Tt(v,_),re=$>>2&3,he=($>>4)-1,xe=new Int8Array([he])[0],Ge=Tt(v,_);F.push({name:Y,index:xe,type:Ge,compression:re}),U-=Y.length+3}const j=Ft.channels,E=new Array(p.inputChannels.length);for(let Y=0;Y<p.inputChannels.length;++Y){const $=E[Y]={},re=j[Y];$.name=re.name,$.compression=0,$.decoded=!1,$.type=re.pixelType,$.pLinear=re.pLinear,$.width=p.columns,$.height=p.lines}const B={idx:new Array(3)};for(let Y=0;Y<p.inputChannels.length;++Y){const $=E[Y];for(let re=0;re<F.length;++re){const he=F[re];$.name==he.name&&($.compression=he.compression,he.index>=0&&(B.idx[he.index]=Y),$.offset=Y)}}let z,q,X;if(N.acCompressedSize>0)switch(N.acCompression){case 0:z=new Uint16Array(N.totalAcUncompressedCount),mn(p.array,v,_,N.acCompressedSize,z,N.totalAcUncompressedCount);break;case 1:const Y=p.array.slice(_.value,_.value+N.totalAcUncompressedCount),$=Yn(Y);z=new Uint16Array($.buffer),_.value+=N.totalAcUncompressedCount;break}if(N.dcCompressedSize>0){const Y={array:p.array,offset:_,size:N.dcCompressedSize};q=new Uint16Array(ri(Y).buffer),_.value+=N.dcCompressedSize}if(N.rleRawSize>0){const Y=p.array.slice(_.value,_.value+N.rleCompressedSize),$=Yn(Y);X=Gs($.buffer),_.value+=N.rleCompressedSize}let Z=0;const ee=new Array(E.length);for(let Y=0;Y<ee.length;++Y)ee[Y]=new Array;for(let Y=0;Y<p.lines;++Y)for(let $=0;$<E.length;++$)ee[$].push(Z),Z+=E[$].width*p.type*2;mh(B,ee,E,z,q,C);for(let Y=0;Y<E.length;++Y){const $=E[Y];if(!$.decoded)switch($.compression){case 2:let re=0,he=0;for(let xe=0;xe<p.lines;++xe){let Ge=ee[Y][re];for(let ve=0;ve<$.width;++ve){for(let oe=0;oe<2*$.type;++oe)C[Ge++]=X[he+oe*$.width*$.height];he++}re++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(C.buffer)}function tr(p,v){const _=new Uint8Array(p);let C=0;for(;_[v.value+C]!=0;)C+=1;const N=new TextDecoder().decode(_.slice(v.value,v.value+C));return v.value=v.value+C+1,N}function Mh(p,v,_){const C=new TextDecoder().decode(new Uint8Array(p).slice(v.value,v.value+_));return v.value=v.value+_,C}function Ah(p,v){const _=Ze(p,v),C=Ye(p,v);return[_,C]}function Ih(p,v){const _=Ye(p,v),C=Ye(p,v);return[_,C]}function Ze(p,v){const _=p.getInt32(v.value,!0);return v.value=v.value+4,_}function Ye(p,v){const _=p.getUint32(v.value,!0);return v.value=v.value+4,_}function Ws(p,v){const _=p[v.value];return v.value=v.value+1,_}function Tt(p,v){const _=p.getUint8(v.value);return v.value=v.value+1,_}const Ee=function(p,v){let _;return"getBigInt64"in DataView.prototype?_=Number(p.getBigInt64(v.value,!0)):_=p.getUint32(v.value+4,!0)+Number(p.getUint32(v.value,!0)<<32),v.value+=8,_};function De(p,v){const _=p.getFloat32(v.value,!0);return v.value+=4,_}function Ch(p,v){return h.DataUtils.toHalfFloat(De(p,v))}function K(p){const v=(p&31744)>>10,_=p&1023;return(p>>15?-1:1)*(v?v===31?_?NaN:1/0:Math.pow(2,v-15)*(1+_/1024):6103515625e-14*(_/1024))}function vn(p,v){const _=p.getUint16(v.value,!0);return v.value+=2,_}function Ph(p,v){return K(vn(p,v))}function Dh(p,v,_,C){const N=_.value,F=[];for(;_.value<N+C-1;){const U=tr(v,_),j=Ze(p,_),E=Tt(p,_);_.value+=3;const B=Ze(p,_),z=Ze(p,_);F.push({name:U,pixelType:j,pLinear:E,xSampling:B,ySampling:z})}return _.value+=1,F}function Fh(p,v){const _=De(p,v),C=De(p,v),N=De(p,v),F=De(p,v),U=De(p,v),j=De(p,v),E=De(p,v),B=De(p,v);return{redX:_,redY:C,greenX:N,greenY:F,blueX:U,blueY:j,whiteX:E,whiteY:B}}function Rh(p,v){const _=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],C=Tt(p,v);return _[C]}function Oh(p,v){const _=Ze(p,v),C=Ze(p,v),N=Ze(p,v),F=Ze(p,v);return{xMin:_,yMin:C,xMax:N,yMax:F}}function Lh(p,v){const _=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],C=Tt(p,v);return _[C]}function Nh(p,v){const _=["ENVMAP_LATLONG","ENVMAP_CUBE"],C=Tt(p,v);return _[C]}function kh(p,v){const _=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],C=["ROUND_DOWN","ROUND_UP"],N=Ye(p,v),F=Ye(p,v),U=Tt(p,v);return{xSize:N,ySize:F,levelMode:_[U&15],roundingMode:C[U>>4]}}function zh(p,v){const _=De(p,v),C=De(p,v);return[_,C]}function Bh(p,v){const _=De(p,v),C=De(p,v),N=De(p,v);return[_,C,N]}function Uh(p,v,_,C,N){if(C==="string"||C==="stringvector"||C==="iccProfile")return Mh(v,_,N);if(C==="chlist")return Dh(p,v,_,N);if(C==="chromaticities")return Fh(p,_);if(C==="compression")return Rh(p,_);if(C==="box2i")return Oh(p,_);if(C==="envmap")return Nh(p,_);if(C==="tiledesc")return kh(p,_);if(C==="lineOrder")return Lh(p,_);if(C==="float")return De(p,_);if(C==="v2f")return zh(p,_);if(C==="v3f")return Bh(p,_);if(C==="int")return Ze(p,_);if(C==="rational")return Ah(p,_);if(C==="timecode")return Ih(p,_);if(C==="preview")return _.value+=N,"skipped";_.value+=N}function Eh(p,v){const _=Math.log2(p);return v=="ROUND_DOWN"?Math.floor(_):Math.ceil(_)}function Gh(p,v,_){let C=0;switch(p.levelMode){case"ONE_LEVEL":C=1;break;case"MIPMAP_LEVELS":C=Eh(Math.max(v,_),p.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return C}function js(p,v,_,C){const N=new Array(p);for(let F=0;F<p;F++){const U=1<<F;let j=v/U|0;C=="ROUND_UP"&&j*U<v&&(j+=1);const E=Math.max(j,1);N[F]=(E+_-1)/_|0}return N}function Vh(){const p=this,v=p.offset,_={value:0};for(let C=0;C<p.tileCount;C++){const N=Ze(p.viewer,v),F=Ze(p.viewer,v);v.value+=8,p.size=Ye(p.viewer,v);const U=N*p.blockWidth,j=F*p.blockHeight;p.columns=U+p.blockWidth>p.width?p.width-U:p.blockWidth,p.lines=j+p.blockHeight>p.height?p.height-j:p.blockHeight;const E=p.columns*p.totalBytes,z=p.size<p.lines*E?p.uncompress(p):ni(p);v.value+=p.size;for(let q=0;q<p.lines;q++){const X=q*p.columns*p.totalBytes;for(let Z=0;Z<p.inputChannels.length;Z++){const ee=Ft.channels[Z].name,Y=p.channelByteOffsets[ee]*p.columns,$=p.decodeChannels[ee];if($===void 0)continue;_.value=X+Y;const re=(p.height-(1+j+q))*p.outLineWidth;for(let he=0;he<p.columns;he++){const xe=re+(he+U)*p.outputChannels+$;p.byteArray[xe]=p.getter(z,_)}}}}}function Wh(){const p=this,v=p.offset,_={value:0};for(let C=0;C<p.height/p.blockHeight;C++){const N=Ze(p.viewer,v)-Ft.dataWindow.yMin;p.size=Ye(p.viewer,v),p.lines=N+p.blockHeight>p.height?p.height-N:p.blockHeight;const F=p.columns*p.totalBytes,j=p.size<p.lines*F?p.uncompress(p):ni(p);v.value+=p.size;for(let E=0;E<p.blockHeight;E++){const B=C*p.blockHeight,z=E+p.scanOrder(B);if(z>=p.height)continue;const q=E*F,X=(p.height-1-z)*p.outLineWidth;for(let Z=0;Z<p.inputChannels.length;Z++){const ee=Ft.channels[Z].name,Y=p.channelByteOffsets[ee]*p.columns,$=p.decodeChannels[ee];if($!==void 0){_.value=q+Y;for(let re=0;re<p.columns;re++){const he=X+re*p.outputChannels+$;p.byteArray[he]=p.getter(j,_)}}}}}}function jh(p,v,_){const C={};if(p.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");C.version=p.getUint8(4);const N=p.getUint8(5);C.spec={singleTile:!!(N&2),longName:!!(N&4),deepFormat:!!(N&8),multiPart:!!(N&16)},_.value=8;let F=!0;for(;F;){const U=tr(v,_);if(U==="")F=!1;else{const j=tr(v,_),E=Ye(p,_),B=Uh(p,v,_,j,E);B===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${j}'.`):C[U]=B}}if((N&-7)!=0)throw console.error("THREE.EXRHeader:",C),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return C}function qh(p,v,_,C,N){const F={size:0,viewer:v,array:_,offset:C,width:p.dataWindow.xMax-p.dataWindow.xMin+1,height:p.dataWindow.yMax-p.dataWindow.yMin+1,inputChannels:p.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:h.LinearSRGBColorSpace};switch(p.compression){case"NO_COMPRESSION":F.blockHeight=1,F.uncompress=ni;break;case"RLE_COMPRESSION":F.blockHeight=1,F.uncompress=_h;break;case"ZIPS_COMPRESSION":F.blockHeight=1,F.uncompress=ri;break;case"ZIP_COMPRESSION":F.blockHeight=16,F.uncompress=ri;break;case"PIZ_COMPRESSION":F.blockHeight=32,F.uncompress=Th;break;case"PXR24_COMPRESSION":F.blockHeight=16,F.uncompress=Sh;break;case"DWAA_COMPRESSION":F.blockHeight=32,F.uncompress=Vs;break;case"DWAB_COMPRESSION":F.blockHeight=256,F.uncompress=Vs;break;default:throw new Error("EXRLoader.parse: "+p.compression+" is unsupported")}const U={};for(const z of p.channels)switch(z.name){case"Y":case"R":case"G":case"B":case"A":U[z.name]=!0,F.type=z.pixelType}let j=!1;if(U.R&&U.G&&U.B)j=!U.A,F.outputChannels=4,F.decodeChannels={R:0,G:1,B:2,A:3};else if(U.Y)F.outputChannels=1,F.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(F.type==1)switch(N){case h.FloatType:F.getter=Ph;break;case h.HalfFloatType:F.getter=vn;break}else if(F.type==2)switch(N){case h.FloatType:F.getter=De;break;case h.HalfFloatType:F.getter=Ch}else throw new Error("EXRLoader.parse: unsupported pixelType "+F.type+" for "+p.compression+".");F.columns=F.width;const E=F.width*F.height*F.outputChannels;switch(N){case h.FloatType:F.byteArray=new Float32Array(E),j&&F.byteArray.fill(1,0,E);break;case h.HalfFloatType:F.byteArray=new Uint16Array(E),j&&F.byteArray.fill(15360,0,E);break;default:console.error("THREE.EXRLoader: unsupported type: ",N);break}let B=0;for(const z of p.channels)F.decodeChannels[z.name]!==void 0&&(F.channelByteOffsets[z.name]=B),B+=z.pixelType*2;if(F.totalBytes=B,F.outLineWidth=F.width*F.outputChannels,p.lineOrder==="INCREASING_Y"?F.scanOrder=z=>z:F.scanOrder=z=>F.height-1-z,F.outputChannels==4?(F.format=h.RGBAFormat,F.colorSpace=h.LinearSRGBColorSpace):(F.format=h.RedFormat,F.colorSpace=h.NoColorSpace),p.spec.singleTile){F.blockHeight=p.tiles.ySize,F.blockWidth=p.tiles.xSize;const z=Gh(p.tiles,F.width,F.height),q=js(z,F.width,p.tiles.xSize,p.tiles.roundingMode),X=js(z,F.height,p.tiles.ySize,p.tiles.roundingMode);F.tileCount=q[0]*X[0];for(let Z=0;Z<z;Z++)for(let ee=0;ee<X[Z];ee++)for(let Y=0;Y<q[Z];Y++)Ee(v,C);F.decode=Vh.bind(F)}else{F.blockWidth=F.width;const z=Math.ceil(F.height/F.blockHeight);for(let q=0;q<z;q++)Ee(v,C);F.decode=Wh.bind(F)}return F}const qs={value:0},Zs=new DataView(e),Zh=new Uint8Array(e),Ft=jh(Zs,e,qs),Ht=qh(Ft,Zs,Zh,qs,this.type);return Ht.decode(),{header:Ft,width:Ht.width,height:Ht.height,data:Ht.byteArray,format:Ht.format,colorSpace:Ht.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,n,r){function o(i,a){i.colorSpace=a.colorSpace,i.minFilter=h.LinearFilter,i.magFilter=h.LinearFilter,i.generateMipmaps=!1,i.flipY=!1,t&&t(i,a)}return super.load(e,o,n,r)}}class gu extends h.DataTextureLoader{constructor(e){super(e),this.type=h.HalfFloatType}parse(e){const i=function(D,R){switch(D){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(R||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(R||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(R||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(R||""))}},d=`
|
|
3983
|
-
`,u=function(D,R
|
|
3984
|
-
`;
|
|
3985
|
-
`,
|
|
3986
|
-
`;continue}if((J=Q.match(O))&&(G.gamma=parseFloat(J[1])),(J=Q.match(k))&&(G.exposure=parseFloat(J[1])),(J=Q.match(L))&&(G.valid|=2,G.format=J[1]),(J=Q.match(V))&&(G.valid|=4,G.height=parseInt(J[1],10),G.width=parseInt(J[2],10)),G.valid&2&&G.valid&4)break}return G.valid&2||i(3,"missing format specifier"),G.valid&4||i(3,"missing image size specifier"),G},g=function(D,R,O){const k=R;if(k<8||k>32767||D[0]!==2||D[1]!==2||D[2]&128)return new Uint8Array(D);k!==(D[2]<<8|D[3])&&i(3,"wrong scanline width");const L=new Uint8Array(4*R*O);L.length||i(4,"unable to allocate buffer space");let V=0,G=0;const Q=4*k,J=new Uint8Array(4),me=new Uint8Array(Q);let Ce=O;for(;Ce>0&&G<D.byteLength;){G+4>D.byteLength&&i(1),J[0]=D[G++],J[1]=D[G++],J[2]=D[G++],J[3]=D[G++],(J[0]!=2||J[1]!=2||(J[2]<<8|J[3])!=k)&&i(3,"bad rgbe scanline format");let ge=0,ye;for(;ge<Q&&G<D.byteLength;){ye=D[G++];const we=ye>128;if(we&&(ye-=128),(ye===0||ge+ye>Q)&&i(3,"bad scanline data"),we){const Te=D[G++];for(let ut=0;ut<ye;ut++)me[ge++]=Te}else me.set(D.subarray(G,G+ye),ge),ge+=ye,G+=ye}const nt=k;for(let we=0;we<nt;we++){let Te=0;L[V]=me[we+Te],Te+=k,L[V+1]=me[we+Te],Te+=k,L[V+2]=me[we+Te],Te+=k,L[V+3]=me[we+Te],V+=4}Ce--}return L},y=function(D,R,O,k){const L=D[R+3],V=Math.pow(2,L-128)/255;O[k+0]=D[R+0]*V,O[k+1]=D[R+1]*V,O[k+2]=D[R+2]*V,O[k+3]=1},w=function(D,R,O,k){const L=D[R+3],V=Math.pow(2,L-128)/255;O[k+0]=h.DataUtils.toHalfFloat(Math.min(D[R+0]*V,65504)),O[k+1]=h.DataUtils.toHalfFloat(Math.min(D[R+1]*V,65504)),O[k+2]=h.DataUtils.toHalfFloat(Math.min(D[R+2]*V,65504)),O[k+3]=h.DataUtils.toHalfFloat(1)},m=new Uint8Array(e);m.pos=0;const x=l(m),b=x.width,T=x.height,M=g(m.subarray(m.pos),b,T);let A,I,P;switch(this.type){case h.FloatType:P=M.length/4;const D=new Float32Array(P*4);for(let O=0;O<P;O++)y(M,O*4,D,O*4);A=D,I=h.FloatType;break;case h.HalfFloatType:P=M.length/4;const R=new Uint16Array(P*4);for(let O=0;O<P;O++)w(M,O*4,R,O*4);A=R,I=h.HalfFloatType;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:b,height:T,data:A,header:x.string,gamma:x.gamma,exposure:x.exposure,type:I}}setDataType(e){return this.type=e,this}load(e,t,n,r){function o(i,a){switch(i.type){case h.FloatType:case h.HalfFloatType:i.colorSpace=h.LinearSRGBColorSpace,i.minFilter=h.LinearFilter,i.magFilter=h.LinearFilter,i.generateMipmaps=!1,i.flipY=!0;break}t&&t(i,a)}return super.load(e,o,n,r)}}class vu extends h.Scene{constructor(){super();const e=new h.BoxGeometry;e.deleteAttribute("uv");const t=new h.MeshStandardMaterial({side:h.BackSide}),n=new h.MeshStandardMaterial,r=new h.PointLight(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);const o=new h.Mesh(e,t);o.position.set(-.757,13.219,.717),o.scale.set(31.713,28.305,28.591),this.add(o);const i=new h.InstancedMesh(e,n,6),a=new h.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(),i.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(),i.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(),i.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(),i.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(),i.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(),i.setMatrixAt(5,a.matrix),this.add(i);const c=new h.Mesh(e,Qt(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const f=new h.Mesh(e,Qt(50));f.position.set(-16.109,18.021,-8.207),f.scale.set(.1,2.425,2.751),this.add(f);const d=new h.Mesh(e,Qt(17));d.position.set(14.904,12.198,-1.832),d.scale.set(.15,4.265,6.331),this.add(d);const u=new h.Mesh(e,Qt(43));u.position.set(-.462,8.89,14.52),u.scale.set(4.38,5.441,.088),this.add(u);const l=new h.Mesh(e,Qt(20));l.position.set(3.235,11.486,-12.541),l.scale.set(2.5,2,.1),this.add(l);const g=new h.Mesh(e,Qt(100));g.position.set(0,20,0),g.scale.set(1,.1,1),this.add(g)}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 Qt(s){const e=new h.MeshBasicMaterial;return e.color.setScalar(s),e}class yu{constructor(){this.pmremGenerator=null,this.loadedTextures=new Map}async initialize(e){var t;try{const n=e.renderer;let r=n.renderer||((t=n.getThreeRenderer)==null?void 0:t.call(n));if(!r&&n.getDomElement){const o=n.getDomElement();if(o&&"parentElement"in o&&o.parentElement){const i=o.parentElement.renderer;i instanceof S.WebGLRenderer&&(r=i)}}return r?(this.pmremGenerator=new S.PMREMGenerator(r),this.pmremGenerator.compileEquirectangularShader(),W.ok(void 0)):W.err(new H("Could not access Three.js renderer",te.INITIALIZATION_FAILED))}catch(n){return W.err(new H("Failed to initialize environment service",te.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return W.ok(new Jt(n));const r=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let o;switch(r){case"hdr":o=new gu;break;case"exr":o=new mu;break;case"jpg":case"jpeg":case"png":o=new S.TextureLoader;break;default:return W.err(new H(`Unsupported environment map format: ${r}`,te.UNSUPPORTED_FORMAT,{url:e,extension:r}))}const i=await new Promise((a,c)=>{o.load(e,f=>{a(f)},void 0,f=>c(f))});if(this.pmremGenerator){i.mapping=S.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(i).texture;return this.loadedTextures.set(e,a),this.loadedTextures.set(e+"_original",i),W.ok(new Jt(a))}return this.loadedTextures.set(e,i),W.ok(new Jt(i))}catch(n){return W.err(new H("Failed to load environment map",te.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{if(!(e instanceof St))return W.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));if(!(t instanceof Jt))return W.err(new H("Texture must be ThreeTextureAdapter",te.INVALID_PARAMETER));const r=e.getThreeScene(),o=t.getThreeTexture();if(r.environment=o,n&&(n.backgroundBlurriness!==void 0&&(r.backgroundBlurriness=n.backgroundBlurriness),n.backgroundIntensity!==void 0&&(r.backgroundIntensity=n.backgroundIntensity),n.environmentIntensity!==void 0&&(r.environmentIntensity=n.environmentIntensity)),o.mapping===S.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,f])=>c.endsWith("_original")&&f.mapping===S.EquirectangularReflectionMapping);a&&(r.__originalEnvironmentTexture=a[1])}else o.mapping===S.EquirectangularReflectionMapping&&(r.__originalEnvironmentTexture=o);if(o.mapping===S.EquirectangularReflectionMapping)r.background=o;else if(o.mapping===S.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,f])=>c.endsWith("_original")&&f.mapping===S.EquirectangularReflectionMapping);a?r.background=a[1]:r.background=o}else r.background=o;return W.ok(void 0)}catch(r){return W.err(new H("Failed to apply environment to scene",te.SCENE_OPERATION_FAILED,{originalError:r}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new Jt(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return W.err(new H("Environment service not initialized",te.INITIALIZATION_FAILED));const t=new vu,n=this.pmremGenerator.fromScene(t).texture;return t.dispose(),W.ok(new Jt(n))}catch(t){return W.err(new H("Failed to create studio environment",te.TEXTURE_LOAD_FAILED,{originalError:t}))}}dispose(){this.loadedTextures.forEach(e=>e.dispose()),this.loadedTextures.clear(),this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null)}}class Jt{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 xu{constructor(e){this.object=e,this.boundingBox=new S.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 S.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class bu{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof S.Object3D&&(t=e),t?(new xu(t).alignToFloor(),W.ok(void 0)):W.err(new H("Could not get Three.js object for floor alignment",te.INVALID_PARAMETER))}catch(t){return W.err(new H("Failed to align object to floor",te.OPERATION_FAILED,{originalError:t}))}}}var Kn=(s=>(s.MapControls="MapControls",s.OrbitControls="OrbitControls",s))(Kn||{});class wu{static convertRendererOptions(e){const t={antialias:e.antialias,alpha:e.alpha,premultipliedAlpha:e.premultipliedAlpha,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference,pixelRatio:e.pixelRatio};return(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}),t}static convertShadowMapType(e){if(typeof e=="number"){if(e===S.BasicShadowMap)return"basic";if(e===S.PCFShadowMap)return"pcf";if(e===S.PCFSoftShadowMap)return"pcfsoft";if(e===S.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===S.NoToneMapping)return"none";if(e===S.LinearToneMapping)return"linear";if(e===S.ReinhardToneMapping)return"reinhard";if(e===S.CineonToneMapping)return"cineon";if(e===S.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class _u{static createViewer(e,t){var w;const n=new to(e),r=new St,o=this.createCamera(t),i=this.createControls(o.getThreeCamera(),e,t),a=new Tu().createDefaultLoader(),c=new ia,f=new yu;let d;(((w=t.pathTracing)==null?void 0:w.enabled)??!1)&&(d=new Hl);const l=new bu,g=wu.convertRendererOptions(t.renderer||{}),y={renderer:n,scene:r,camera:o,controls:i,modelLoader:a,options:t,rendererOptions:g,sceneSetupService:c,environmentService:f,pathTracingService:d,floorAlignmentService:l};return new Hs(y)}static createCamera(e){const n=e.camera||{},r=n.fov||n.cameraFov||75,o=n.near||n.cameraNear||.1,i=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,f=or.create(r,1,o,i);return a&&f.position.set(a[0],a[1],a[2]),c&&f.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),f}static createControls(e,t,n){const r=n.controls||{},o=r.type||Kn.OrbitControls;let i;o===Kn.MapControls?i=new bi(e,t):i=new xi(e,t),i.enabled=r.enabled??!0,i.enableDamping=r.enableDamping??!0,i.dampingFactor=r.dampingFactor??.25,i.enableZoom=r.enableZoom??!0,i.enableRotate=r.enableRotate??!0,i.enablePan=r.enablePan??!0,r.minDistance!==void 0&&(i.minDistance=r.minDistance),r.maxDistance!==void 0&&(i.maxDistance=r.maxDistance),r.minPolarAngle!==void 0&&(i.minPolarAngle=r.minPolarAngle),r.maxPolarAngle!==void 0&&(i.maxPolarAngle=r.maxPolarAngle);const c=n.camera||{},f=c.target||c.cameraTarget;return f&&i.target&&(i.target.set(f[0],f[1],f[2]),i.update()),i}}class Tu extends di{createDefaultLoader(){return di.createLoader("model.glb")}}const Ms={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!0,animationLoop:null,pathTracing:{enabled:!1,maxSamples:16,bounces:16,transmissiveBounces:4,renderScale:.8,lowResScale:.25,dynamicLowRes:!0},camera:{position:[60,60,60],target:[0,0,0],fov:45,near:.1,far:1e5,autoFitToObject:!0},environment:{url:"https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/industrial_sunset_puresky.jpg",backgroundBlurriness:.15,backgroundIntensity:1,environmentIntensity:1},lighting:{ambientLight:{color:"#404040",intensity:Math.PI},hemisphereLight:{skyColor:"#ffffbb",groundColor:"#080820",intensity:1},directionalLight:{color:"#ffffff",intensity:Math.PI,position:[72,72,72],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:1}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:window.devicePixelRatio,shadowMapType:2,toneMapping:6,toneMappingExposure:1.5},controls:{type:Kn.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:{type:"hexagonal_wire",size:20,divisions:20,colorGrid:4473924,opacity:.5,styleOptions:{}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}};function Su(s){const e=ne.useRef(s),t=ne.useMemo(()=>JSON.stringify({pathTracing:s.pathTracing,staticScene:s.staticScene,renderer:s.renderer,camera:s.camera,controls:s.controls,backgroundColor:s.backgroundColor,environment:s.environment,lighting:s.lighting,helpers:s.helpers}),[s.pathTracing,s.staticScene,s.renderer,s.camera,s.controls,s.backgroundColor,s.environment,s.lighting,s.helpers]);return ne.useMemo(()=>{e.current=s},[t,s]),e.current}function Mu(s,e){const t=ne.useRef(null),[n,r]=ne.useState(new $e),[o,i]=ne.useState(!1),a=Su(e);ne.useEffect(()=>{if(!s.current||t.current)return;const f={...Ms,...a},d=_u.createViewer(s.current,f);t.current=d;const u=d.onStateChange(l=>{r(l)});return d.initialize().then(l=>{l.ok?i(!0):console.error("Failed to initialize viewer:",l.error)}),()=>{u(),d.dispose(),t.current=null,i(!1)}},[s,a]);const c=ne.useRef({width:0,height:0});return ne.useEffect(()=>{if(!t.current||!s.current)return;let f=null;const d=g=>{if(s.current&&t.current){const y=s.current.parentElement||s.current;let{clientWidth:w,clientHeight:m}=y;if(g&&g[0]){const{width:x,height:b}=g[0].contentRect;w=Math.floor(x),m=Math.floor(b)}if(c.current.width===w&&c.current.height===m)return;f!==null&&cancelAnimationFrame(f),f=requestAnimationFrame(()=>{t.current&&s.current&&(t.current.resize(w,m),c.current={width:w,height:m})})}};d();const u=()=>d();window.addEventListener("resize",u);let l=null;return typeof ResizeObserver<"u"&&s.current.parentElement&&(l=new ResizeObserver(d),l.observe(s.current.parentElement)),()=>{window.removeEventListener("resize",u),l==null||l.disconnect(),f!==null&&cancelAnimationFrame(f)}},[o,s]),{viewer:t.current,state:n,isInitialized:o}}function Au(s,e){const t=ne.useRef(e);t.current=e,ne.useEffect(()=>{if(!s)return;const n=s.getEvents(),r=[];return Object.keys(e).forEach(o=>{if(e[o]){const a=c=>{const f=t.current[o];f&&f(c)};n.on(o,a),r.push(()=>n.off(o,a))}}),()=>{r.forEach(o=>o())}},[s])}const As=ne.createContext(null);function Iu({viewer:s,canvasRef:e,children:t}){return Se.jsx(As.Provider,{value:{viewer:s,canvasRef:e},children:t})}function Cu(){const s=ne.useContext(As);if(!s)throw new Error("useViewerContext must be used within ViewerProvider");return s}function Pu(){const{canvasRef:s}=Cu();return Se.jsx("canvas",{ref:s,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var s=document.createElement("style");s.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(s)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();const Du=(s,e,t,n,r,o)=>{const i=performance.now(),a=()=>{const c=performance.now()-i,f=Math.min(c/r,1);s.position.lerpVectors(t,n,f),e==null||e.update(),o(),f<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},Is={type:"change"},$r={type:"start"},Cs={type:"end"},Xn=new h.Ray,Ps=new h.Plane,Fu=Math.cos(70*h.MathUtils.DEG2RAD),Ae=new h.Vector3,ze=2*Math.PI,le={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Qr=1e-6;class Ds extends h.Controls{constructor(e,t=null){super(e,t),this.state=le.NONE,this.target=new h.Vector3,this.cursor=new h.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:h.MOUSE.ROTATE,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.PAN},this.touches={ONE:h.TOUCH.ROTATE,TWO:h.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 h.Vector3,this._lastQuaternion=new h.Quaternion,this._lastTargetPosition=new h.Vector3,this._quat=new h.Quaternion().setFromUnitVectors(e.up,new h.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new h.Spherical,this._sphericalDelta=new h.Spherical,this._scale=1,this._panOffset=new h.Vector3,this._rotateStart=new h.Vector2,this._rotateEnd=new h.Vector2,this._rotateDelta=new h.Vector2,this._panStart=new h.Vector2,this._panEnd=new h.Vector2,this._panDelta=new h.Vector2,this._dollyStart=new h.Vector2,this._dollyEnd=new h.Vector2,this._dollyDelta=new h.Vector2,this._dollyDirection=new h.Vector3,this._mouse=new h.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Ou.bind(this),this._onPointerDown=Ru.bind(this),this._onPointerUp=Lu.bind(this),this._onContextMenu=Gu.bind(this),this._onMouseWheel=zu.bind(this),this._onKeyDown=Bu.bind(this),this._onTouchStart=Uu.bind(this),this._onTouchMove=Eu.bind(this),this._onMouseDown=Nu.bind(this),this._onMouseMove=ku.bind(this),this._interceptControlDown=Vu.bind(this),this._interceptControlUp=Wu.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(Is),this.update(),this.state=le.NONE}update(e=null){const t=this.object.position;Ae.copy(t).sub(this.target),Ae.applyQuaternion(this._quat),this._spherical.setFromVector3(Ae),this.autoRotate&&this.state===le.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,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=ze:n>Math.PI&&(n-=ze),r<-Math.PI?r+=ze:r>Math.PI&&(r-=ze),n<=r?this._spherical.theta=Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+r)/2?Math.max(n,this._spherical.theta):Math.min(r,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 o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=i!=this._spherical.radius}if(Ae.setFromSpherical(this._spherical),Ae.applyQuaternion(this._quatInverse),t.copy(this.target).add(Ae),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 i=null;if(this.object.isPerspectiveCamera){const a=Ae.length();i=this._clampDistance(a*this._scale);const c=a-i;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new h.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(),o=c!==this.object.zoom;const f=new h.Vector3(this._mouse.x,this._mouse.y,0);f.unproject(this.object),this.object.position.sub(f).add(a),this.object.updateMatrixWorld(),i=Ae.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(Xn.origin.copy(this.object.position),Xn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Xn.direction))<Fu?this.object.lookAt(this.target):(Ps.setFromNormalAndCoplanarPoint(this.object.up,this.target),Xn.intersectPlane(Ps,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>Qr||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Qr||this._lastTargetPosition.distanceToSquared(this.target)>Qr?(this.dispatchEvent(Is),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ze/60*this.autoRotateSpeed*e:ze/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){Ae.setFromMatrixColumn(t,0),Ae.multiplyScalar(-e),this._panOffset.add(Ae)}_panUp(e,t){this.screenSpacePanning===!0?Ae.setFromMatrixColumn(t,1):(Ae.setFromMatrixColumn(t,0),Ae.crossVectors(this.object.up,Ae)),Ae.multiplyScalar(e),this._panOffset.add(Ae)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;Ae.copy(r).sub(this.target);let o=Ae.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/n.clientHeight,this.object.matrix),this._panUp(2*t*o/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(),r=e-n.left,o=t-n.top,i=n.width,a=n.height;this._mouse.x=r/i*2-1,this._mouse.y=-(o/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(ze*this._rotateDelta.x/t.clientHeight),this._rotateUp(ze*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(ze*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(-ze*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(ze*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(-ze*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),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_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),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,o=Math.sqrt(n*n+r*r);this._dollyStart.set(0,o)}_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),r=.5*(e.pageX+n.x),o=.5*(e.pageY+n.y);this._rotateEnd.set(r,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ze*this._rotateDelta.x/t.clientHeight),this._rotateUp(ze*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),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}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,r=e.pageY-t.y,o=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,o),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 i=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(i,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 h.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 Ru(s){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(s.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(s)&&(this._addPointer(s),s.pointerType==="touch"?this._onTouchStart(s):this._onMouseDown(s)))}function Ou(s){this.enabled!==!1&&(s.pointerType==="touch"?this._onTouchMove(s):this._onMouseMove(s))}function Lu(s){switch(this._removePointer(s),this._pointers.length){case 0:this.domElement.releasePointerCapture(s.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Cs),this.state=le.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 Nu(s){let e;switch(s.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 h.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(s),this.state=le.DOLLY;break;case h.MOUSE.ROTATE:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=le.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=le.ROTATE}break;case h.MOUSE.PAN:if(s.ctrlKey||s.metaKey||s.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(s),this.state=le.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(s),this.state=le.PAN}break;default:this.state=le.NONE}this.state!==le.NONE&&this.dispatchEvent($r)}function ku(s){switch(this.state){case le.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(s);break;case le.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(s);break;case le.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(s);break}}function zu(s){this.enabled===!1||this.enableZoom===!1||this.state!==le.NONE||(s.preventDefault(),this.dispatchEvent($r),this._handleMouseWheel(this._customWheelEvent(s)),this.dispatchEvent(Cs))}function Bu(s){this.enabled!==!1&&this._handleKeyDown(s)}function Uu(s){switch(this._trackPointer(s),this._pointers.length){case 1:switch(this.touches.ONE){case h.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(s),this.state=le.TOUCH_ROTATE;break;case h.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(s),this.state=le.TOUCH_PAN;break;default:this.state=le.NONE}break;case 2:switch(this.touches.TWO){case h.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(s),this.state=le.TOUCH_DOLLY_PAN;break;case h.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(s),this.state=le.TOUCH_DOLLY_ROTATE;break;default:this.state=le.NONE}break;default:this.state=le.NONE}this.state!==le.NONE&&this.dispatchEvent($r)}function Eu(s){switch(this._trackPointer(s),this.state){case le.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(s),this.update();break;case le.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(s),this.update();break;case le.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(s),this.update();break;case le.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(s),this.update();break;default:this.state=le.NONE}}function Gu(s){this.enabled!==!1&&s.preventDefault()}function Vu(s){s.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Wu(s){s.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class ju extends Ds{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:h.MOUSE.PAN,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.ROTATE},this.touches={ONE:h.TOUCH.PAN,TWO:h.TOUCH.DOLLY_ROTATE}}}const se={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 wt=(s=>(s.FRONT="FRONT",s.BACK="BACK",s.RIGHT="RIGHT",s.LEFT="LEFT",s.TOP="TOP",s.BOTTOM="BOTTOM",s))(wt||{});new S.Vector3(0,1,0);const dn="rotation-arrows-name",Jr="left-rotation-arrow-name",$n="right-rotation-arrow-name",qu="gizmo-group-name",Zu=[$n,Jr],Qn={GIZMO_DISTANCE:8,DEFAULT_UP:new S.Vector3(0,1,0),FORWARD:new S.Vector3(0,0,-1)},Hr=s=>Qn.FORWARD.clone().applyQuaternion(s),Fs=(s,e,t=new S.Vector3)=>t.clone().add(s.multiplyScalar(-e));class Yu{constructor(e,t=dn){this.gizmoScene=e,this.gizmoArrowsName=t}syncGizmoWithMain(e,t){e.quaternion.copy(t.quaternion),e.up.copy(t.up);const n=Hr(e.quaternion).normalize();e.position.copy(Fs(n,Qn.GIZMO_DISTANCE)),e.camera.updateMatrixWorld(!0);const r=this.gizmoScene.getObjectByName(this.gizmoArrowsName);r&&r.rotation.copy(e.camera.rotation)}syncMainWithGizmo(e,t,n){const r=n.target.clone(),o=e.position.distanceTo(r),i=e.camera instanceof S.PerspectiveCamera;n instanceof ju&&!i?this.syncMapControls(e,t,r,o):this.syncOrbitControls(e,t,r,o),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,r){const o=e.position.y-n.y,i=Hr(t.quaternion);i.y=0,i.normalize();const a=n.clone();a.y+=o,a.add(i.multiplyScalar(-r)),e.position.copy(a),e.up.copy(Qn.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,r){const o=Hr(t.quaternion),i=Qn.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=Fs(o,r,n);e.position.copy(a),e.up.copy(i),e.camera.lookAt(n)}}const Rs=s=>new Yu(s),Os=(s,e,t)=>{Rs(t).syncGizmoWithMain({camera:s,position:s.position,quaternion:s.quaternion,up:s.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up})},Ku=(s,e,t)=>{Rs(e.userData.scene).syncMainWithGizmo({camera:s,position:s.position,quaternion:s.quaternion,up:s.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up},t)},Xu=()=>{try{const s=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(s.getContext("webgl")||s.getContext("experimental-webgl")))}catch{return!1}},$u=()=>Xu()?new S.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),Qu=s=>{const e=new S.AmbientLight(16777215,1);s.add(e);const t=new S.DirectionalLight(16777215,1);t.position.set(5,10,5),s.add(t);const n=new S.DirectionalLight(16777215,1);n.position.set(-5,-10,5),s.add(n);const r=new S.PointLight(16777215,1,100);r.position.set(0,0,5),s.add(r),t.castShadow=!1,n.castShadow=!1,r.castShadow=!1};class Ju{static createTextTexture(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=se.CANVAS_SIZE,t.height=se.CANVAS_SIZE,n&&(n.clearRect(0,0,t.width,t.height),n.font=`${se.FONT_SIZE} Arial`,n.fillStyle=se.TEXT_COLOR,n.textAlign=se.TEXT_ALIGN,n.textBaseline=se.TEXT_BASELINE,n.fillText(e,t.width/2,t.height/2));const r=new S.CanvasTexture(t);return r.needsUpdate=!0,r}}class Jn{static createWireframe([e,t,n]){const r=new S.BoxGeometry(e,t,n),o=new S.EdgesGeometry(r),i=new S.LineBasicMaterial({color:se.LINE_COLOR}),a=new S.LineSegments(o,i);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const r=se.CUBE_SIZE-se.EDGE_SECTION_SIZE,o={x:se.EDGE_SECTION_SIZE,y:se.EDGE_SECTION_SIZE,z:se.EDGE_SECTION_SIZE};o[t]=r;const i=new S.BoxGeometry(o.x,o.y,o.z),a=new S.MeshStandardMaterial({color:se.EDGE_COLOR}),c=new S.Mesh(i,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new S.BoxGeometry(se.EDGE_SECTION_SIZE,se.EDGE_SECTION_SIZE,se.EDGE_SECTION_SIZE),r=new S.MeshStandardMaterial({color:se.CORNER_COLOR}),o=new S.Mesh(n,r);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,n){const r=new S.Group,o=new S.BoxGeometry(se.CUBE_SIZE-se.EDGE_SECTION_SIZE,se.CUBE_SIZE-se.EDGE_SECTION_SIZE,se.FACE_THICKNESS),i=new S.MeshStandardMaterial({color:se.FACE_COLOR}),a=new S.Mesh(o,i);a.name=`Face Box ${n}`,r.add(a);const c=new S.PlaneGeometry(se.CUBE_SIZE-se.EDGE_SECTION_SIZE,se.CUBE_SIZE-se.EDGE_SECTION_SIZE),f=new S.MeshStandardMaterial({map:Ju.createTextTexture(n),transparent:!0,depthWrite:!1}),d=new S.Mesh(c,f);return d.position.set(0,0,se.FACE_THICKNESS/2+.01),r.add(d),r.position.copy(e),r.rotation.copy(t),r}}const Hu=(s,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(s,t.width/2,t.height/2);const r=new S.CanvasTexture(t),o=new S.SpriteMaterial({map:r}),i=new S.Sprite(o);return i.scale.set(.5,.5,.5),i};class eh{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 wt.BACK:return new S.Euler(0,Math.PI,0);case wt.RIGHT:return new S.Euler(0,-Math.PI/2,0);case wt.LEFT:return new S.Euler(0,Math.PI/2,0);case wt.TOP:return new S.Euler(Math.PI/2,0,0);case wt.BOTTOM:return new S.Euler(-Math.PI/2,0,0);case wt.FRONT:default:return new S.Euler(0,0,0)}}createWireframe(){const e=se.CUBE_SIZE+se.EDGE_SECTION_SIZE,t=Jn.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,n){const r=Jn.createEdgeBox(e,t,n);return r.userData.gizmoCube=this,r}createCornerCube(e,t){const n=Jn.createCornerCube(e,t);return n.userData.gizmoCube=this,n}createFace(e,t,n){const r=Jn.createFace(e,t,n),o=r.getObjectByName(`Face Box ${n}`);return o.userData.gizmoCube=this,r}createEdges(e){const t=se.CUBE_SIZE/2;[{axis:"x",pos:new S.Vector3(0,t,-t)},{axis:"x",pos:new S.Vector3(0,t,t)},{axis:"x",pos:new S.Vector3(0,-t,-t)},{axis:"x",pos:new S.Vector3(0,-t,t)},{axis:"y",pos:new S.Vector3(t,0,-t)},{axis:"y",pos:new S.Vector3(t,0,t)},{axis:"y",pos:new S.Vector3(-t,0,-t)},{axis:"y",pos:new S.Vector3(-t,0,t)},{axis:"z",pos:new S.Vector3(t,t,0)},{axis:"z",pos:new S.Vector3(t,-t,0)},{axis:"z",pos:new S.Vector3(-t,t,0)},{axis:"z",pos:new S.Vector3(-t,-t,0)}].forEach(({axis:n,pos:r},o)=>{const i=this.createEdgeBox(r,n,o+1);e.add(i)})}createCorners(e){const t=se.CUBE_SIZE/2;[new S.Vector3(-t,-t,-t),new S.Vector3(-t,-t,t),new S.Vector3(-t,t,-t),new S.Vector3(-t,t,t),new S.Vector3(t,-t,-t),new S.Vector3(t,-t,t),new S.Vector3(t,t,-t),new S.Vector3(t,t,t)].forEach((n,r)=>{const o=this.createCornerCube(n,r+1);e.add(o)})}createFaces(e){const t=se.CUBE_SIZE/2;[{pos:new S.Vector3(0,0,t),rotation:new S.Euler(0,0,0),label:"FRONT"},{pos:new S.Vector3(0,0,-t),rotation:new S.Euler(0,Math.PI,0),label:"BACK"},{pos:new S.Vector3(t,0,0),rotation:new S.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new S.Vector3(-t,0,0),rotation:new S.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new S.Vector3(0,t,0),rotation:new S.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new S.Vector3(0,-t,0),rotation:new S.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:r,label:o})=>{const i=this.createFace(n,r,o);e.add(i)})}createAxis(e){const{color:t,direction:n,length:r,origin:o,lineWidth:i,label:a}=e,c=new S.Group,f=i/2,d=new S.CylinderGeometry(f,f,r,32),u=new S.MeshBasicMaterial({color:t}),l=new S.Mesh(d,u);if(l.position.copy(o).add(n.clone().multiplyScalar(r/2)),!n.equals(new S.Vector3(0,1,0))){const y=new S.Vector3(0,1,0).cross(n).normalize(),w=Math.acos(new S.Vector3(0,1,0).dot(n));l.setRotationFromAxisAngle(y,w)}c.add(l);const g=Hu(a,t);return g.position.copy(o).add(n.clone().multiplyScalar(r+.1)),c.add(g),c}createCoordinateAxes(){const e=new S.Group,t=se.CUBE_SIZE,n=se.EDGE_SECTION_SIZE,r=-1.075,o=a=>{const c=new S.Vector3(1,1,1);return new S.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},i=t+1.25*n;return[{color:16711680,direction:new S.Vector3(1,0,0),length:i,origin:o(r),lineWidth:.04,label:"X"},{color:65280,direction:new S.Vector3(0,1,0),length:i,origin:o(r),lineWidth:.04,label:"Y"},{color:255,direction:new S.Vector3(0,0,1),length:i,origin:o(r),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new S.Group;e.name=qu;const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const n=this.createCoordinateAxes();e.add(n);const r=this.getInitialRotation();return e.setRotationFromEuler(r),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof S.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 S.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new S.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class th{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:r,options:o}=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=r,this.options=o,this.gizmoControls=new Ds(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 eh({initialFace:((e=this.options)==null?void 0:e.initialFace)??wt.FRONT}).create();this.gizmoScene.add(t),Qu(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(dn);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 nh=(s,e)=>{let t;return function(...n){t||(s.apply(this,n),t=!0,setTimeout(()=>t=!1,e))}};function Ls(s,e,t){if(!e)return;const n=e.domElement.getBoundingClientRect();t.x=(s.clientX-n.left)/n.width*2-1,t.y=-((s.clientY-n.top)/n.height)*2+1}const Ns=(s,e,t,n)=>(n.setFromCamera(s,e),n.intersectObjects(t.children,!0)),ks=s=>{var e;const t=["Wireframe",""];return((e=s.find(n=>!t.includes(n.object.name)))==null?void 0:e.object)||null};function rh(s,e,t,n){if(!e||!t)return null;const r=Ns(s,e,t,n);return ks(r)}function ih(s,e){const t=s==null?void 0:s.userData.gizmoCube;if(s&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const sh={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},oh={size:.2,depth:.1,heightRatio:1.4,segments:1};class ah{constructor(e={}){this.config={...sh,...e},this.material=new S.MeshBasicMaterial({color:this.config.color})}create(){const e=new S.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=dn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new S.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new S.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},(r,o)=>{const i=o/this.config.numPoints,a=n+t*i,c=this.config.radius*Math.sin(a),f=this.config.radius*Math.cos(a);return new S.Vector3(c,f,0)})}createTubes([e,t]){const n=(r,o)=>{const i=new S.TubeGeometry(r,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new S.Mesh(i,this.material);return a.name=o,a};return[n(e,Jr),n(t,$n)]}createArrowHeads([e,t]){const{size:n,depth:r,heightRatio:o,segments:i}=oh,a=this.createArrowShape(n,o),c=new S.ExtrudeGeometry(a,{steps:i,depth:r,bevelEnabled:!1}).center(),f=(d,u,l)=>{const g=new S.Mesh(c,this.material);return g.position.copy(d),g.rotation.z=u,g.name=l,g};return[f(e.getPoint(0),this.calculateArrowRotation(e.getTangent(0))+Math.PI/2,Jr),f(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,$n)]}createArrowShape(e,t){return new S.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 ch=s=>{const e=s.rotation,t=.01,n=Math.PI,r=(Math.abs(e.x)%(2*n)+2*n)%(2*n),o=(Math.abs(e.y)%(2*n)+2*n)%(2*n),i=Math.abs(r-n/2)<t||Math.abs(r-3*n/2)<t||Math.abs(o-n/2)<t||Math.abs(o-3*n/2)<t,a=(Math.abs(r)<t||Math.abs(r-n)<t)&&(Math.abs(o)<t||Math.abs(o-n)<t);return!(i||a)},lh=25,uh=200;function hh({gizmoRenderer:s,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:r}){const o=ne.useRef(null),i=ne.useRef(null),a=ne.useRef(new S.Raycaster).current,c=ne.useRef(new S.Vector2).current,f=ne.useCallback(()=>{const w=e.getObjectByName(dn),m=ch(t);if(w&&m){e.remove(w);return}if(w||m)return;const x=new ah().create();x.rotation.copy(t.rotation),e.add(x)},[e,t]),d=ne.useCallback(()=>{const w=e.getObjectByName(dn);w&&e.remove(w)},[e]),u=ne.useCallback(nh(w=>{if(!r.current||!s)return;Ls(w,s,c);const m=Ns(c,t,e,a),x=ks(m);x!=null&&x.userData.gizmoCube?x.userData.gizmoCube.highlightObject(x):e.traverse(b=>{b.userData.gizmoCube&&b.userData.gizmoCube.highlightObject(null)}),m.length>0?f():d()},1e3/lh),[r,s,t,e,a,c,f,d]),l=ne.useCallback(w=>{o.current=Date.now(),i.current={x:w.clientX,y:w.clientY}},[]),g=ne.useCallback(w=>{var m;const x=w.name===$n?1:-1,b=90*Math.PI/180,T=new S.Vector3(0,0,0),M=x*b,A=new S.Matrix4;A.makeRotationZ(M),t.up.applyMatrix4(A),t.lookAt(T),(m=r.current)==null||m.gizmoControls.update()},[t,r]),y=ne.useCallback(w=>{if((o.current?Date.now()-o.current:0)<uh){Ls(w,s,c);const m=rh(c,t,e,a);m!=null&&m.name&&Zu.includes(m.name)?g(m):ih(m,n)}o.current=null,i.current=null},[g,n,s,t,e,a,c]);return{onMouseDown:l,onMouseMove:u,onMouseUp:y,onMouseLeave:d}}const fh=({camera:s,controls:e,className:t,render:n,options:r})=>{const o=ne.useRef(null),i=ne.useRef(new S.Scene).current,[a]=ne.useState(()=>$u()),c=30,f=1,d=.1,u=10,l=new S.PerspectiveCamera(c,f,d,u),g=ne.useRef(l).current,y=ne.useRef(null),w=ne.useCallback(()=>{a&&(n(),a.render(i,g))},[n,a,i,g]),m=ne.useCallback(A=>{if(!s||!e)return;const I=s.position.length(),P=A.clone().multiplyScalar(I),D=400,R=new S.Matrix4;R.lookAt(P,new S.Vector3(0,0,0),new S.Vector3(0,1,0));const O=new S.Quaternion;O.setFromRotationMatrix(R),s.quaternion.copy(O),Du(s,e,s.position.clone(),P,D,w),s.up.set(0,1,0),s.lookAt(new S.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[s,e,w,i]),{onMouseDown:x,onMouseMove:b,onMouseUp:T,onMouseLeave:M}=hh({gizmoRenderer:a,gizmoScene:i,gizmoCamera:g,alignCameraWithVector:m,gizmoControlRef:y});return ne.useEffect(()=>{const A=o.current;if(!A||!s||!e||!a)return;y.current&&y.current.dispose();const I={gizmoDiv:A,gizmoScene:i,gizmoRenderer:a,gizmoCamera:g},P={mainCamera:s,mainControls:e,renderGizmo:w},D={syncGizmoCameraWithMain:Os,syncMainCameraWithGizmo:Ku};return y.current=new th({gizmoParams:I,mainParams:P,syncFunctions:D,options:r}),A.addEventListener("mousedown",x),A.addEventListener("mousemove",b),A.addEventListener("mouseup",T),A.addEventListener("mouseleave",M),()=>{y.current&&(y.current.dispose(),y.current=null),A.removeEventListener("mousedown",x),A.removeEventListener("mousemove",b),A.removeEventListener("mouseup",T),A.removeEventListener("mouseleave",M)}},[s,e,w,b,x,T]),ne.useEffect(()=>{s&&(Os(g,s,i),w())},[s,w]),Se.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},dh=({camera:s,controls:e,render:t,placement:n="top-right",size:r=128})=>{const o=ne.useRef(null);if(ne.useEffect(()=>{if(!o.current)return;const a=o.current;a.style.position="absolute",a.style.width=`${r}px`,a.style.height=`${r}px`,a.style.zIndex="1000",a.style.top="auto",a.style.bottom="auto",a.style.left="auto",a.style.right="auto";const c="10px";switch(n){case"top-left":a.style.top=c,a.style.left=c;break;case"top-right":a.style.top=c,a.style.right=c;break;case"bottom-left":a.style.bottom=c,a.style.left=c;break;case"bottom-right":a.style.bottom=c,a.style.right=c;break}},[n,r]),!s||!e)return null;const i=e;return Se.jsx("div",{ref:o,className:"viewer-gizmo-container",children:Se.jsx(fh,{camera:s,controls:i,render:t})})};class ph extends ne.Component{constructor(e){super(e),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:Se.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:Se.jsxs("div",{children:[Se.jsx("h3",{children:"Error Loading 3D Viewer"}),Se.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"})]})}):this.props.children}}class zs{static toThreeObject(e){if("getThreeObject"in e&&typeof e.getThreeObject=="function")return e.getThreeObject();if(e instanceof S.Object3D)return e;const t=new S.Object3D;return t.position.set(e.position.x,e.position.y,e.position.z),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.scale.set(e.scale.x,e.scale.y,e.scale.z),t}static toThreeCamera(e){return"getThreeCamera"in e&&typeof e.getThreeCamera=="function"?e.getThreeCamera():e instanceof S.Camera?e:new S.PerspectiveCamera}static toThreeControls(e){return"getThreeControls"in e&&typeof e.getThreeControls=="function"?e.getThreeControls():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)}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}const Bs=ne.forwardRef(({object:s,options:e={}},t)=>{var M,A;const n=ne.useRef(null),{viewer:r,isInitialized:o}=Mu(n,e),i=ne.useRef(new xn),a=ne.useRef(void 0),c=ne.useMemo(()=>{if(typeof s=="string")return s;if(s)return`object-${s.uuid||"no-uuid"}`},[s]);ne.useMemo(()=>{a.current=s},[c,s]),ne.useEffect(()=>{if(!r||!o||!a.current)return;const I=typeof a.current=="string"?a.current:new Fe(a.current);r.loadModel(I).then(P=>{P.ok||console.error("Failed to load model:",P.error)})},[r,o,c]);const f=ne.useMemo(()=>({"model:loaded":I=>i.current.emit("model:loaded",zs.convertModelLoaded(I)),"model:error":I=>i.current.emit("model:error",I),"render:complete":I=>i.current.emit("render:complete",I),"controls:change":I=>i.current.emit("controls:change",zs.convertControlsChange(I)),error:I=>i.current.emit("error",I)}),[]);Au(r,f);const d=ne.useCallback(I=>{if(I&&typeof I=="object"){const P=I;if(typeof P.getThreeScene=="function")return P.getThreeScene()}return null},[]),u=ne.useCallback(I=>{if(I&&typeof I=="object"){const P=I;if(typeof P.getThreeCamera=="function")return P.getThreeCamera()}return null},[]),l=ne.useCallback(I=>{if(I&&typeof I=="object"){const P=I;if(typeof P.getThreeRenderer=="function")return P.getThreeRenderer()}return null},[]),g=ne.useCallback(I=>{if(I&&typeof I=="object"){const P=I;if(typeof P.getThreeControls=="function")return P.getThreeControls()}return null},[]),y=r?u(r.camera):null,w=r?g(r.controls):null,m=r?l(r.renderer):null,x=ne.useCallback(()=>{if(m&&r){const I=r;I.renderLoopManager&&typeof I.renderLoopManager.requestRender=="function"&&I.renderLoopManager.requestRender()}},[r,m]),b=((M=e.helpers)==null?void 0:M.gizmo)!==void 0&&e.helpers.gizmo!==!1,T=typeof((A=e.helpers)==null?void 0:A.gizmo)=="object"?e.helpers.gizmo:{};return ne.useImperativeHandle(t,()=>({scene:r?d(r.scene):null,camera:y,renderer:m,controls:w,events:i.current}),[r,y,m,w,d]),Se.jsx(ph,{children:Se.jsx(Iu,{viewer:r,canvasRef:n,children:Se.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Se.jsx(Pu,{}),b&&o&&y&&w&&Se.jsx(dh,{camera:y,controls:w,render:x,placement:T.placement,size:T.size})]})})})});Bs.displayName="SimpleViewer";const Us=ne.forwardRef((s,e)=>Se.jsx(Bs,{ref:e,...s}));Us.displayName="SimpleViewer",Xe.SimpleViewer=Us,Xe.TypedEventEmitter=xn,Xe.defaultOptions=Ms,Object.defineProperty(Xe,Symbol.toStringTag,{value:"Module"})});
|
|
3982
|
+
*/var Je=Uint8Array,sn=Uint16Array,Mu=Int32Array,Es=new Je([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]),Gs=new Je([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]),Au=new Je([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Vs=function(r,e){for(var t=new sn(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new Mu(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)i[o]=o-t[n]<<5|n;return{b:t,r:i}},Ws=Vs(Es,2),js=Ws.b,Iu=Ws.r;js[28]=258,Iu[258]=28;for(var Cu=Vs(Gs,0),Pu=Cu.b,ar=new sn(32768),ve=0;ve<32768;++ve){var Mt=(ve&43690)>>1|(ve&21845)<<1;Mt=(Mt&52428)>>2|(Mt&13107)<<2,Mt=(Mt&61680)>>4|(Mt&3855)<<4,ar[ve]=((Mt&65280)>>8|(Mt&255)<<8)>>1}for(var xn=function(r,e,t){for(var n=r.length,i=0,o=new sn(e);i<n;++i)r[i]&&++o[r[i]-1];var s=new sn(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;var a;if(t){a=new sn(1<<e);var c=15-e;for(i=0;i<n;++i)if(r[i])for(var d=i<<4|r[i],f=e-r[i],u=s[r[i]-1]++<<f,l=u|(1<<f)-1;u<=l;++u)a[ar[u]>>c]=d}else for(a=new sn(n),i=0;i<n;++i)r[i]&&(a[i]=ar[s[r[i]-1]++]>>15-r[i]);return a},bn=new Je(288),ve=0;ve<144;++ve)bn[ve]=8;for(var ve=144;ve<256;++ve)bn[ve]=9;for(var ve=256;ve<280;++ve)bn[ve]=7;for(var ve=280;ve<288;++ve)bn[ve]=8;for(var qs=new Je(32),ve=0;ve<32;++ve)qs[ve]=5;var Du=xn(bn,9,1),Fu=xn(qs,5,1),cr=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},at=function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},lr=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},Ru=function(r){return(r+7)/8|0},Ou=function(r,e,t){return(t==null||t>r.length)&&(t=r.length),new Je(r.subarray(e,t))},Lu=["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"],ct=function(r,e,t){var n=new Error(e||Lu[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,ct),!t)throw n;return n},Nu=function(r,e,t,n){var i=r.length,o=0;if(!i||e.f&&!e.l)return t||new Je(0);var s=!t,a=s||e.i!=2,c=e.i;s&&(t=new Je(i*3));var d=function(Et){var It=t.length;if(Et>It){var Tn=new Je(Math.max(It*2,Et));Tn.set(t),t=Tn}},f=e.f||0,u=e.p||0,l=e.b||0,g=e.l,y=e.d,b=e.m,m=e.n,_=i*8;do{if(!g){f=at(r,u,1);var x=at(r,u+1,3);if(u+=3,x)if(x==1)g=Du,y=Fu,b=9,m=5;else if(x==2){var I=at(r,u,31)+257,C=at(r,u+10,15)+4,D=I+at(r,u+5,31)+1;u+=14;for(var L=new Je(D),R=new Je(19),N=0;N<C;++N)R[Au[N]]=at(r,u+N*3,7);u+=C*3;for(var O=cr(R),B=(1<<O)-1,z=xn(R,O,1),N=0;N<D;){var X=z[at(r,u,B)];u+=X&15;var w=X>>4;if(w<16)L[N++]=w;else{var J=0,Me=0;for(w==16?(Me=3+at(r,u,3),u+=2,J=L[N-1]):w==17?(Me=3+at(r,u,7),u+=3):w==18&&(Me=11+at(r,u,127),u+=7);Me--;)L[N++]=J}}var Ve=L.subarray(0,I),Se=L.subarray(I);b=cr(Ve),m=cr(Se),g=xn(Ve,b,1),y=xn(Se,m,1)}else ct(1);else{var w=Ru(u)+4,S=r[w-4]|r[w-3]<<8,M=w+S;if(M>i){c&&ct(0);break}a&&d(l+S),t.set(r.subarray(w,M),l),e.b=l+=S,e.p=u=M*8,e.f=f;continue}if(u>_){c&&ct(0);break}}a&&d(l+131072);for(var fe=(1<<b)-1,We=(1<<m)-1,me=u;;me=u){var J=g[lr(r,u)&fe],be=J>>4;if(u+=J&15,u>_){c&&ct(0);break}if(J||ct(2),be<256)t[l++]=be;else if(be==256){me=u,g=null;break}else{var ht=be-254;if(be>264){var N=be-257,je=Es[N];ht=at(r,u,(1<<je)-1)+js[N],u+=je}var le=y[lr(r,u)&We],He=le>>4;le||ct(3),u+=le&15;var Se=Pu[He];if(He>3){var je=Gs[He];Se+=lr(r,u)&(1<<je)-1,u+=je}if(u>_){c&&ct(0);break}a&&d(l+131072);var lt=l+ht;if(l<Se){var cn=o-Se,Sn=Math.min(Se,lt);for(cn+l<0&&ct(3);l<Sn;++l)t[l]=n[cn+l]}for(;l<lt;++l)t[l]=t[l-Se]}}e.l=g,e.p=me,e.b=l,e.f=f,g&&(f=1,e.m=b,e.d=y,e.n=m)}while(!f);return l!=t.length&&s?Ou(t,0,l):t.subarray(0,l)},ku=new Je(0),Bu=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&ct(6,"invalid zlib data"),(r[1]>>5&1)==1&&ct(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function ai(r,e){return Nu(r.subarray(Bu(r),-4),{i:2},e,e)}var zu=typeof TextDecoder<"u"&&new TextDecoder,Uu=0;try{zu.decode(ku,{stream:!0}),Uu=1}catch{}class Eu extends h.DataTextureLoader{constructor(e){super(e),this.type=h.HalfFloatType,this.outputFormat=h.RGBAFormat}parse(e){const L=Math.pow(2.7182818,2.2);function R(p,v){let T=0;for(let k=0;k<65536;++k)(k==0||p[k>>3]&1<<(k&7))&&(v[T++]=k);const F=T-1;for(;T<65536;)v[T++]=0;return F}function N(p){for(let v=0;v<16384;v++)p[v]={},p[v].len=0,p[v].lit=0,p[v].p=null}const O={l:0,c:0,lc:0};function B(p,v,T,F,k){for(;T<p;)v=v<<8|mo(F,k),T+=8;T-=p,O.l=v>>T&(1<<p)-1,O.c=v,O.lc=T}const z=new Array(59);function X(p){for(let T=0;T<=58;++T)z[T]=0;for(let T=0;T<65537;++T)z[p[T]]+=1;let v=0;for(let T=58;T>0;--T){const F=v+z[T]>>1;z[T]=v,v=F}for(let T=0;T<65537;++T){const F=p[T];F>0&&(p[T]=F|z[F]++<<6)}}function J(p,v,T,F,k,V){const P=v;let W=0,E=0;for(;F<=k;F++){if(P.value-v.value>T)return!1;B(6,W,E,p,P);const U=O.l;if(W=O.c,E=O.lc,V[F]=U,U==63){if(P.value-v.value>T)throw new Error("Something wrong with hufUnpackEncTable");B(8,W,E,p,P);let G=O.l+6;if(W=O.c,E=O.lc,F+G>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;G--;)V[F++]=0;F--}else if(U>=59){let G=U-59+2;if(F+G>k+1)throw new Error("Something wrong with hufUnpackEncTable");for(;G--;)V[F++]=0;F--}}X(V)}function Me(p){return p&63}function Ve(p){return p>>6}function Se(p,v,T,F){for(;v<=T;v++){const k=Ve(p[v]),V=Me(p[v]);if(k>>V)throw new Error("Invalid table entry");if(V>14){const P=F[k>>V-14];if(P.len)throw new Error("Invalid table entry");if(P.lit++,P.p){const W=P.p;P.p=new Array(P.lit);for(let E=0;E<P.lit-1;++E)P.p[E]=W[E]}else P.p=new Array(1);P.p[P.lit-1]=v}else if(V){let P=0;for(let W=1<<14-V;W>0;W--){const E=F[(k<<14-V)+P];if(E.len||E.p)throw new Error("Invalid table entry");E.len=V,E.lit=v,P++}}}return!0}const fe={c:0,lc:0};function We(p,v,T,F){p=p<<8|mo(T,F),v+=8,fe.c=p,fe.lc=v}const me={c:0,lc:0};function be(p,v,T,F,k,V,P,W,E){if(p==v){F<8&&(We(T,F,k,V),T=fe.c,F=fe.lc),F-=8;let U=T>>F;if(U=new Uint8Array([U])[0],W.value+U>E)return!1;const G=P[W.value-1];for(;U-- >0;)P[W.value++]=G}else if(W.value<E)P[W.value++]=p;else return!1;me.c=T,me.lc=F}function ht(p){return p&65535}function je(p){const v=ht(p);return v>32767?v-65536:v}const le={a:0,b:0};function He(p,v){const T=je(p),k=je(v),V=T+(k&1)+(k>>1),P=V,W=V-k;le.a=P,le.b=W}function lt(p,v){const T=ht(p),F=ht(v),k=T-(F>>1)&65535,V=F+k-32768&65535;le.a=V,le.b=k}function cn(p,v,T,F,k,V,P){const W=P<16384,E=T>k?k:T;let U=1,G,Z;for(;U<=E;)U<<=1;for(U>>=1,G=U,U>>=1;U>=1;){Z=0;const j=Z+V*(k-G),K=V*U,ee=V*G,Y=F*U,Q=F*G;let ie,ce,pe,Re;for(;Z<=j;Z+=ee){let de=Z;const re=Z+F*(T-G);for(;de<=re;de+=Q){const we=de+Y,ke=de+K,xe=ke+Y;W?(He(p[de+v],p[ke+v]),ie=le.a,pe=le.b,He(p[we+v],p[xe+v]),ce=le.a,Re=le.b,He(ie,ce),p[de+v]=le.a,p[we+v]=le.b,He(pe,Re),p[ke+v]=le.a,p[xe+v]=le.b):(lt(p[de+v],p[ke+v]),ie=le.a,pe=le.b,lt(p[we+v],p[xe+v]),ce=le.a,Re=le.b,lt(ie,ce),p[de+v]=le.a,p[we+v]=le.b,lt(pe,Re),p[ke+v]=le.a,p[xe+v]=le.b)}if(T&U){const we=de+K;W?He(p[de+v],p[we+v]):lt(p[de+v],p[we+v]),ie=le.a,p[we+v]=le.b,p[de+v]=ie}}if(k&U){let de=Z;const re=Z+F*(T-G);for(;de<=re;de+=Q){const we=de+Y;W?He(p[de+v],p[we+v]):lt(p[de+v],p[we+v]),ie=le.a,p[we+v]=le.b,p[de+v]=ie}}G=U,U>>=1}return Z}function Sn(p,v,T,F,k,V,P,W,E){let U=0,G=0;const Z=P,j=Math.trunc(F.value+(k+7)/8);for(;F.value<j;)for(We(U,G,T,F),U=fe.c,G=fe.lc;G>=14;){const ee=U>>G-14&16383,Y=v[ee];if(Y.len)G-=Y.len,be(Y.lit,V,U,G,T,F,W,E,Z),U=me.c,G=me.lc;else{if(!Y.p)throw new Error("hufDecode issues");let Q;for(Q=0;Q<Y.lit;Q++){const ie=Me(p[Y.p[Q]]);for(;G<ie&&F.value<j;)We(U,G,T,F),U=fe.c,G=fe.lc;if(G>=ie&&Ve(p[Y.p[Q]])==(U>>G-ie&(1<<ie)-1)){G-=ie,be(Y.p[Q],V,U,G,T,F,W,E,Z),U=me.c,G=me.lc;break}}if(Q==Y.lit)throw new Error("hufDecode issues")}}const K=8-k&7;for(U>>=K,G-=K;G>0;){const ee=v[U<<14-G&16383];if(ee.len)G-=ee.len,be(ee.lit,V,U,G,T,F,W,E,Z),U=me.c,G=me.lc;else throw new Error("hufDecode issues")}return!0}function Et(p,v,T,F,k,V){const P={value:0},W=T.value,E=tt(v,T),U=tt(v,T);T.value+=4;const G=tt(v,T);if(T.value+=4,E<0||E>=65537||U<0||U>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Z=new Array(65537),j=new Array(16384);N(j);const K=F-(T.value-W);if(J(p,T,K,E,U,Z),G>8*(F-(T.value-W)))throw new Error("Something wrong with hufUncompress");Se(Z,E,U,j),Sn(Z,j,p,T,G,U,V,k,P)}function It(p,v,T){for(let F=0;F<T;++F)v[F]=p[v[F]]}function Tn(p){for(let v=1;v<p.length;v++){const T=p[v-1]+p[v]-128;p[v]=T}}function ao(p,v){let T=0,F=Math.floor((p.length+1)/2),k=0;const V=p.length-1;for(;!(k>V||(v[k++]=p[T++],k>V));)v[k++]=p[F++]}function co(p){let v=p.byteLength;const T=new Array;let F=0;const k=new DataView(p);for(;v>0;){const V=k.getInt8(F++);if(V<0){const P=-V;v-=P+1;for(let W=0;W<P;W++)T.push(k.getUint8(F++))}else{const P=V;v-=2;const W=k.getUint8(F++);for(let E=0;E<P+1;E++)T.push(W)}}return T}function Gh(p,v,T,F,k,V){let P=new DataView(V.buffer);const W=T[p.idx[0]].width,E=T[p.idx[0]].height,U=3,G=Math.floor(W/8),Z=Math.ceil(W/8),j=Math.ceil(E/8),K=W-(Z-1)*8,ee=E-(j-1)*8,Y={value:0},Q=new Array(U),ie=new Array(U),ce=new Array(U),pe=new Array(U),Re=new Array(U);for(let re=0;re<U;++re)Re[re]=v[p.idx[re]],Q[re]=re<1?0:Q[re-1]+Z*j,ie[re]=new Float32Array(64),ce[re]=new Uint16Array(64),pe[re]=new Uint16Array(Z*64);for(let re=0;re<j;++re){let we=8;re==j-1&&(we=ee);let ke=8;for(let ae=0;ae<Z;++ae){ae==Z-1&&(ke=K);for(let ge=0;ge<U;++ge)ce[ge].fill(0),ce[ge][0]=k[Q[ge]++],lo(Y,F,ce[ge]),uo(ce[ge],ie[ge]),ho(ie[ge]);Wh(ie);for(let ge=0;ge<U;++ge)fo(ie[ge],pe[ge],ae*64)}let xe=0;for(let ae=0;ae<U;++ae){const ge=T[p.idx[ae]].type;for(let vt=8*re;vt<8*re+we;++vt){xe=Re[ae][vt];for(let An=0;An<G;++An){const dt=An*64+(vt&7)*8;P.setUint16(xe+0*2*ge,pe[ae][dt+0],!0),P.setUint16(xe+1*2*ge,pe[ae][dt+1],!0),P.setUint16(xe+2*2*ge,pe[ae][dt+2],!0),P.setUint16(xe+3*2*ge,pe[ae][dt+3],!0),P.setUint16(xe+4*2*ge,pe[ae][dt+4],!0),P.setUint16(xe+5*2*ge,pe[ae][dt+5],!0),P.setUint16(xe+6*2*ge,pe[ae][dt+6],!0),P.setUint16(xe+7*2*ge,pe[ae][dt+7],!0),xe+=8*2*ge}}if(G!=Z)for(let vt=8*re;vt<8*re+we;++vt){const An=Re[ae][vt]+8*G*2*ge,dt=G*64+(vt&7)*8;for(let pi=0;pi<ke;++pi)P.setUint16(An+pi*2*ge,pe[ae][dt+pi],!0)}}}const de=new Uint16Array(W);P=new DataView(V.buffer);for(let re=0;re<U;++re){T[p.idx[re]].decoded=!0;const we=T[p.idx[re]].type;if(T[re].type==2)for(let ke=0;ke<E;++ke){const xe=Re[re][ke];for(let ae=0;ae<W;++ae)de[ae]=P.getUint16(xe+ae*2*we,!0);for(let ae=0;ae<W;++ae)P.setFloat32(xe+ae*2*we,$(de[ae]),!0)}}}function Vh(p,v,T,F,k,V){const P=new DataView(V.buffer),W=T[p],E=W.width,U=W.height,G=Math.ceil(E/8),Z=Math.ceil(U/8),j=Math.floor(E/8),K=E-(G-1)*8,ee=U-(Z-1)*8,Y={value:0};let Q=0;const ie=new Float32Array(64),ce=new Uint16Array(64),pe=new Uint16Array(G*64);for(let Re=0;Re<Z;++Re){let de=8;Re==Z-1&&(de=ee);for(let re=0;re<G;++re)ce.fill(0),ce[0]=k[Q++],lo(Y,F,ce),uo(ce,ie),ho(ie),fo(ie,pe,re*64);for(let re=8*Re;re<8*Re+de;++re){let we=v[p][re];for(let ke=0;ke<j;++ke){const xe=ke*64+(re&7)*8;for(let ae=0;ae<8;++ae)P.setUint16(we+ae*2*W.type,pe[xe+ae],!0);we+=8*2*W.type}if(G!=j){const ke=j*64+(re&7)*8;for(let xe=0;xe<K;++xe)P.setUint16(we+xe*2*W.type,pe[ke+xe],!0)}}}W.decoded=!0}function lo(p,v,T){let F,k=1;for(;k<64;)F=v[p.value],F==65280?k=64:F>>8==255?k+=F&255:(T[k]=F,k++),p.value++}function uo(p,v){v[0]=$(p[0]),v[1]=$(p[1]),v[2]=$(p[5]),v[3]=$(p[6]),v[4]=$(p[14]),v[5]=$(p[15]),v[6]=$(p[27]),v[7]=$(p[28]),v[8]=$(p[2]),v[9]=$(p[4]),v[10]=$(p[7]),v[11]=$(p[13]),v[12]=$(p[16]),v[13]=$(p[26]),v[14]=$(p[29]),v[15]=$(p[42]),v[16]=$(p[3]),v[17]=$(p[8]),v[18]=$(p[12]),v[19]=$(p[17]),v[20]=$(p[25]),v[21]=$(p[30]),v[22]=$(p[41]),v[23]=$(p[43]),v[24]=$(p[9]),v[25]=$(p[11]),v[26]=$(p[18]),v[27]=$(p[24]),v[28]=$(p[31]),v[29]=$(p[40]),v[30]=$(p[44]),v[31]=$(p[53]),v[32]=$(p[10]),v[33]=$(p[19]),v[34]=$(p[23]),v[35]=$(p[32]),v[36]=$(p[39]),v[37]=$(p[45]),v[38]=$(p[52]),v[39]=$(p[54]),v[40]=$(p[20]),v[41]=$(p[22]),v[42]=$(p[33]),v[43]=$(p[38]),v[44]=$(p[46]),v[45]=$(p[51]),v[46]=$(p[55]),v[47]=$(p[60]),v[48]=$(p[21]),v[49]=$(p[34]),v[50]=$(p[37]),v[51]=$(p[47]),v[52]=$(p[50]),v[53]=$(p[56]),v[54]=$(p[59]),v[55]=$(p[61]),v[56]=$(p[35]),v[57]=$(p[36]),v[58]=$(p[48]),v[59]=$(p[49]),v[60]=$(p[57]),v[61]=$(p[58]),v[62]=$(p[62]),v[63]=$(p[63])}function ho(p){const v=.5*Math.cos(.7853975),T=.5*Math.cos(3.14159/16),F=.5*Math.cos(3.14159/8),k=.5*Math.cos(3*3.14159/16),V=.5*Math.cos(5*3.14159/16),P=.5*Math.cos(3*3.14159/8),W=.5*Math.cos(7*3.14159/16),E=new Array(4),U=new Array(4),G=new Array(4),Z=new Array(4);for(let j=0;j<8;++j){const K=j*8;E[0]=F*p[K+2],E[1]=P*p[K+2],E[2]=F*p[K+6],E[3]=P*p[K+6],U[0]=T*p[K+1]+k*p[K+3]+V*p[K+5]+W*p[K+7],U[1]=k*p[K+1]-W*p[K+3]-T*p[K+5]-V*p[K+7],U[2]=V*p[K+1]-T*p[K+3]+W*p[K+5]+k*p[K+7],U[3]=W*p[K+1]-V*p[K+3]+k*p[K+5]-T*p[K+7],G[0]=v*(p[K+0]+p[K+4]),G[3]=v*(p[K+0]-p[K+4]),G[1]=E[0]+E[3],G[2]=E[1]-E[2],Z[0]=G[0]+G[1],Z[1]=G[3]+G[2],Z[2]=G[3]-G[2],Z[3]=G[0]-G[1],p[K+0]=Z[0]+U[0],p[K+1]=Z[1]+U[1],p[K+2]=Z[2]+U[2],p[K+3]=Z[3]+U[3],p[K+4]=Z[3]-U[3],p[K+5]=Z[2]-U[2],p[K+6]=Z[1]-U[1],p[K+7]=Z[0]-U[0]}for(let j=0;j<8;++j)E[0]=F*p[16+j],E[1]=P*p[16+j],E[2]=F*p[48+j],E[3]=P*p[48+j],U[0]=T*p[8+j]+k*p[24+j]+V*p[40+j]+W*p[56+j],U[1]=k*p[8+j]-W*p[24+j]-T*p[40+j]-V*p[56+j],U[2]=V*p[8+j]-T*p[24+j]+W*p[40+j]+k*p[56+j],U[3]=W*p[8+j]-V*p[24+j]+k*p[40+j]-T*p[56+j],G[0]=v*(p[j]+p[32+j]),G[3]=v*(p[j]-p[32+j]),G[1]=E[0]+E[3],G[2]=E[1]-E[2],Z[0]=G[0]+G[1],Z[1]=G[3]+G[2],Z[2]=G[3]-G[2],Z[3]=G[0]-G[1],p[0+j]=Z[0]+U[0],p[8+j]=Z[1]+U[1],p[16+j]=Z[2]+U[2],p[24+j]=Z[3]+U[3],p[32+j]=Z[3]-U[3],p[40+j]=Z[2]-U[2],p[48+j]=Z[1]-U[1],p[56+j]=Z[0]-U[0]}function Wh(p){for(let v=0;v<64;++v){const T=p[0][v],F=p[1][v],k=p[2][v];p[0][v]=T+1.5747*k,p[1][v]=T-.1873*F-.4682*k,p[2][v]=T+1.8556*F}}function fo(p,v,T){for(let F=0;F<64;++F)v[T+F]=h.DataUtils.toHalfFloat(jh(p[F]))}function jh(p){return p<=1?Math.sign(p)*Math.pow(Math.abs(p),2.2):Math.sign(p)*Math.pow(L,Math.abs(p)-1)}function mr(p){return new DataView(p.array.buffer,p.offset.value,p.size)}function qh(p){const v=p.viewer.buffer.slice(p.offset.value,p.offset.value+p.size),T=new Uint8Array(co(v)),F=new Uint8Array(T.length);return Tn(T),ao(T,F),new DataView(F.buffer)}function gr(p){const v=p.array.slice(p.offset.value,p.offset.value+p.size),T=ai(v),F=new Uint8Array(T.length);return Tn(T),ao(T,F),new DataView(F.buffer)}function Zh(p){const v=p.viewer,T={value:p.offset.value},F=new Uint16Array(p.columns*p.lines*(p.inputChannels.length*p.type)),k=new Uint8Array(8192);let V=0;const P=new Array(p.inputChannels.length);for(let ee=0,Y=p.inputChannels.length;ee<Y;ee++)P[ee]={},P[ee].start=V,P[ee].end=P[ee].start,P[ee].nx=p.columns,P[ee].ny=p.lines,P[ee].size=p.type,V+=P[ee].nx*P[ee].ny*P[ee].size;const W=Mn(v,T),E=Mn(v,T);if(E>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(W<=E)for(let ee=0;ee<E-W+1;ee++)k[ee+W]=Ct(v,T);const U=new Uint16Array(65536),G=R(k,U),Z=tt(v,T);Et(p.array,v,T,Z,F,V);for(let ee=0;ee<p.inputChannels.length;++ee){const Y=P[ee];for(let Q=0;Q<P[ee].size;++Q)cn(F,Y.start+Q,Y.nx,Y.size,Y.ny,Y.nx*Y.size,G)}It(U,F,V);let j=0;const K=new Uint8Array(F.buffer.byteLength);for(let ee=0;ee<p.lines;ee++)for(let Y=0;Y<p.inputChannels.length;Y++){const Q=P[Y],ie=Q.nx*Q.size,ce=new Uint8Array(F.buffer,Q.end*2,ie*2);K.set(ce,j),j+=ie*2,Q.end+=ie}return new DataView(K.buffer)}function Yh(p){const v=p.array.slice(p.offset.value,p.offset.value+p.size),T=ai(v),F=p.inputChannels.length*p.lines*p.columns*p.totalBytes,k=new ArrayBuffer(F),V=new DataView(k);let P=0,W=0;const E=new Array(4);for(let U=0;U<p.lines;U++)for(let G=0;G<p.inputChannels.length;G++){let Z=0;switch(p.inputChannels[G].pixelType){case 1:E[0]=P,E[1]=E[0]+p.columns,P=E[1]+p.columns;for(let K=0;K<p.columns;++K){const ee=T[E[0]++]<<8|T[E[1]++];Z+=ee,V.setUint16(W,Z,!0),W+=2}break;case 2:E[0]=P,E[1]=E[0]+p.columns,E[2]=E[1]+p.columns,P=E[2]+p.columns;for(let K=0;K<p.columns;++K){const ee=T[E[0]++]<<24|T[E[1]++]<<16|T[E[2]++]<<8;Z+=ee,V.setUint32(W,Z,!0),W+=4}break}}return V}function po(p){const v=p.viewer,T={value:p.offset.value},F=new Uint8Array(p.columns*p.lines*(p.inputChannels.length*p.type*2)),k={version:Ke(v,T),unknownUncompressedSize:Ke(v,T),unknownCompressedSize:Ke(v,T),acCompressedSize:Ke(v,T),dcCompressedSize:Ke(v,T),rleCompressedSize:Ke(v,T),rleUncompressedSize:Ke(v,T),rleRawSize:Ke(v,T),totalAcUncompressedCount:Ke(v,T),totalDcUncompressedCount:Ke(v,T),acCompression:Ke(v,T)};if(k.version<2)throw new Error("EXRLoader.parse: "+Gt.compression+" version "+k.version+" is unsupported");const V=new Array;let P=Mn(v,T)-2;for(;P>0;){const Y=fi(v.buffer,T),Q=Ct(v,T),ie=Q>>2&3,ce=(Q>>4)-1,pe=new Int8Array([ce])[0],Re=Ct(v,T);V.push({name:Y,index:pe,type:Re,compression:ie}),P-=Y.length+3}const W=Gt.channels,E=new Array(p.inputChannels.length);for(let Y=0;Y<p.inputChannels.length;++Y){const Q=E[Y]={},ie=W[Y];Q.name=ie.name,Q.compression=0,Q.decoded=!1,Q.type=ie.pixelType,Q.pLinear=ie.pLinear,Q.width=p.columns,Q.height=p.lines}const U={idx:new Array(3)};for(let Y=0;Y<p.inputChannels.length;++Y){const Q=E[Y];for(let ie=0;ie<V.length;++ie){const ce=V[ie];Q.name==ce.name&&(Q.compression=ce.compression,ce.index>=0&&(U.idx[ce.index]=Y),Q.offset=Y)}}let G,Z,j;if(k.acCompressedSize>0)switch(k.acCompression){case 0:G=new Uint16Array(k.totalAcUncompressedCount),Et(p.array,v,T,k.acCompressedSize,G,k.totalAcUncompressedCount);break;case 1:const Y=p.array.slice(T.value,T.value+k.totalAcUncompressedCount),Q=ai(Y);G=new Uint16Array(Q.buffer),T.value+=k.totalAcUncompressedCount;break}if(k.dcCompressedSize>0){const Y={array:p.array,offset:T,size:k.dcCompressedSize};Z=new Uint16Array(gr(Y).buffer),T.value+=k.dcCompressedSize}if(k.rleRawSize>0){const Y=p.array.slice(T.value,T.value+k.rleCompressedSize),Q=ai(Y);j=co(Q.buffer),T.value+=k.rleCompressedSize}let K=0;const ee=new Array(E.length);for(let Y=0;Y<ee.length;++Y)ee[Y]=new Array;for(let Y=0;Y<p.lines;++Y)for(let Q=0;Q<E.length;++Q)ee[Q].push(K),K+=E[Q].width*p.type*2;U.idx[0]!==void 0&&E[U.idx[0]]&&Gh(U,ee,E,G,Z,F);for(let Y=0;Y<E.length;++Y){const Q=E[Y];if(!Q.decoded)switch(Q.compression){case 2:let ie=0,ce=0;for(let pe=0;pe<p.lines;++pe){let Re=ee[Y][ie];for(let de=0;de<Q.width;++de){for(let re=0;re<2*Q.type;++re)F[Re++]=j[ce+re*Q.width*Q.height];ce++}ie++}break;case 1:Vh(Y,ee,E,G,Z,F);break;default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(F.buffer)}function fi(p,v){const T=new Uint8Array(p);let F=0;for(;T[v.value+F]!=0;)F+=1;const k=new TextDecoder().decode(T.slice(v.value,v.value+F));return v.value=v.value+F+1,k}function Kh(p,v,T){const F=new TextDecoder().decode(new Uint8Array(p).slice(v.value,v.value+T));return v.value=v.value+T,F}function Xh(p,v){const T=et(p,v),F=tt(p,v);return[T,F]}function $h(p,v){const T=tt(p,v),F=tt(p,v);return[T,F]}function et(p,v){const T=p.getInt32(v.value,!0);return v.value=v.value+4,T}function tt(p,v){const T=p.getUint32(v.value,!0);return v.value=v.value+4,T}function mo(p,v){const T=p[v.value];return v.value=v.value+1,T}function Ct(p,v){const T=p.getUint8(v.value);return v.value=v.value+1,T}const Ke=function(p,v){let T;return"getBigInt64"in DataView.prototype?T=Number(p.getBigInt64(v.value,!0)):T=p.getUint32(v.value+4,!0)+Number(p.getUint32(v.value,!0)<<32),v.value+=8,T};function Ue(p,v){const T=p.getFloat32(v.value,!0);return v.value+=4,T}function Qh(p,v){return h.DataUtils.toHalfFloat(Ue(p,v))}function $(p){const v=(p&31744)>>10,T=p&1023;return(p>>15?-1:1)*(v?v===31?T?NaN:1/0:Math.pow(2,v-15)*(1+T/1024):6103515625e-14*(T/1024))}function Mn(p,v){const T=p.getUint16(v.value,!0);return v.value+=2,T}function Jh(p,v){return $(Mn(p,v))}function Hh(p,v,T,F){const k=T.value,V=[];for(;T.value<k+F-1;){const P=fi(v,T),W=et(p,T),E=Ct(p,T);T.value+=3;const U=et(p,T),G=et(p,T);V.push({name:P,pixelType:W,pLinear:E,xSampling:U,ySampling:G})}return T.value+=1,V}function ed(p,v){const T=Ue(p,v),F=Ue(p,v),k=Ue(p,v),V=Ue(p,v),P=Ue(p,v),W=Ue(p,v),E=Ue(p,v),U=Ue(p,v);return{redX:T,redY:F,greenX:k,greenY:V,blueX:P,blueY:W,whiteX:E,whiteY:U}}function td(p,v){const T=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],F=Ct(p,v);return T[F]}function nd(p,v){const T=et(p,v),F=et(p,v),k=et(p,v),V=et(p,v);return{xMin:T,yMin:F,xMax:k,yMax:V}}function id(p,v){const T=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],F=Ct(p,v);return T[F]}function rd(p,v){const T=["ENVMAP_LATLONG","ENVMAP_CUBE"],F=Ct(p,v);return T[F]}function sd(p,v){const T=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],F=["ROUND_DOWN","ROUND_UP"],k=tt(p,v),V=tt(p,v),P=Ct(p,v);return{xSize:k,ySize:V,levelMode:T[P&15],roundingMode:F[P>>4]}}function od(p,v){const T=Ue(p,v),F=Ue(p,v);return[T,F]}function ad(p,v){const T=Ue(p,v),F=Ue(p,v),k=Ue(p,v);return[T,F,k]}function cd(p,v,T,F,k){if(F==="string"||F==="stringvector"||F==="iccProfile")return Kh(v,T,k);if(F==="chlist")return Hh(p,v,T,k);if(F==="chromaticities")return ed(p,T);if(F==="compression")return td(p,T);if(F==="box2i")return nd(p,T);if(F==="envmap")return rd(p,T);if(F==="tiledesc")return sd(p,T);if(F==="lineOrder")return id(p,T);if(F==="float")return Ue(p,T);if(F==="v2f")return od(p,T);if(F==="v3f")return ad(p,T);if(F==="int")return et(p,T);if(F==="rational")return Xh(p,T);if(F==="timecode")return $h(p,T);if(F==="preview")return T.value+=k,"skipped";T.value+=k}function ld(p,v){const T=Math.log2(p);return v=="ROUND_DOWN"?Math.floor(T):Math.ceil(T)}function ud(p,v,T){let F=0;switch(p.levelMode){case"ONE_LEVEL":F=1;break;case"MIPMAP_LEVELS":F=ld(Math.max(v,T),p.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return F}function go(p,v,T,F){const k=new Array(p);for(let V=0;V<p;V++){const P=1<<V;let W=v/P|0;F=="ROUND_UP"&&W*P<v&&(W+=1);const E=Math.max(W,1);k[V]=(E+T-1)/T|0}return k}function hd(){const p=this,v=p.offset,T={value:0};for(let F=0;F<p.tileCount;F++){const k=et(p.viewer,v),V=et(p.viewer,v);v.value+=8,p.size=tt(p.viewer,v);const P=k*p.blockWidth,W=V*p.blockHeight;p.columns=P+p.blockWidth>p.width?p.width-P:p.blockWidth,p.lines=W+p.blockHeight>p.height?p.height-W:p.blockHeight;const E=p.columns*p.totalBytes,G=p.size<p.lines*E?p.uncompress(p):mr(p);v.value+=p.size;for(let Z=0;Z<p.lines;Z++){const j=Z*p.columns*p.totalBytes;for(let K=0;K<p.inputChannels.length;K++){const ee=Gt.channels[K].name,Y=p.channelByteOffsets[ee]*p.columns,Q=p.decodeChannels[ee];if(Q===void 0)continue;T.value=j+Y;const ie=(p.height-(1+W+Z))*p.outLineWidth;for(let ce=0;ce<p.columns;ce++){const pe=ie+(ce+P)*p.outputChannels+Q;p.byteArray[pe]=p.getter(G,T)}}}}}function dd(){const p=this,v=p.offset,T={value:0};for(let F=0;F<p.height/p.blockHeight;F++){const k=et(p.viewer,v)-Gt.dataWindow.yMin;p.size=tt(p.viewer,v),p.lines=k+p.blockHeight>p.height?p.height-k:p.blockHeight;const V=p.columns*p.totalBytes,W=p.size<p.lines*V?p.uncompress(p):mr(p);v.value+=p.size;for(let E=0;E<p.blockHeight;E++){const U=F*p.blockHeight,G=E+p.scanOrder(U);if(G>=p.height)continue;const Z=E*V,j=(p.height-1-G)*p.outLineWidth;for(let K=0;K<p.inputChannels.length;K++){const ee=Gt.channels[K].name,Y=p.channelByteOffsets[ee]*p.columns,Q=p.decodeChannels[ee];if(Q!==void 0){T.value=Z+Y;for(let ie=0;ie<p.columns;ie++){const ce=j+ie*p.outputChannels+Q;p.byteArray[ce]=p.getter(W,T)}}}}}}function fd(p,v,T){const F={};if(p.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");F.version=p.getUint8(4);const k=p.getUint8(5);F.spec={singleTile:!!(k&2),longName:!!(k&4),deepFormat:!!(k&8),multiPart:!!(k&16)},T.value=8;let V=!0;for(;V;){const P=fi(v,T);if(P==="")V=!1;else{const W=fi(v,T),E=tt(p,T),U=cd(p,v,T,W,E);U===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${W}'.`):F[P]=U}}if((k&-7)!=0)throw console.error("THREE.EXRHeader:",F),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return F}function pd(p,v,T,F,k,V){const P={size:0,viewer:v,array:T,offset:F,width:p.dataWindow.xMax-p.dataWindow.xMin+1,height:p.dataWindow.yMax-p.dataWindow.yMin+1,inputChannels:p.channels,channelByteOffsets:{},shouldExpand:!1,scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:h.LinearSRGBColorSpace};switch(p.compression){case"NO_COMPRESSION":P.blockHeight=1,P.uncompress=mr;break;case"RLE_COMPRESSION":P.blockHeight=1,P.uncompress=qh;break;case"ZIPS_COMPRESSION":P.blockHeight=1,P.uncompress=gr;break;case"ZIP_COMPRESSION":P.blockHeight=16,P.uncompress=gr;break;case"PIZ_COMPRESSION":P.blockHeight=32,P.uncompress=Zh;break;case"PXR24_COMPRESSION":P.blockHeight=16,P.uncompress=Yh;break;case"DWAA_COMPRESSION":P.blockHeight=32,P.uncompress=po;break;case"DWAB_COMPRESSION":P.blockHeight=256,P.uncompress=po;break;default:throw new Error("EXRLoader.parse: "+p.compression+" is unsupported")}const W={};for(const j of p.channels)switch(j.name){case"Y":case"R":case"G":case"B":case"A":W[j.name]=!0,P.type=j.pixelType}let E=!1,U=!1;if(W.R&&W.G&&W.B)P.outputChannels=4;else if(W.Y)P.outputChannels=1;else throw new Error("EXRLoader.parse: file contains unsupported data channels.");switch(P.outputChannels){case 4:V==h.RGBAFormat?(E=!W.A,P.format=h.RGBAFormat,P.colorSpace=h.LinearSRGBColorSpace,P.outputChannels=4,P.decodeChannels={R:0,G:1,B:2,A:3}):V==h.RGFormat?(P.format=h.RGFormat,P.colorSpace=h.LinearSRGBColorSpace,P.outputChannels=2,P.decodeChannels={R:0,G:1}):V==h.RedFormat?(P.format=h.RedFormat,P.colorSpace=h.LinearSRGBColorSpace,P.outputChannels=1,P.decodeChannels={R:0}):U=!0;break;case 1:V==h.RGBAFormat?(E=!0,P.format=h.RGBAFormat,P.colorSpace=h.LinearSRGBColorSpace,P.outputChannels=4,P.shouldExpand=!0,P.decodeChannels={Y:0}):V==h.RGFormat?(P.format=h.RGFormat,P.colorSpace=h.LinearSRGBColorSpace,P.outputChannels=2,P.shouldExpand=!0,P.decodeChannels={Y:0}):V==h.RedFormat?(P.format=h.RedFormat,P.colorSpace=h.LinearSRGBColorSpace,P.outputChannels=1,P.decodeChannels={Y:0}):U=!0;break;default:U=!0}if(U)throw new Error("EXRLoader.parse: invalid output format for specified file.");if(P.type==1)switch(k){case h.FloatType:P.getter=Jh;break;case h.HalfFloatType:P.getter=Mn;break}else if(P.type==2)switch(k){case h.FloatType:P.getter=Ue;break;case h.HalfFloatType:P.getter=Qh}else throw new Error("EXRLoader.parse: unsupported pixelType "+P.type+" for "+p.compression+".");P.columns=P.width;const G=P.width*P.height*P.outputChannels;switch(k){case h.FloatType:P.byteArray=new Float32Array(G),E&&P.byteArray.fill(1,0,G);break;case h.HalfFloatType:P.byteArray=new Uint16Array(G),E&&P.byteArray.fill(15360,0,G);break;default:console.error("THREE.EXRLoader: unsupported type: ",k);break}let Z=0;for(const j of p.channels)P.decodeChannels[j.name]!==void 0&&(P.channelByteOffsets[j.name]=Z),Z+=j.pixelType*2;if(P.totalBytes=Z,P.outLineWidth=P.width*P.outputChannels,p.lineOrder==="INCREASING_Y"?P.scanOrder=j=>j:P.scanOrder=j=>P.height-1-j,p.spec.singleTile){P.blockHeight=p.tiles.ySize,P.blockWidth=p.tiles.xSize;const j=ud(p.tiles,P.width,P.height),K=go(j,P.width,p.tiles.xSize,p.tiles.roundingMode),ee=go(j,P.height,p.tiles.ySize,p.tiles.roundingMode);P.tileCount=K[0]*ee[0];for(let Y=0;Y<j;Y++)for(let Q=0;Q<ee[Y];Q++)for(let ie=0;ie<K[Y];ie++)Ke(v,F);P.decode=hd.bind(P)}else{P.blockWidth=P.width;const j=Math.ceil(P.height/P.blockHeight);for(let K=0;K<j;K++)Ke(v,F);P.decode=dd.bind(P)}return P}const yo={value:0},vo=new DataView(e),md=new Uint8Array(e),Gt=fd(vo,e,yo),Pt=pd(Gt,vo,md,yo,this.type,this.outputFormat);if(Pt.decode(),Pt.shouldExpand){const p=Pt.byteArray;if(this.outputFormat==h.RGBAFormat)for(let v=0;v<p.length;v+=4)p[v+2]=p[v+1]=p[v];else if(this.outputFormat==h.RGFormat)for(let v=0;v<p.length;v+=2)p[v+1]=p[v]}return{header:Gt,width:Pt.width,height:Pt.height,data:Pt.byteArray,format:Pt.format,colorSpace:Pt.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}setOutputFormat(e){return this.outputFormat=e,this}load(e,t,n,i){function o(s,a){s.colorSpace=a.colorSpace,s.minFilter=h.LinearFilter,s.magFilter=h.LinearFilter,s.generateMipmaps=!1,s.flipY=!1,t&&t(s,a)}return super.load(e,o,n,i)}}class Gu extends h.DataTextureLoader{constructor(e){super(e),this.type=h.HalfFloatType}parse(e){const s=function(D,L){switch(D){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(L||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(L||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(L||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(L||""))}},f=`
|
|
3983
|
+
`,u=function(D,L,R){L=L||1024;let O=D.pos,B=-1,z=0,X="",J=String.fromCharCode.apply(null,new Uint16Array(D.subarray(O,O+128)));for(;0>(B=J.indexOf(f))&&z<L&&O<D.byteLength;)X+=J,z+=J.length,O+=128,J+=String.fromCharCode.apply(null,new Uint16Array(D.subarray(O,O+128)));return-1<B?(D.pos+=z+B+1,X+J.slice(0,B)):!1},l=function(D){const L=/^#\?(\S+)/,R=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,N=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,O=/^\s*FORMAT=(\S+)\s*$/,B=/^\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 X,J;for((D.pos>=D.byteLength||!(X=u(D)))&&s(1,"no header found"),(J=X.match(L))||s(3,"bad initial token"),z.valid|=1,z.programtype=J[1],z.string+=X+`
|
|
3984
|
+
`;X=u(D),X!==!1;){if(z.string+=X+`
|
|
3985
|
+
`,X.charAt(0)==="#"){z.comments+=X+`
|
|
3986
|
+
`;continue}if((J=X.match(R))&&(z.gamma=parseFloat(J[1])),(J=X.match(N))&&(z.exposure=parseFloat(J[1])),(J=X.match(O))&&(z.valid|=2,z.format=J[1]),(J=X.match(B))&&(z.valid|=4,z.height=parseInt(J[1],10),z.width=parseInt(J[2],10)),z.valid&2&&z.valid&4)break}return z.valid&2||s(3,"missing format specifier"),z.valid&4||s(3,"missing image size specifier"),z},g=function(D,L,R){const N=L;if(N<8||N>32767||D[0]!==2||D[1]!==2||D[2]&128)return new Uint8Array(D);N!==(D[2]<<8|D[3])&&s(3,"wrong scanline width");const O=new Uint8Array(4*L*R);O.length||s(4,"unable to allocate buffer space");let B=0,z=0;const X=4*N,J=new Uint8Array(4),Me=new Uint8Array(X);let Ve=R;for(;Ve>0&&z<D.byteLength;){z+4>D.byteLength&&s(1),J[0]=D[z++],J[1]=D[z++],J[2]=D[z++],J[3]=D[z++],(J[0]!=2||J[1]!=2||(J[2]<<8|J[3])!=N)&&s(3,"bad rgbe scanline format");let Se=0,fe;for(;Se<X&&z<D.byteLength;){fe=D[z++];const me=fe>128;if(me&&(fe-=128),(fe===0||Se+fe>X)&&s(3,"bad scanline data"),me){const be=D[z++];for(let ht=0;ht<fe;ht++)Me[Se++]=be}else Me.set(D.subarray(z,z+fe),Se),Se+=fe,z+=fe}const We=N;for(let me=0;me<We;me++){let be=0;O[B]=Me[me+be],be+=N,O[B+1]=Me[me+be],be+=N,O[B+2]=Me[me+be],be+=N,O[B+3]=Me[me+be],B+=4}Ve--}return O},y=function(D,L,R,N){const O=D[L+3],B=Math.pow(2,O-128)/255;R[N+0]=D[L+0]*B,R[N+1]=D[L+1]*B,R[N+2]=D[L+2]*B,R[N+3]=1},b=function(D,L,R,N){const O=D[L+3],B=Math.pow(2,O-128)/255;R[N+0]=h.DataUtils.toHalfFloat(Math.min(D[L+0]*B,65504)),R[N+1]=h.DataUtils.toHalfFloat(Math.min(D[L+1]*B,65504)),R[N+2]=h.DataUtils.toHalfFloat(Math.min(D[L+2]*B,65504)),R[N+3]=h.DataUtils.toHalfFloat(1)},m=new Uint8Array(e);m.pos=0;const _=l(m),x=_.width,w=_.height,S=g(m.subarray(m.pos),x,w);let M,I,C;switch(this.type){case h.FloatType:C=S.length/4;const D=new Float32Array(C*4);for(let R=0;R<C;R++)y(S,R*4,D,R*4);M=D,I=h.FloatType;break;case h.HalfFloatType:C=S.length/4;const L=new Uint16Array(C*4);for(let R=0;R<C;R++)b(S,R*4,L,R*4);M=L,I=h.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:x,height:w,data:M,header:_.string,gamma:_.gamma,exposure:_.exposure,type:I}}setDataType(e){return this.type=e,this}load(e,t,n,i){function o(s,a){switch(s.type){case h.FloatType:case h.HalfFloatType:s.colorSpace=h.LinearSRGBColorSpace,s.minFilter=h.LinearFilter,s.magFilter=h.LinearFilter,s.generateMipmaps=!1,s.flipY=!0;break}t&&t(s,a)}return super.load(e,o,n,i)}}class Vu extends Gu{constructor(e){console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."),super(e)}}class Wu extends h.Scene{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;const e=new h.BoxGeometry;e.deleteAttribute("uv");const t=new h.MeshStandardMaterial({side:h.BackSide}),n=new h.MeshStandardMaterial,i=new h.PointLight(16777215,900,28,2);i.position.set(.418,16.199,.3),this.add(i);const o=new h.Mesh(e,t);o.position.set(-.757,13.219,.717),o.scale.set(31.713,28.305,28.591),this.add(o);const s=new h.InstancedMesh(e,n,6),a=new h.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(),s.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(),s.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(),s.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(),s.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(),s.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(),s.setMatrixAt(5,a.matrix),this.add(s);const c=new h.Mesh(e,on(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const d=new h.Mesh(e,on(50));d.position.set(-16.109,18.021,-8.207),d.scale.set(.1,2.425,2.751),this.add(d);const f=new h.Mesh(e,on(17));f.position.set(14.904,12.198,-1.832),f.scale.set(.15,4.265,6.331),this.add(f);const u=new h.Mesh(e,on(43));u.position.set(-.462,8.89,14.52),u.scale.set(4.38,5.441,.088),this.add(u);const l=new h.Mesh(e,on(20));l.position.set(3.235,11.486,-12.541),l.scale.set(2.5,2,.1),this.add(l);const g=new h.Mesh(e,on(100));g.position.set(0,20,0),g.scale.set(1,.1,1),this.add(g)}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 on(r){return new h.MeshLambertMaterial({color:0,emissive:16777215,emissiveIntensity:r})}class ju{constructor(){this.pmremGenerator=null,this.loadedTextures=new Map}async initialize(e){var t;try{const n=e.renderer;let i=n.renderer||((t=n.getThreeRenderer)==null?void 0:t.call(n));if(!i&&n.getDomElement){const o=n.getDomElement();if(o&&"parentElement"in o&&o.parentElement){const s=o.parentElement.renderer;s instanceof A.WebGLRenderer&&(i=s)}}return i?(this.pmremGenerator=new A.PMREMGenerator(i),this.pmremGenerator.compileEquirectangularShader(),q.ok(void 0)):q.err(new H("Could not access Three.js renderer",te.INITIALIZATION_FAILED))}catch(n){return q.err(new H("Failed to initialize environment service",te.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return q.ok(new an(n));const i=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let o;switch(i){case"hdr":o=new Vu;break;case"exr":o=new Eu;break;case"jpg":case"jpeg":case"png":o=new A.TextureLoader;break;default:return q.err(new H(`Unsupported environment map format: ${i}`,te.UNSUPPORTED_FORMAT,{url:e,extension:i}))}const s=await new Promise((a,c)=>{o.load(e,d=>{a(d)},void 0,d=>c(d))});if(this.pmremGenerator){s.mapping=A.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(s).texture;return this.loadedTextures.set(e,a),this.loadedTextures.set(e+"_original",s),q.ok(new an(a))}return this.loadedTextures.set(e,s),q.ok(new an(s))}catch(n){return q.err(new H("Failed to load environment map",te.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{if(!(e instanceof Dt))return q.err(new H("Scene must be ThreeSceneAdapter",te.INVALID_PARAMETER));if(!(t instanceof an))return q.err(new H("Texture must be ThreeTextureAdapter",te.INVALID_PARAMETER));const i=e.getThreeScene(),o=t.getThreeTexture();if(i.environment=o,n&&(n.backgroundBlurriness!==void 0&&(i.backgroundBlurriness=n.backgroundBlurriness),n.backgroundIntensity!==void 0&&(i.backgroundIntensity=n.backgroundIntensity),n.environmentIntensity!==void 0&&(i.environmentIntensity=n.environmentIntensity)),o.mapping===A.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,d])=>c.endsWith("_original")&&d.mapping===A.EquirectangularReflectionMapping);a&&(i.__originalEnvironmentTexture=a[1])}else o.mapping===A.EquirectangularReflectionMapping&&(i.__originalEnvironmentTexture=o);if(o.mapping===A.EquirectangularReflectionMapping)i.background=o;else if(o.mapping===A.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,d])=>c.endsWith("_original")&&d.mapping===A.EquirectangularReflectionMapping);a?i.background=a[1]:i.background=o}else i.background=o;return q.ok(void 0)}catch(i){return q.err(new H("Failed to apply environment to scene",te.SCENE_OPERATION_FAILED,{originalError:i}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new an(t):null}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return q.err(new H("Environment service not initialized",te.INITIALIZATION_FAILED));const t=new Wu,n=this.pmremGenerator.fromScene(t).texture;return t.dispose(),q.ok(new an(n))}catch(t){return q.err(new H("Failed to create studio environment",te.TEXTURE_LOAD_FAILED,{originalError:t}))}}dispose(){this.loadedTextures.forEach(e=>e.dispose()),this.loadedTextures.clear(),this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null)}}class an{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 qu{constructor(e){this.object=e,this.boundingBox=new A.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 A.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class Zu{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof A.Object3D&&(t=e),t?(new qu(t).alignToFloor(),q.ok(void 0)):q.err(new H("Could not get Three.js object for floor alignment",te.INVALID_PARAMETER))}catch(t){return q.err(new H("Failed to align object to floor",te.OPERATION_FAILED,{originalError:t}))}}}var ci=(r=>(r.MapControls="MapControls",r.OrbitControls="OrbitControls",r))(ci||{});class Yu{static convertRendererOptions(e){const t={antialias:e.antialias,alpha:e.alpha,premultipliedAlpha:e.premultipliedAlpha,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference,pixelRatio:e.pixelRatio};return(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}),t}static convertShadowMapType(e){if(typeof e=="number"){if(e===A.BasicShadowMap)return"basic";if(e===A.PCFShadowMap)return"pcf";if(e===A.PCFSoftShadowMap)return"pcfsoft";if(e===A.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===A.NoToneMapping)return"none";if(e===A.LinearToneMapping)return"linear";if(e===A.ReinhardToneMapping)return"reinhard";if(e===A.CineonToneMapping)return"cineon";if(e===A.ACESFilmicToneMapping)return"aces"}return typeof e=="string"?e:"aces"}}class Ku{static createViewer(e,t){var b;const n=new Io(e),i=new Dt,o=this.createCamera(t),s=this.createControls(o.getThreeCamera(),e,t),a=new Xu().createDefaultLoader(),c=new Pa,d=new ju;let f;(((b=t.pathTracing)==null?void 0:b.enabled)??!1)&&(f=new Tu);const l=new Zu,g=Yu.convertRendererOptions(t.renderer||{}),y={renderer:n,scene:i,camera:o,controls:s,modelLoader:a,options:t,rendererOptions:g,sceneSetupService:c,environmentService:d,pathTracingService:f,floorAlignmentService:l};return new Mo(y)}static createCamera(e){const n=e.camera||{},i=n.fov||n.cameraFov||75,o=n.near||n.cameraNear||.1,s=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,d=vi.create(i,1,o,s);return a&&d.position.set(a[0],a[1],a[2]),c&&d.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),d}static createControls(e,t,n){const i=n.controls||{},o=i.type||ci.OrbitControls;let s;o===ci.MapControls?s=new Nr(e,t):s=new Lr(e,t),s.enabled=i.enabled??!0,s.enableDamping=i.enableDamping??!0,s.dampingFactor=i.dampingFactor??.25,s.enableZoom=i.enableZoom??!0,s.enableRotate=i.enableRotate??!0,s.enablePan=i.enablePan??!0,i.minDistance!==void 0&&(s.minDistance=i.minDistance),i.maxDistance!==void 0&&(s.maxDistance=i.maxDistance),i.minPolarAngle!==void 0&&(s.minPolarAngle=i.minPolarAngle),i.maxPolarAngle!==void 0&&(s.maxPolarAngle=i.maxPolarAngle);const c=n.camera||{},d=c.target||c.cameraTarget;return d&&s.target&&(s.target.set(d[0],d[1],d[2]),s.update()),s}}class Xu extends Cr{createDefaultLoader(){return Cr.createLoader("model.glb")}}const Zs={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!0,animationLoop:null,pathTracing:{enabled:!1,maxSamples:16,bounces:16,transmissiveBounces:4,renderScale:.8,lowResScale:.25,dynamicLowRes:!0},camera:{position:[60,60,60],target:[0,0,0],fov:45,near:.1,far:1e5,autoFitToObject:!0},environment:{url:"https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/industrial_sunset_puresky.jpg",backgroundBlurriness:.15,backgroundIntensity:1,environmentIntensity:1},lighting:{ambientLight:{color:"#404040",intensity:Math.PI},hemisphereLight:{skyColor:"#ffffbb",groundColor:"#080820",intensity:1},directionalLight:{color:"#ffffff",intensity:Math.PI,position:[72,72,72],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:1}}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:window.devicePixelRatio,shadowMapType:2,toneMapping:6,toneMappingExposure:1.5},controls:{type:ci.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0},helpers:{grid:{type:"hexagonal_wire",size:20,divisions:20,colorGrid:4473924,opacity:.5,styleOptions:{}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}};function $u(r){const e=ne.useRef(r),t=ne.useMemo(()=>JSON.stringify({pathTracing:r.pathTracing,staticScene:r.staticScene,renderer:r.renderer,camera:r.camera,controls:r.controls,backgroundColor:r.backgroundColor,environment:r.environment,lighting:r.lighting,helpers:r.helpers}),[r.pathTracing,r.staticScene,r.renderer,r.camera,r.controls,r.backgroundColor,r.environment,r.lighting,r.helpers]);return ne.useMemo(()=>{e.current=r},[t,r]),e.current}function Qu(r,e){const t=ne.useRef(null),[n,i]=ne.useState(new it),[o,s]=ne.useState(!1),a=$u(e);ne.useEffect(()=>{if(!r.current||t.current)return;const d={...Zs,...a},f=Ku.createViewer(r.current,d);t.current=f;const u=f.onStateChange(l=>{i(l)});return f.initialize().then(l=>{l.ok?s(!0):console.error("Failed to initialize viewer:",l.error)}),()=>{u(),f.dispose(),t.current=null,s(!1)}},[r,a]);const c=ne.useRef({width:0,height:0});return ne.useEffect(()=>{if(!t.current||!r.current)return;let d=null;const f=g=>{if(r.current&&t.current){const y=r.current.parentElement||r.current;let{clientWidth:b,clientHeight:m}=y;if(g&&g[0]){const{width:_,height:x}=g[0].contentRect;b=Math.floor(_),m=Math.floor(x)}if(c.current.width===b&&c.current.height===m)return;d!==null&&cancelAnimationFrame(d),d=requestAnimationFrame(()=>{t.current&&r.current&&(t.current.resize(b,m),c.current={width:b,height:m})})}};f();const u=()=>f();window.addEventListener("resize",u);let l=null;return typeof ResizeObserver<"u"&&r.current.parentElement&&(l=new ResizeObserver(f),l.observe(r.current.parentElement)),()=>{window.removeEventListener("resize",u),l==null||l.disconnect(),d!==null&&cancelAnimationFrame(d)}},[o,r]),{viewer:t.current,state:n,isInitialized:o}}function Ju(r,e){const t=ne.useRef(e);t.current=e,ne.useEffect(()=>{if(!r)return;const n=r.getEvents(),i=[];return Object.keys(e).forEach(o=>{if(e[o]){const a=c=>{const d=t.current[o];d&&d(c)};n.on(o,a),i.push(()=>n.off(o,a))}}),()=>{i.forEach(o=>o())}},[r])}const Ys=ne.createContext(null);function Hu({viewer:r,canvasRef:e,children:t}){return Ce.jsx(Ys.Provider,{value:{viewer:r,canvasRef:e},children:t})}function eh(){const r=ne.useContext(Ys);if(!r)throw new Error("useViewerContext must be used within ViewerProvider");return r}function th(){const{canvasRef:r}=eh();return Ce.jsx("canvas",{ref:r,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var r=document.createElement("style");r.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(r)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();const nh=(r,e,t,n,i,o)=>{const s=performance.now(),a=()=>{const c=performance.now()-s,d=Math.min(c/i,1);r.position.lerpVectors(t,n,d),e==null||e.update(),o(),d<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},Ks={type:"change"},ur={type:"start"},Xs={type:"end"},li=new h.Ray,$s=new h.Plane,ih=Math.cos(70*h.MathUtils.DEG2RAD),Fe=new h.Vector3,Ye=2*Math.PI,he={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},hr=1e-6;class Qs extends h.Controls{constructor(e,t=null){super(e,t),this.state=he.NONE,this.target=new h.Vector3,this.cursor=new h.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:h.MOUSE.ROTATE,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.PAN},this.touches={ONE:h.TOUCH.ROTATE,TWO:h.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 h.Vector3,this._lastQuaternion=new h.Quaternion,this._lastTargetPosition=new h.Vector3,this._quat=new h.Quaternion().setFromUnitVectors(e.up,new h.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new h.Spherical,this._sphericalDelta=new h.Spherical,this._scale=1,this._panOffset=new h.Vector3,this._rotateStart=new h.Vector2,this._rotateEnd=new h.Vector2,this._rotateDelta=new h.Vector2,this._panStart=new h.Vector2,this._panEnd=new h.Vector2,this._panDelta=new h.Vector2,this._dollyStart=new h.Vector2,this._dollyEnd=new h.Vector2,this._dollyDelta=new h.Vector2,this._dollyDirection=new h.Vector3,this._mouse=new h.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=sh.bind(this),this._onPointerDown=rh.bind(this),this._onPointerUp=oh.bind(this),this._onContextMenu=fh.bind(this),this._onMouseWheel=lh.bind(this),this._onKeyDown=uh.bind(this),this._onTouchStart=hh.bind(this),this._onTouchMove=dh.bind(this),this._onMouseDown=ah.bind(this),this._onMouseMove=ch.bind(this),this._interceptControlDown=ph.bind(this),this._interceptControlUp=mh.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(Ks),this.update(),this.state=he.NONE}update(e=null){const t=this.object.position;Fe.copy(t).sub(this.target),Fe.applyQuaternion(this._quat),this._spherical.setFromVector3(Fe),this.autoRotate&&this.state===he.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,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=Ye:n>Math.PI&&(n-=Ye),i<-Math.PI?i+=Ye:i>Math.PI&&(i-=Ye),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,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 o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=s!=this._spherical.radius}if(Fe.setFromSpherical(this._spherical),Fe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Fe),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 s=null;if(this.object.isPerspectiveCamera){const a=Fe.length();s=this._clampDistance(a*this._scale);const c=a-s;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new h.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(),o=c!==this.object.zoom;const d=new h.Vector3(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(a),this.object.updateMatrixWorld(),s=Fe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;s!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position):(li.origin.copy(this.object.position),li.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(li.direction))<ih?this.object.lookAt(this.target):($s.setFromNormalAndCoplanarPoint(this.object.up,this.target),li.intersectPlane($s,this.target))))}else if(this.object.isOrthographicCamera){const s=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>hr||8*(1-this._lastQuaternion.dot(this.object.quaternion))>hr||this._lastTargetPosition.distanceToSquared(this.target)>hr?(this.dispatchEvent(Ks),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Ye/60*this.autoRotateSpeed*e:Ye/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){Fe.setFromMatrixColumn(t,0),Fe.multiplyScalar(-e),this._panOffset.add(Fe)}_panUp(e,t){this.screenSpacePanning===!0?Fe.setFromMatrixColumn(t,1):(Fe.setFromMatrixColumn(t,0),Fe.crossVectors(this.object.up,Fe)),Fe.multiplyScalar(e),this._panOffset.add(Fe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Fe.copy(i).sub(this.target);let o=Fe.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/n.clientHeight,this.object.matrix),this._panUp(2*t*o/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(),i=e-n.left,o=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-(o/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(Ye*this._rotateDelta.x/t.clientHeight),this._rotateUp(Ye*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(Ye*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(-Ye*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(Ye*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(-Ye*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),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_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),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,o=Math.sqrt(n*n+i*i);this._dollyStart.set(0,o)}_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),i=.5*(e.pageX+n.x),o=.5*(e.pageY+n.y);this._rotateEnd.set(i,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Ye*this._rotateDelta.x/t.clientHeight),this._rotateUp(Ye*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),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}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,i=e.pageY-t.y,o=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,o),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 s=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(s,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 h.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 rh(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r)))}function sh(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function oh(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Xs),this.state=he.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 ah(r){let e;switch(r.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 h.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=he.DOLLY;break;case h.MOUSE.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=he.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=he.ROTATE}break;case h.MOUSE.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=he.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=he.PAN}break;default:this.state=he.NONE}this.state!==he.NONE&&this.dispatchEvent(ur)}function ch(r){switch(this.state){case he.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case he.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case he.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function lh(r){this.enabled===!1||this.enableZoom===!1||this.state!==he.NONE||(r.preventDefault(),this.dispatchEvent(ur),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(Xs))}function uh(r){this.enabled!==!1&&this._handleKeyDown(r)}function hh(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case h.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=he.TOUCH_ROTATE;break;case h.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=he.TOUCH_PAN;break;default:this.state=he.NONE}break;case 2:switch(this.touches.TWO){case h.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=he.TOUCH_DOLLY_PAN;break;case h.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=he.TOUCH_DOLLY_ROTATE;break;default:this.state=he.NONE}break;default:this.state=he.NONE}this.state!==he.NONE&&this.dispatchEvent(ur)}function dh(r){switch(this._trackPointer(r),this.state){case he.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case he.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case he.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case he.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=he.NONE}}function fh(r){this.enabled!==!1&&r.preventDefault()}function ph(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function mh(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class gh extends Qs{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:h.MOUSE.PAN,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.ROTATE},this.touches={ONE:h.TOUCH.PAN,TWO:h.TOUCH.DOLLY_ROTATE}}}const oe={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 At=(r=>(r.FRONT="FRONT",r.BACK="BACK",r.RIGHT="RIGHT",r.LEFT="LEFT",r.TOP="TOP",r.BOTTOM="BOTTOM",r))(At||{});new A.Vector3(0,1,0);const wn="rotation-arrows-name",dr="left-rotation-arrow-name",ui="right-rotation-arrow-name",yh="gizmo-group-name",vh=[ui,dr],hi={GIZMO_DISTANCE:8,DEFAULT_UP:new A.Vector3(0,1,0),FORWARD:new A.Vector3(0,0,-1)},fr=r=>hi.FORWARD.clone().applyQuaternion(r),Js=(r,e,t=new A.Vector3)=>t.clone().add(r.multiplyScalar(-e));class xh{constructor(e,t=wn){this.gizmoScene=e,this.gizmoArrowsName=t}syncGizmoWithMain(e,t){e.quaternion.copy(t.quaternion),e.up.copy(t.up);const n=fr(e.quaternion).normalize();e.position.copy(Js(n,hi.GIZMO_DISTANCE)),e.camera.updateMatrixWorld(!0);const i=this.gizmoScene.getObjectByName(this.gizmoArrowsName);i&&i.rotation.copy(e.camera.rotation)}syncMainWithGizmo(e,t,n){const i=n.target.clone(),o=e.position.distanceTo(i),s=e.camera instanceof A.PerspectiveCamera;n instanceof gh&&!s?this.syncMapControls(e,t,i,o):this.syncOrbitControls(e,t,i,o),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,i){const o=e.position.y-n.y,s=fr(t.quaternion);s.y=0,s.normalize();const a=n.clone();a.y+=o,a.add(s.multiplyScalar(-i)),e.position.copy(a),e.up.copy(hi.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,i){const o=fr(t.quaternion),s=hi.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=Js(o,i,n);e.position.copy(a),e.up.copy(s),e.camera.lookAt(n)}}const Hs=r=>new xh(r),eo=(r,e,t)=>{Hs(t).syncGizmoWithMain({camera:r,position:r.position,quaternion:r.quaternion,up:r.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up})},bh=(r,e,t)=>{Hs(e.userData.scene).syncMainWithGizmo({camera:r,position:r.position,quaternion:r.quaternion,up:r.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up},t)},wh=()=>{try{const r=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(r.getContext("webgl")||r.getContext("experimental-webgl")))}catch{return!1}},_h=()=>wh()?new A.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),Sh=r=>{const e=new A.AmbientLight(16777215,1);r.add(e);const t=new A.DirectionalLight(16777215,1);t.position.set(5,10,5),r.add(t);const n=new A.DirectionalLight(16777215,1);n.position.set(-5,-10,5),r.add(n);const i=new A.PointLight(16777215,1,100);i.position.set(0,0,5),r.add(i),t.castShadow=!1,n.castShadow=!1,i.castShadow=!1};class Th{static createTextTexture(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=oe.CANVAS_SIZE,t.height=oe.CANVAS_SIZE,n&&(n.clearRect(0,0,t.width,t.height),n.font=`${oe.FONT_SIZE} Arial`,n.fillStyle=oe.TEXT_COLOR,n.textAlign=oe.TEXT_ALIGN,n.textBaseline=oe.TEXT_BASELINE,n.fillText(e,t.width/2,t.height/2));const i=new A.CanvasTexture(t);return i.needsUpdate=!0,i}}class di{static createWireframe([e,t,n]){const i=new A.BoxGeometry(e,t,n),o=new A.EdgesGeometry(i),s=new A.LineBasicMaterial({color:oe.LINE_COLOR}),a=new A.LineSegments(o,s);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const i=oe.CUBE_SIZE-oe.EDGE_SECTION_SIZE,o={x:oe.EDGE_SECTION_SIZE,y:oe.EDGE_SECTION_SIZE,z:oe.EDGE_SECTION_SIZE};o[t]=i;const s=new A.BoxGeometry(o.x,o.y,o.z),a=new A.MeshStandardMaterial({color:oe.EDGE_COLOR}),c=new A.Mesh(s,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new A.BoxGeometry(oe.EDGE_SECTION_SIZE,oe.EDGE_SECTION_SIZE,oe.EDGE_SECTION_SIZE),i=new A.MeshStandardMaterial({color:oe.CORNER_COLOR}),o=new A.Mesh(n,i);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,n){const i=new A.Group,o=new A.BoxGeometry(oe.CUBE_SIZE-oe.EDGE_SECTION_SIZE,oe.CUBE_SIZE-oe.EDGE_SECTION_SIZE,oe.FACE_THICKNESS),s=new A.MeshStandardMaterial({color:oe.FACE_COLOR}),a=new A.Mesh(o,s);a.name=`Face Box ${n}`,i.add(a);const c=new A.PlaneGeometry(oe.CUBE_SIZE-oe.EDGE_SECTION_SIZE,oe.CUBE_SIZE-oe.EDGE_SECTION_SIZE),d=new A.MeshStandardMaterial({map:Th.createTextTexture(n),transparent:!0,depthWrite:!1}),f=new A.Mesh(c,d);return f.position.set(0,0,oe.FACE_THICKNESS/2+.01),i.add(f),i.position.copy(e),i.rotation.copy(t),i}}const Mh=(r,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(r,t.width/2,t.height/2);const i=new A.CanvasTexture(t),o=new A.SpriteMaterial({map:i}),s=new A.Sprite(o);return s.scale.set(.5,.5,.5),s};class Ah{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 At.BACK:return new A.Euler(0,Math.PI,0);case At.RIGHT:return new A.Euler(0,-Math.PI/2,0);case At.LEFT:return new A.Euler(0,Math.PI/2,0);case At.TOP:return new A.Euler(Math.PI/2,0,0);case At.BOTTOM:return new A.Euler(-Math.PI/2,0,0);case At.FRONT:default:return new A.Euler(0,0,0)}}createWireframe(){const e=oe.CUBE_SIZE+oe.EDGE_SECTION_SIZE,t=di.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,n){const i=di.createEdgeBox(e,t,n);return i.userData.gizmoCube=this,i}createCornerCube(e,t){const n=di.createCornerCube(e,t);return n.userData.gizmoCube=this,n}createFace(e,t,n){const i=di.createFace(e,t,n),o=i.getObjectByName(`Face Box ${n}`);return o.userData.gizmoCube=this,i}createEdges(e){const t=oe.CUBE_SIZE/2;[{axis:"x",pos:new A.Vector3(0,t,-t)},{axis:"x",pos:new A.Vector3(0,t,t)},{axis:"x",pos:new A.Vector3(0,-t,-t)},{axis:"x",pos:new A.Vector3(0,-t,t)},{axis:"y",pos:new A.Vector3(t,0,-t)},{axis:"y",pos:new A.Vector3(t,0,t)},{axis:"y",pos:new A.Vector3(-t,0,-t)},{axis:"y",pos:new A.Vector3(-t,0,t)},{axis:"z",pos:new A.Vector3(t,t,0)},{axis:"z",pos:new A.Vector3(t,-t,0)},{axis:"z",pos:new A.Vector3(-t,t,0)},{axis:"z",pos:new A.Vector3(-t,-t,0)}].forEach(({axis:n,pos:i},o)=>{const s=this.createEdgeBox(i,n,o+1);e.add(s)})}createCorners(e){const t=oe.CUBE_SIZE/2;[new A.Vector3(-t,-t,-t),new A.Vector3(-t,-t,t),new A.Vector3(-t,t,-t),new A.Vector3(-t,t,t),new A.Vector3(t,-t,-t),new A.Vector3(t,-t,t),new A.Vector3(t,t,-t),new A.Vector3(t,t,t)].forEach((n,i)=>{const o=this.createCornerCube(n,i+1);e.add(o)})}createFaces(e){const t=oe.CUBE_SIZE/2;[{pos:new A.Vector3(0,0,t),rotation:new A.Euler(0,0,0),label:"FRONT"},{pos:new A.Vector3(0,0,-t),rotation:new A.Euler(0,Math.PI,0),label:"BACK"},{pos:new A.Vector3(t,0,0),rotation:new A.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new A.Vector3(-t,0,0),rotation:new A.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new A.Vector3(0,t,0),rotation:new A.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new A.Vector3(0,-t,0),rotation:new A.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:i,label:o})=>{const s=this.createFace(n,i,o);e.add(s)})}createAxis(e){const{color:t,direction:n,length:i,origin:o,lineWidth:s,label:a}=e,c=new A.Group,d=s/2,f=new A.CylinderGeometry(d,d,i,32),u=new A.MeshBasicMaterial({color:t}),l=new A.Mesh(f,u);if(l.position.copy(o).add(n.clone().multiplyScalar(i/2)),!n.equals(new A.Vector3(0,1,0))){const y=new A.Vector3(0,1,0).cross(n).normalize(),b=Math.acos(new A.Vector3(0,1,0).dot(n));l.setRotationFromAxisAngle(y,b)}c.add(l);const g=Mh(a,t);return g.position.copy(o).add(n.clone().multiplyScalar(i+.1)),c.add(g),c}createCoordinateAxes(){const e=new A.Group,t=oe.CUBE_SIZE,n=oe.EDGE_SECTION_SIZE,i=-1.075,o=a=>{const c=new A.Vector3(1,1,1);return new A.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},s=t+1.25*n;return[{color:16711680,direction:new A.Vector3(1,0,0),length:s,origin:o(i),lineWidth:.04,label:"X"},{color:65280,direction:new A.Vector3(0,1,0),length:s,origin:o(i),lineWidth:.04,label:"Y"},{color:255,direction:new A.Vector3(0,0,1),length:s,origin:o(i),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new A.Group;e.name=yh;const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const n=this.createCoordinateAxes();e.add(n);const i=this.getInitialRotation();return e.setRotationFromEuler(i),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof A.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 A.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new A.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class Ih{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:i,options:o}=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=i,this.options=o,this.gizmoControls=new Qs(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 Ah({initialFace:((e=this.options)==null?void 0:e.initialFace)??At.FRONT}).create();this.gizmoScene.add(t),Sh(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(wn);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 Ch=(r,e)=>{let t;return function(...n){t||(r.apply(this,n),t=!0,setTimeout(()=>t=!1,e))}};function to(r,e,t){if(!e)return;const n=e.domElement.getBoundingClientRect();t.x=(r.clientX-n.left)/n.width*2-1,t.y=-((r.clientY-n.top)/n.height)*2+1}const no=(r,e,t,n)=>(n.setFromCamera(r,e),n.intersectObjects(t.children,!0)),io=r=>{var e;const t=["Wireframe",""];return((e=r.find(n=>!t.includes(n.object.name)))==null?void 0:e.object)||null};function Ph(r,e,t,n){if(!e||!t)return null;const i=no(r,e,t,n);return io(i)}function Dh(r,e){const t=r==null?void 0:r.userData.gizmoCube;if(r&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const Fh={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},Rh={size:.2,depth:.1,heightRatio:1.4,segments:1};class Oh{constructor(e={}){this.config={...Fh,...e},this.material=new A.MeshBasicMaterial({color:this.config.color})}create(){const e=new A.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=wn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new A.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new A.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},(i,o)=>{const s=o/this.config.numPoints,a=n+t*s,c=this.config.radius*Math.sin(a),d=this.config.radius*Math.cos(a);return new A.Vector3(c,d,0)})}createTubes([e,t]){const n=(i,o)=>{const s=new A.TubeGeometry(i,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new A.Mesh(s,this.material);return a.name=o,a};return[n(e,dr),n(t,ui)]}createArrowHeads([e,t]){const{size:n,depth:i,heightRatio:o,segments:s}=Rh,a=this.createArrowShape(n,o),c=new A.ExtrudeGeometry(a,{steps:s,depth:i,bevelEnabled:!1}).center(),d=(f,u,l)=>{const g=new A.Mesh(c,this.material);return g.position.copy(f),g.rotation.z=u,g.name=l,g};return[d(e.getPoint(0),this.calculateArrowRotation(e.getTangent(0))+Math.PI/2,dr),d(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,ui)]}createArrowShape(e,t){return new A.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 Lh=r=>{const e=r.rotation,t=.01,n=Math.PI,i=(Math.abs(e.x)%(2*n)+2*n)%(2*n),o=(Math.abs(e.y)%(2*n)+2*n)%(2*n),s=Math.abs(i-n/2)<t||Math.abs(i-3*n/2)<t||Math.abs(o-n/2)<t||Math.abs(o-3*n/2)<t,a=(Math.abs(i)<t||Math.abs(i-n)<t)&&(Math.abs(o)<t||Math.abs(o-n)<t);return!(s||a)},Nh=25,kh=200;function Bh({gizmoRenderer:r,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:i}){const o=ne.useRef(null),s=ne.useRef(null),a=ne.useRef(new A.Raycaster).current,c=ne.useRef(new A.Vector2).current,d=ne.useCallback(()=>{const b=e.getObjectByName(wn),m=Lh(t);if(b&&m){e.remove(b);return}if(b||m)return;const _=new Oh().create();_.rotation.copy(t.rotation),e.add(_)},[e,t]),f=ne.useCallback(()=>{const b=e.getObjectByName(wn);b&&e.remove(b)},[e]),u=ne.useCallback(Ch(b=>{if(!i.current||!r)return;to(b,r,c);const m=no(c,t,e,a),_=io(m);_!=null&&_.userData.gizmoCube?_.userData.gizmoCube.highlightObject(_):e.traverse(x=>{x.userData.gizmoCube&&x.userData.gizmoCube.highlightObject(null)}),m.length>0?d():f()},1e3/Nh),[i,r,t,e,a,c,d,f]),l=ne.useCallback(b=>{o.current=Date.now(),s.current={x:b.clientX,y:b.clientY}},[]),g=ne.useCallback(b=>{var m;const _=b.name===ui?1:-1,x=90*Math.PI/180,w=new A.Vector3(0,0,0),S=_*x,M=new A.Matrix4;M.makeRotationZ(S),t.up.applyMatrix4(M),t.lookAt(w),(m=i.current)==null||m.gizmoControls.update()},[t,i]),y=ne.useCallback(b=>{if((o.current?Date.now()-o.current:0)<kh){to(b,r,c);const m=Ph(c,t,e,a);m!=null&&m.name&&vh.includes(m.name)?g(m):Dh(m,n)}o.current=null,s.current=null},[g,n,r,t,e,a,c]);return{onMouseDown:l,onMouseMove:u,onMouseUp:y,onMouseLeave:f}}const zh=({camera:r,controls:e,className:t,render:n,options:i})=>{const o=ne.useRef(null),s=ne.useRef(new A.Scene).current,[a]=ne.useState(()=>_h()),c=30,d=1,f=.1,u=10,l=new A.PerspectiveCamera(c,d,f,u),g=ne.useRef(l).current,y=ne.useRef(null),b=ne.useCallback(()=>{a&&(n(),a.render(s,g))},[n,a,s,g]),m=ne.useCallback(M=>{if(!r||!e)return;const I=r.position.length(),C=M.clone().multiplyScalar(I),D=400,L=new A.Matrix4;L.lookAt(C,new A.Vector3(0,0,0),new A.Vector3(0,1,0));const R=new A.Quaternion;R.setFromRotationMatrix(L),r.quaternion.copy(R),nh(r,e,r.position.clone(),C,D,b),r.up.set(0,1,0),r.lookAt(new A.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[r,e,b,s]),{onMouseDown:_,onMouseMove:x,onMouseUp:w,onMouseLeave:S}=Bh({gizmoRenderer:a,gizmoScene:s,gizmoCamera:g,alignCameraWithVector:m,gizmoControlRef:y});return ne.useEffect(()=>{const M=o.current;if(!M||!r||!e||!a)return;y.current&&y.current.dispose();const I={gizmoDiv:M,gizmoScene:s,gizmoRenderer:a,gizmoCamera:g},C={mainCamera:r,mainControls:e,renderGizmo:b},D={syncGizmoCameraWithMain:eo,syncMainCameraWithGizmo:bh};return y.current=new Ih({gizmoParams:I,mainParams:C,syncFunctions:D,options:i}),M.addEventListener("mousedown",_),M.addEventListener("mousemove",x),M.addEventListener("mouseup",w),M.addEventListener("mouseleave",S),()=>{y.current&&(y.current.dispose(),y.current=null),M.removeEventListener("mousedown",_),M.removeEventListener("mousemove",x),M.removeEventListener("mouseup",w),M.removeEventListener("mouseleave",S)}},[r,e,b,x,_,w]),ne.useEffect(()=>{r&&(eo(g,r,s),b())},[r,b]),Ce.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},Uh=({camera:r,controls:e,render:t,placement:n="top-right",size:i=128})=>{const o=ne.useRef(null);if(ne.useEffect(()=>{if(!o.current)return;const a=o.current;a.style.position="absolute",a.style.width=`${i}px`,a.style.height=`${i}px`,a.style.zIndex="1000",a.style.top="auto",a.style.bottom="auto",a.style.left="auto",a.style.right="auto";const c="10px";switch(n){case"top-left":a.style.top=c,a.style.left=c;break;case"top-right":a.style.top=c,a.style.right=c;break;case"bottom-left":a.style.bottom=c,a.style.left=c;break;case"bottom-right":a.style.bottom=c,a.style.right=c;break}},[n,i]),!r||!e)return null;const s=e;return Ce.jsx("div",{ref:o,className:"viewer-gizmo-container",children:Ce.jsx(zh,{camera:r,controls:s,render:t})})};class Eh extends ne.Component{constructor(e){super(e),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:Ce.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:Ce.jsxs("div",{children:[Ce.jsx("h3",{children:"Error Loading 3D Viewer"}),Ce.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"})]})}):this.props.children}}class ro{static toThreeObject(e){if("getThreeObject"in e&&typeof e.getThreeObject=="function")return e.getThreeObject();if(e instanceof A.Object3D)return e;const t=new A.Object3D;return t.position.set(e.position.x,e.position.y,e.position.z),t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),t.scale.set(e.scale.x,e.scale.y,e.scale.z),t}static toThreeCamera(e){return"getThreeCamera"in e&&typeof e.getThreeCamera=="function"?e.getThreeCamera():e instanceof A.Camera?e:new A.PerspectiveCamera}static toThreeControls(e){return"getThreeControls"in e&&typeof e.getThreeControls=="function"?e.getThreeControls():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)}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}const so=ne.forwardRef(({object:r,options:e={}},t)=>{var S,M;const n=ne.useRef(null),{viewer:i,isInitialized:o}=Qu(n,e),s=ne.useRef(new In),a=ne.useRef(void 0),c=ne.useMemo(()=>{if(typeof r=="string")return r;if(r)return`object-${r.uuid||"no-uuid"}`},[r]);ne.useMemo(()=>{a.current=r},[c,r]),ne.useEffect(()=>{if(!i||!o||!a.current)return;const I=typeof a.current=="string"?a.current:new Ee(a.current);i.loadModel(I).then(C=>{C.ok||console.error("Failed to load model:",C.error)})},[i,o,c]);const d=ne.useMemo(()=>({"model:loaded":I=>s.current.emit("model:loaded",ro.convertModelLoaded(I)),"model:error":I=>s.current.emit("model:error",I),"render:complete":I=>s.current.emit("render:complete",I),"controls:change":I=>s.current.emit("controls:change",ro.convertControlsChange(I)),error:I=>s.current.emit("error",I)}),[]);Ju(i,d);const f=ne.useCallback(I=>{if(I&&typeof I=="object"){const C=I;if(typeof C.getThreeScene=="function")return C.getThreeScene()}return null},[]),u=ne.useCallback(I=>{if(I&&typeof I=="object"){const C=I;if(typeof C.getThreeCamera=="function")return C.getThreeCamera()}return null},[]),l=ne.useCallback(I=>{if(I&&typeof I=="object"){const C=I;if(typeof C.getThreeRenderer=="function")return C.getThreeRenderer()}return null},[]),g=ne.useCallback(I=>{if(I&&typeof I=="object"){const C=I;if(typeof C.getThreeControls=="function")return C.getThreeControls()}return null},[]),y=i?u(i.camera):null,b=i?g(i.controls):null,m=i?l(i.renderer):null,_=ne.useCallback(()=>{if(m&&i){const I=i;I.renderLoopManager&&typeof I.renderLoopManager.requestRender=="function"&&I.renderLoopManager.requestRender()}},[i,m]),x=((S=e.helpers)==null?void 0:S.gizmo)!==void 0&&e.helpers.gizmo!==!1,w=typeof((M=e.helpers)==null?void 0:M.gizmo)=="object"?e.helpers.gizmo:{};return ne.useImperativeHandle(t,()=>({scene:i?f(i.scene):null,camera:y,renderer:m,controls:b,events:s.current}),[i,y,m,b,f]),Ce.jsx(Eh,{children:Ce.jsx(Hu,{viewer:i,canvasRef:n,children:Ce.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Ce.jsx(th,{}),x&&o&&y&&b&&Ce.jsx(Uh,{camera:y,controls:b,render:_,placement:w.placement,size:w.size})]})})})});so.displayName="SimpleViewer";const oo=ne.forwardRef((r,e)=>Ce.jsx(so,{ref:e,...r}));oo.displayName="SimpleViewer",nt.SimpleViewer=oo,nt.TypedEventEmitter=In,nt.defaultOptions=Zs,Object.defineProperty(nt,Symbol.toStringTag,{value:"Module"})});
|