softbox 4.16.1 → 4.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ThreePathTracingService-CK3zD4Qj.js → ThreePathTracingService-Cf8e9Msc.js} +1 -1
- package/dist/{ThreePathTracingService-VOgJGtMH.cjs → ThreePathTracingService-DvBQToys.cjs} +1 -1
- package/dist/{index-BWjJNKzq.js → index-1jWUObtn.js} +2110 -2056
- package/dist/index-BlwMVqol.cjs +29 -0
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/simple-viewer.cjs +1 -1
- package/dist/simple-viewer.es.js +1 -1
- package/package.json +1 -1
- package/dist/index-BqbKpEQh.cjs +0 -29
package/dist/index-BqbKpEQh.cjs
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
"use strict";var Jo=Object.create;var Zi=Object.defineProperty;var ea=Object.getOwnPropertyDescriptor;var ta=Object.getOwnPropertyNames;var na=Object.getPrototypeOf,sa=Object.prototype.hasOwnProperty;var ia=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ta(e))!sa.call(i,s)&&s!==t&&Zi(i,s,{get:()=>e[s],enumerable:!(n=ea(e,s))||n.enumerable});return i};var Os=(i,e,t)=>(t=i!=null?Jo(na(i)):{},ia(e||!i||!i.__esModule?Zi(t,"default",{value:i,enumerable:!0}):t,i));const ge=require("react/jsx-runtime"),se=require("react"),p=require("three");function ra(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const y=ra(p);class Z extends Error{constructor(e,t,n){super(e),this.code=t,this.context=n,this.name="ThreeViewerError",this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,Z)}static fromError(e,t,n){if(e instanceof Z)return e;const s=e instanceof Error?e.message:String(e),o={...n,originalError:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e};return new Z(s,t,o)}}var K=(i=>(i.SCENE_INIT_FAILED="SCENE_INIT_FAILED",i.RENDERER_INIT_FAILED="RENDERER_INIT_FAILED",i.RENDERER_NOT_INITIALIZED="RENDERER_NOT_INITIALIZED",i.CAMERA_INIT_FAILED="CAMERA_INIT_FAILED",i.WEBGL_NOT_SUPPORTED="WEBGL_NOT_SUPPORTED",i.INITIALIZATION_FAILED="INITIALIZATION_FAILED",i.PATH_TRACING_INIT_FAILED="PATH_TRACING_INIT_FAILED",i.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",i.TEXTURE_LOAD_FAILED="TEXTURE_LOAD_FAILED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.UNSUPPORTED_FORMAT="UNSUPPORTED_FORMAT",i.INVALID_CONFIGURATION="INVALID_CONFIGURATION",i.RENDER_ERROR="RENDER_ERROR",i.RENDER_FAILED="RENDER_FAILED",i.SCENE_OPERATION_FAILED="SCENE_OPERATION_FAILED",i.COMPONENT_NOT_MOUNTED="COMPONENT_NOT_MOUNTED",i.INVALID_STATE="INVALID_STATE",i.INVALID_PARAMETER="INVALID_PARAMETER",i.OPERATION_FAILED="OPERATION_FAILED",i.UNKNOWN="UNKNOWN",i))(K||{});const N={ok(i){return{ok:!0,value:i}},err(i){return{ok:!1,error:i}},wrap(i){try{return N.ok(i())}catch(e){return N.err(e instanceof Z?e:new Z(String(e),K.UNKNOWN,{originalError:e}))}}};class bs{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);return n&&n.add(t),()=>{var s;(s=this.listeners.get(e))==null||s.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(s=>{try{s(t)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}})}once(e,t){const n=this.on(e,s=>{n(),t(s)});return n}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t;return((t=this.listeners.get(e))==null?void 0:t.size)||0}off(e,t){var n;(n=this.listeners.get(e))==null||n.delete(t)}removeListener(e,t){this.off(e,t)}}const ii=300,Ds={meters:1,centimeters:.01,millimeters:.001,feet:.3048,inches:.0254},oa="softbox-units-scale";function Dr(i){const e=i??"meters";if(!Object.prototype.hasOwnProperty.call(Ds,e))throw new Z(`Unknown units '${String(e)}'. Valid values: ${Object.keys(Ds).join(", ")}`,K.INVALID_PARAMETER);return Ds[e]}const Ki="#1a1a1f",Ns=i=>{if(Array.isArray(i))return i;if(i&&typeof i=="object")return[i.x,i.y,i.z]},ks=i=>i!==void 0?String(i):void 0;class aa{configureScene(e,t,n){var a,c,h;if(n.helpers){const d={grid:n.helpers.grid,axes:n.helpers.axes,gridColor:"#AAAAAA"},u=t.addHelpers(e,d);u.ok||console.warn("Failed to add helpers:",u.error)}const s=n.lighting;if(s){const d={ambient:s.ambientLight?{color:String(s.ambientLight.color),intensity:s.ambientLight.intensity}:void 0,hemisphere:s.hemisphereLight?{skyColor:String(s.hemisphereLight.skyColor),groundColor:String(s.hemisphereLight.groundColor),intensity:s.hemisphereLight.intensity}:void 0,directional:s.directionalLight?{color:ks(s.directionalLight.color),intensity:s.directionalLight.intensity,position:Ns(s.directionalLight.position),castShadow:s.directionalLight.castShadow,shadow:s.directionalLight.shadow}:void 0,fill:s.fillLight?{color:ks(s.fillLight.color),intensity:s.fillLight.intensity,position:Ns(s.fillLight.position)}:void 0,rim:s.rimLight?{color:ks(s.rimLight.color),intensity:s.rimLight.intensity,position:Ns(s.rimLight.position)}:void 0},u=t.addLighting(e,d);u.ok||console.warn("Failed to add lighting:",u.error)}const o=(a=n.environment)==null?void 0:a.url,r=(((c=n.helpers)==null?void 0:c.studioEnvironment)??!1)&&(((h=n.helpers)==null?void 0:h.darkStudioMode)??!1);if(n.backgroundColor&&!o&&!r){const d=String(n.backgroundColor),u=n.backgroundColorEdge,f=u!==void 0?{topColor:d,bottomColor:String(u),radial:!0}:{topColor:d,bottomColor:d},m=t.createGradientBackground(e,f);m.ok||console.warn("Failed to set background:",m.error)}}async configureEnvironment(e,t,n,s,o,r){var d,u,f,m,E,b;const a=await t.initialize({renderer:s,autoDispose:!0});if(r())return;a.ok||console.warn("Failed to initialize environment service:",a.error);const c={backgroundBlurriness:(d=o.environment)==null?void 0:d.backgroundBlurriness,backgroundIntensity:(u=o.environment)==null?void 0:u.backgroundIntensity,environmentIntensity:(f=o.environment)==null?void 0:f.environmentIntensity},h=(m=o.environment)==null?void 0:m.url;if(h){const w=await t.loadEnvironmentMap(h);if(r())return;w.ok?t.applyToScene(e,w.value,c):console.warn("Failed to load environment map:",w.error)}else if((E=o.helpers)!=null&&E.studioEnvironment){const w=t.createStudioEnvironment();if(w.ok){if(t.applyToScene(e,w.value,{...c,setBackground:!1}),(b=o.helpers)!=null&&b.darkStudioMode&&n){const A=n.createGradientBackground(e,{topColor:Ki,bottomColor:Ki});A.ok||console.warn("Failed to set dark studio background:",A.error)}}else console.warn("Failed to create studio environment:",w.error)}}}class ca{constructor(e={}){this.animationFrameId=null,this.lastRenderTime=0,this.idleTimeout=null,this.isIdle=!1,this.needsRender=!0,this.continuousRenderingEnabled=!1,this.continuousReasons=new Set,this.alwaysRender=!1,this.enableIdleDetection=e.enableIdleDetection??!0,this.idleDelay=e.idleDelay??1e3,this.targetFPS=e.targetFPS??60,this.frameInterval=1e3/this.targetFPS,this.enableFrameRateLimiting=e.enableFrameRateLimiting??!0,this.alwaysRender=e.alwaysRender??!1,this.lastRenderTime=performance.now()}requestRender(){this.needsRender=!0,this.wakeUp()}requireContinuous(e){this.continuousReasons.add(e),this.continuousRenderingEnabled=!0,this.wakeUp()}releaseContinuous(e){this.continuousReasons.delete(e),this.continuousRenderingEnabled=this.continuousReasons.size>0}hasContinuousDemand(){return this.continuousReasons.size>0}setAlwaysRender(e){this.alwaysRender=e,e&&this.wakeUp()}wakeUp(){this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1}start(e){if(this.animationFrameId!==null)return;const t=n=>{if(this.animationFrameId===null)return;const s=n-this.lastRenderTime;if(this.enableFrameRateLimiting&&s<this.frameInterval){this.animationFrameId=requestAnimationFrame(t);return}(this.alwaysRender||this.needsRender||this.continuousRenderingEnabled)&&(e(s),this.lastRenderTime=n,this.needsRender=!1),this.enableIdleDetection&&!this.alwaysRender&&(this.continuousRenderingEnabled||this.needsRender?this.wakeUp():this.idleTimeout===null&&!this.isIdle&&(this.idleTimeout=window.setTimeout(()=>{this.isIdle=!0},this.idleDelay))),this.alwaysRender||!this.enableIdleDetection||!this.isIdle||this.continuousRenderingEnabled||this.needsRender?this.animationFrameId=requestAnimationFrame(t):this.animationFrameId=null};this.animationFrameId=requestAnimationFrame(t)}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.idleTimeout!==null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.isIdle=!1,this.needsRender=!1,this.continuousRenderingEnabled=!1,this.continuousReasons.clear(),this.alwaysRender=!1}isRunning(){return this.animationFrameId!==null}getIsIdle(){return this.isIdle}getNeedsRender(){return this.needsRender||this.continuousRenderingEnabled||this.alwaysRender}}function Gn(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function on(i,e){if(!Gn(i)||!Gn(e))return e===void 0?i:e;const t=e,n={...i};for(const s of Object.keys(t)){const o=t[s];if(o===void 0)continue;const r=n[s];n[s]=Gn(r)&&Gn(o)?on(r,o):o}return n}const la=i=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>setTimeout(()=>requestAnimationFrame(()=>setTimeout(i,0)),0)):setTimeout(i,0)};class Nr{static serialize(e,t,n,s){const o=t.position,r=n.target||{x:0,y:0,z:0};return{modelUrl:e,cameraPosition:{x:o.x,y:o.y,z:o.z},cameraTarget:{x:r.x,y:r.y,z:r.z},controlsTarget:{x:r.x,y:r.y,z:r.z},rendererSize:{width:s.clientWidth,height:s.clientHeight}}}static async restore(e,t,n,s){t.position.set(e.cameraPosition.x,e.cameraPosition.y,e.cameraPosition.z),t.lookAt({x:e.cameraTarget.x,y:e.cameraTarget.y,z:e.cameraTarget.z,set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),n.target&&n.target.set(e.controlsTarget.x,e.controlsTarget.y,e.controlsTarget.z),n.update&&n.update(),e.modelUrl&&s&&await s(e.modelUrl)}}function ri(i,e){i.type==="perspective"&&"aspect"in i&&(i.aspect=e),i.updateProjectionMatrix()}class yt{constructor(e={}){this.data=Object.freeze({status:"idle",currentModel:null,error:null,isInitialized:!1,loadProgress:0,renderInfo:{frameCount:0,fps:0,lastRenderTime:0,averageRenderTime:0},...e})}get status(){return this.data.status}get currentModel(){return this.data.currentModel}get error(){return this.data.error}get isInitialized(){return this.data.isInitialized}get loadProgress(){return this.data.loadProgress}get renderInfo(){return this.data.renderInfo}setInitialized(){return new yt({...this.data,isInitialized:!0,status:"idle"})}startLoading(){return new yt({...this.data,status:"loading",loadProgress:0,error:null})}updateLoadProgress(e){return new yt({...this.data,loadProgress:Math.min(Math.max(0,e),1)})}setLoaded(e){return new yt({...this.data,status:"loaded",currentModel:e,loadProgress:1,error:null})}setError(e){return new yt({...this.data,status:"error",error:e,loadProgress:0})}startRendering(){return new yt({...this.data,status:"rendering"})}updateRenderInfo(e){return new yt({...this.data,renderInfo:{...this.data.renderInfo,...e}})}dispose(){return new yt({...this.data,status:"disposed",currentModel:null})}canLoad(){return this.data.isInitialized&&(this.data.status==="idle"||this.data.status==="loaded"||this.data.status==="error"||this.data.status==="rendering")}canRender(){return this.data.isInitialized&&this.data.status==="loaded"&&this.data.currentModel!==null}isLoading(){return this.data.status==="loading"}hasError(){return this.data.status==="error"&&this.data.error!==null}toJSON(){return{...this.data}}}class ha{constructor(){this.state=new yt,this.stateChangeCallbacks=new Set}getState(){return this.state}setInitialized(){this.updateState(this.state.setInitialized())}startLoading(){this.updateState(this.state.startLoading())}setLoaded(e){this.updateState(this.state.setLoaded(e))}setError(e){this.updateState(this.state.setError(e))}startRendering(){this.updateState(this.state.startRendering())}updateRenderInfo(e){this.updateState(this.state.updateRenderInfo(e))}setDisposed(){this.updateState(this.state.dispose())}canLoad(){return this.state.canLoad()}isInitialized(){return this.state.isInitialized}getStatus(){return this.state.status}getCurrentModel(){return this.state.currentModel}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>{this.stateChangeCallbacks.delete(e)}}clearCallbacks(){this.stateChangeCallbacks.clear()}updateState(e){this.state=e,this.stateChangeCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("Error in state change callback:",n)}})}}function kr(i){const e=i.toDataURL("image/png");return!e||e==="data:,"?null:e}class ua{constructor(e){this.screenshotElement=null,this.isShowingScreenshot=!1,this.renderer=e.renderer,this.onRestore=e.onRestore}isActive(){return this.isShowingScreenshot}captureAndReplace(e,t,n,s){if(this.isShowingScreenshot)return;const o=this.renderer.getDomElement(),r=kr(o);if(!r){console.warn("[ScreenshotManager] Screenshot capture produced no image, keeping live scene");return}const a=document.createElement("img");a.src=r,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=Nr.serialize(n,e,t,o),o.style.display="none",c.appendChild(a),this.screenshotElement=a,this.isShowingScreenshot=!0;const h=()=>{this.restore()};a.addEventListener("mousedown",h),a.addEventListener("touchstart",h);const d=()=>{this.isShowingScreenshot&&this.restore()};window.addEventListener("resize",d),this.screenshotResizeHandler=d,s==null||s()}}async restore(){if(!this.isShowingScreenshot||!this.screenshotElement)return;const e=this.renderer.getDomElement(),t=this.screenshotElement.parentElement;t&&(this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),t.removeChild(this.screenshotElement),e.style.display="",this.screenshotElement=null,this.isShowingScreenshot=!1,this.onRestore&&await this.onRestore())}getSerializedState(){return this.serializedSceneState}dispose(){this.screenshotResizeHandler&&(window.removeEventListener("resize",this.screenshotResizeHandler),this.screenshotResizeHandler=void 0),this.screenshotElement&&this.screenshotElement.parentElement&&this.screenshotElement.parentElement.removeChild(this.screenshotElement),this.isShowingScreenshot&&(this.renderer.getDomElement().style.display=""),this.screenshotElement=null,this.isShowingScreenshot=!1,this.serializedSceneState=void 0}}class da{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,this.floorAlignment=e.floorAlignment??!0,this.unitsScaleToMeters=e.unitsScaleToMeters??1}getCurrentModel(){return this.currentModel}getLastModelUrl(){return this.lastModelUrl}async loadModel(e,t){const n=performance.now();try{let s;if(typeof e=="string"){this.lastModelUrl=e,t.emit("model:loading",{url:e});const a=await this.modelLoader.load(e,(c,h)=>{t.emit("model:progress",{url:e,loaded:c,total:h})});if(!a.ok)throw a.error;s=a.value.scene}else s=e;if(this.unitsScaleToMeters!==1){if(!this.sceneSetupService)throw new Z("A units conversion is configured but no scene setup service is available to apply it",K.INVALID_PARAMETER);const a=this.sceneSetupService.wrapInUnitsScaleGroup(s,this.unitsScaleToMeters);if(!a.ok)throw a.error;s=a.value}this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel));const o=this.scene.add(s);if(!o.ok)throw o.error;if(this.floorAlignment&&this.floorAlignmentService){const a=this.floorAlignmentService.alignToFloor(s);a.ok||console.warn("Failed to align model to floor:",a.error)}if(s.traverse(a=>{"castShadow"in a&&"receiveShadow"in a&&(a.castShadow=!0,a.receiveShadow=!0)}),this.currentModel=s,this.sceneSetupService){const a=this.sceneSetupService.addDynamicGrid(this.scene,s,2);if(a.ok||console.warn("Failed to add dynamic grid:",a.error),this.floorAlignment){const d=this.sceneSetupService.snapObjectToFloor(this.scene,s);d.ok||console.warn("Failed to snap object to floor:",d.error)}const c=this.sceneSetupService.fitShadowCameraToObject(this.scene,s);c.ok||console.warn("Failed to fit shadow camera to object:",c.error);const h=this.sceneSetupService.resetContactShadow(this.scene);h.ok||console.warn("Failed to reset the contact shadow:",h.error)}if(this.autoFitToObject&&this.sceneSetupService){const a=this.sceneSetupService.fitCameraToObject(s,this.camera,this.controls);a.ok||console.warn("Failed to fit camera to object:",a.error)}const r=performance.now()-n;return t.emit("model:loaded",{model:s,loadTime:r}),N.ok(s)}catch(s){const o=s instanceof Z?s:new Z("Failed to load model",K.MODEL_LOAD_FAILED,{originalError:s,source:e});return t.emit("model:error",{error:o,url:typeof e=="string"?e:void 0}),N.err(o)}}disposeCurrentModel(){this.currentModel&&(this.scene.remove(this.currentModel),this.disposeObject(this.currentModel),this.currentModel=null)}disposeObject(e){e.dispose()}dispose(){var e,t;this.disposeCurrentModel(),(t=(e=this.modelLoader).dispose)==null||t.call(e),this.lastModelUrl=void 0}}class fa{constructor(e){this.scene=e.scene,this.pathTracingService=e.pathTracingService,this.environmentService=e.environmentService}updateServices(e){e.pathTracingService&&(this.pathTracingService=e.pathTracingService),e.environmentService&&(this.environmentService=e.environmentService)}disposeSceneResources(e=!1){this.scene.disposeContents({keepBackgrounds:!0}),this.triggerGarbageCollection()}disposeServices(){this.pathTracingService&&(this.pathTracingService.dispose(),this.pathTracingService=void 0),this.environmentService&&(this.environmentService.dispose(),this.environmentService=void 0)}dispose(){this.disposeServices(),this.scene.disposeContents(),this.triggerGarbageCollection()}triggerGarbageCollection(){var e;globalThis.gc&&((e=globalThis.gc)==null||e.call(globalThis))}}class pa{constructor(e){this.completeHandled=!1,this.suspendedForAnimation=!1,this.initialized=!1,this.initializing=!1,this.selfPauseListeners=new Set,this.deps=e}isEnabled(){var e;return!!(this.deps.service&&(((e=this.deps.getOptions().pathTracing)==null?void 0:e.enabled)??!1))}getMaxSamples(){var e;return((e=this.deps.getOptions().pathTracing)==null?void 0:e.maxSamples)??ii}isCompleteHandled(){return this.completeHandled}isAccumulating(){var e;return!!((e=this.deps.service)!=null&&e.isEnabled())}onSelfPause(e){return this.selfPauseListeners.add(e),()=>this.selfPauseListeners.delete(e)}async initialize(){this.isEnabled()&&await this.ensureInitialized()}async ensureInitialized(){const{service:e,getOptions:t,isDisposed:n,renderer:s,renderLoopManager:o,schedule:r}=this.deps;if(!(!e||this.initialized||this.initializing)){this.initializing=!0;try{const a=await e.initialize({enabled:!0,renderer:s});if(n())return;if(!a.ok){console.warn("Failed to initialize path tracing:",a.error);return}this.initialized=!0;const c=t().pathTracing;c&&e.updateSettings({samples:c.maxSamples??ii,bounces:c.bounces,transmissiveBounces:c.transmissiveBounces,renderScale:c.renderScale,lowResScale:c.lowResScale,dynamicLowRes:c.dynamicLowRes,enablePathTracing:c.enabled??!0}),e.events.on("pathtracing:paused",({reason:h})=>{o.releaseContinuous("path-tracing"),t().staticScene||o.setAlwaysRender(!1),r(()=>{o.hasContinuousDemand()||o.stop()},100),h==="gave-up"&&this.selfPauseListeners.forEach(d=>d())})}finally{this.initializing=!1}}}async enableRuntime(){var s;const{service:e,renderLoopManager:t,getOptions:n}=this.deps;return!e||(await this.ensureInitialized(),!this.initialized)||!(((s=n().pathTracing)==null?void 0:s.enabled)??!1)?!1:(e.setEnabled(!0),e.reset(!0),this.completeHandled=!1,this.suspendedForAnimation=!1,t.requireContinuous("path-tracing"),!0)}disableRuntime(){const{service:e,renderLoopManager:t}=this.deps;e&&(e.setEnabled(!1),e.reset(),t.releaseContinuous("path-tracing"),this.completeHandled=!1,this.suspendedForAnimation=!1,this.selfPauseListeners.forEach(n=>n()))}resetAccumulation(e=!1){const{service:t,renderLoopManager:n}=this.deps;!t||!this.isEnabled()||(t.reset(e),this.completeHandled=!1,!t.isEnabled()&&(t.canResume()||this.suspendedForAnimation)&&(this.suspendedForAnimation=!1,t.setEnabled(!0),n.requireContinuous("path-tracing")))}suspendWhileAnimating(){const e=this.deps.service;if(e)if(e.isEnabled()){const t=!this.suspendedForAnimation;this.suspendedForAnimation=!0,e.setEnabled(!1),this.deps.renderLoopManager.releaseContinuous("path-tracing"),t&&this.selfPauseListeners.forEach(n=>n())}else e.canResume()&&e.getSampleCount()>0&&(e.reset(),this.completeHandled=!1,this.suspendedForAnimation=!0)}getSampleCount(){var e;return((e=this.deps.service)==null?void 0:e.getSampleCount())||0}beforeFrame(){var e;return{wasActive:((e=this.deps.service)==null?void 0:e.isEnabled())||!1,samples:this.getSampleCount()}}render(e,t){const n=this.deps.service;if(!n||n.isPathTracerDisposed())return null;const s=n.getSampleCount(),o=s>=this.getMaxSamples()&&s>0;return!n.isEnabled()&&!o?null:(s===0&&(this.startTime=performance.now()),n.render(e,t))}detectCompletion(e,t){const n=this.deps.service;if(!n)return;(n.getSampleCount()||0)>=this.getMaxSamples()&&!this.completeHandled&&e.wasActive&&this.handleComplete(e.samples,t)}handleComplete(e,t){const{events:n,renderLoopManager:s,getOptions:o,schedule:r,replaceWithScreenshot:a}=this.deps;this.completeHandled=!0,s.releaseContinuous("path-tracing"),o().staticScene||s.setAlwaysRender(!1),n.emit("pathtracing:complete",{samples:e,totalTime:t-(this.startTime||0)});const c=()=>{s.hasContinuousDemand()||s.stop()};if(o().replaceWithScreenshotOnComplete){r(()=>{a(),r(c,200)},100);return}s.requestRender(),r(c,100)}onResizeStart(){var t;const e=((t=this.deps.service)==null?void 0:t.isEnabled())??!1;return this.deps.service&&this.completeHandled&&(this.deps.service.reset(),this.completeHandled=!1),e}onResizeEnd(e){e&&this.deps.service&&this.deps.service.setEnabled(!0)}}function Fr(){const i="0123456789abcdef";return Array.from("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",t=>t==="x"?i[Math.floor(Math.random()*16)]:t==="y"?(Math.floor(Math.random()*16)&3|8).toString(16):t).join("")}const ma=i=>[i,"video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].filter(t=>!!t).find(t=>MediaRecorder.isTypeSupported(t));class ga{constructor(e){this.pendingSettlers=new Set,this.pathTracedWaitSettlers=new Set,this.deps=e}async captureStill(e={}){return this.deps.isDisposed()?N.err(new Z("Cannot capture a still from a disposed viewer",K.INVALID_STATE)):(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed()?N.err(new Z("Viewer was disposed while a model load finished",K.INVALID_STATE)):this.deps.isScreenshotActive()?N.err(new Z("Cannot capture a still while a screenshot is replacing the canvas",K.INVALID_STATE)):this.deps.pathTracing.isEnabled()?this.capturePathTracedStill(e):this.captureRasterStill(e))}settleOnDispose(){[...this.pendingSettlers].forEach(e=>e("disposed"))}notifyTurntableEnabled(){[...this.pathTracedWaitSettlers].forEach(e=>e("turntable"))}async captureVideo(e={}){var d;if(this.deps.isDisposed())return N.err(new Z("Cannot capture video from a disposed viewer",K.INVALID_STATE));if(await this.deps.awaitModelLoads().catch(()=>{}),this.deps.isDisposed())return N.err(new Z("Viewer was disposed while a model load finished",K.INVALID_STATE));if(this.deps.isScreenshotActive())return N.err(new Z("Cannot capture video while a screenshot is replacing the canvas",K.INVALID_STATE));const t=e.duration??3;if(!(t>0))return N.err(new Z("Video duration must be a positive number of seconds",K.INVALID_PARAMETER));const n=this.deps.renderer.getDomElement();if(typeof MediaRecorder>"u"||typeof n.captureStream!="function")return N.err(new Z("Video capture needs MediaRecorder and canvas.captureStream support",K.UNSUPPORTED_FORMAT));const s=n.captureStream(e.fps??30);let o;try{o=new MediaRecorder(s,{mimeType:ma(e.mimeType),videoBitsPerSecond:e.videoBitsPerSecond})}catch(u){return s.getTracks().forEach(f=>f.stop()),N.err(new Z("Failed to start the video recorder",K.OPERATION_FAILED,{originalError:u}))}const r=s.getVideoTracks()[0],a=(d=r==null?void 0:r.requestFrame)==null?void 0:d.bind(r),c=a?this.deps.events.on("render:complete",()=>a()):()=>{},h=`video-capture:${Fr()}`;return this.deps.renderLoopManager.requireContinuous(h),this.deps.reviveRenderLoop(),this.deps.renderLoopManager.requestRender(),new Promise(u=>{const f=[];let m=null,E=!1;const b=A=>{E||(E=!0,this.pendingSettlers.delete(w),c(),m!==null&&clearTimeout(m),this.deps.renderLoopManager.releaseContinuous(h),s.getTracks().forEach(S=>S.stop()),u(A))},w=()=>{b(N.err(new Z("Viewer was disposed during video capture",K.INVALID_STATE)));try{o.stop()}catch{}};this.pendingSettlers.add(w),o.ondataavailable=A=>{A.data.size>0&&f.push(A.data)},o.onstop=()=>{b(N.ok(new Blob(f,{type:o.mimeType||"video/webm"})))},o.onerror=()=>{b(N.err(new Z("Video recording failed",K.OPERATION_FAILED)))},o.start(250),m=setTimeout(()=>{o.state!=="inactive"&&o.stop()},t*1e3)})}async capturePathTracedStill(e){if(e.width!==void 0||e.height!==void 0)return N.err(new Z("Path-traced stills are captured at the canvas resolution; omit width/height",K.INVALID_PARAMETER));if(this.deps.isAutoRotating())return N.err(new Z("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",K.INVALID_STATE));const t=this.deps.pathTracing.isAccumulating()&&this.deps.getStatus()!=="error";if(!this.deps.pathTracing.isCompleteHandled()&&t){const n=await this.waitForPathTracingOutcome();if(n==="disposed")return N.err(new Z("Viewer was disposed while waiting for the path tracer",K.INVALID_STATE));if(n==="error")return N.err(new Z("Model failed while waiting for the path tracer",K.RENDER_FAILED));if(n==="turntable")return N.err(new Z("Cannot capture a path-traced still while the turntable is spinning — pause autoRotate first",K.INVALID_STATE))}return this.readCanvasPng()}waitForPathTracingOutcome(){return new Promise(e=>{let t=()=>{},n=()=>{},s=()=>{},o=()=>{};const r=a=>{this.pendingSettlers.delete(r),this.pathTracedWaitSettlers.delete(r),t(),n(),s(),o(),e(a)};this.pendingSettlers.add(r),this.pathTracedWaitSettlers.add(r),t=this.deps.events.once("pathtracing:complete",()=>r("complete")),n=this.deps.events.once("model:error",()=>r("error")),s=this.deps.pathTracing.onSelfPause(()=>r("complete")),o=this.deps.events.on("controls:change",()=>{this.deps.isAutoRotating()&&r("turntable")})})}captureRasterStill(e){const{renderer:t,scene:n,camera:s,renderLoopManager:o}=this.deps,r=t.getDomElement(),a=t.getPixelRatio(),c=r.clientWidth>0&&r.clientHeight>0,h=c?r.clientWidth:Math.round(r.width/a),d=c?r.clientHeight:Math.round(r.height/a);if(h<=0||d<=0)return N.err(new Z("Cannot capture: the canvas has no size",K.INVALID_STATE));const u=h/d,f=Math.round(e.width??(e.height!==void 0?e.height*u:h*a)),m=Math.round(e.height??(e.width!==void 0?e.width/u:d*a)),E=t.capabilities.maxTextureSize;if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0||f>E||m>E)return N.err(new Z(`Requested still size ${f}x${m} is outside 1..${E}`,K.INVALID_PARAMETER));t.setPixelRatio(1),t.setSize(f,m),ri(s,f/m);const b=t.renderPostProcessed?t.renderPostProcessed(n,s):t.render(n,s),w=b.ok?this.readCanvasPng():N.err(b.error);return t.setSize(h,d),t.setPixelRatio(a),ri(s,u),t.render(n,s),o.requestRender(),w}readCanvasPng(){const e=kr(this.deps.renderer.getDomElement());return e?N.ok(e):N.err(new Z("Canvas produced an empty image",K.RENDER_FAILED))}}class gs{constructor(e){var o;this.frameCount=0,this.disposed=!1,this.pendingTimers=new Set,this.modelLoadChain=Promise.resolve(),this.controlsChangeUnsubscribe=null,this.renderer=e.renderer,this.scene=e.scene,this.camera=e.camera,this.controls=e.controls,this.options=e.options,this.rendererOptions=e.rendererOptions,this.sceneSetupService=e.sceneSetupService,this.environmentService=e.environmentService,this.selectionService=e.selectionService,this.anchorProjectionService=e.anchorProjectionService,this.animationService=e.animationService,this.deferToNextFrame=e.deferToNextFrame??la,this.stateManager=new ha,this.screenshotManager=new ua({renderer:this.renderer,onRestore:async()=>{await this.restoreFromScreenshot()}});const t=Dr(this.options.units);this.modelManager=new da({modelLoader:e.modelLoader,scene:this.scene,camera:this.camera,controls:this.controls,floorAlignmentService:e.floorAlignmentService,sceneSetupService:this.sceneSetupService,autoFitToObject:(o=this.options.camera)==null?void 0:o.autoFitToObject,floorAlignment:this.options.floorAlignment,unitsScaleToMeters:t}),this.resourceManager=new fa({scene:this.scene,pathTracingService:e.pathTracingService,environmentService:this.environmentService}),this.sceneConfigurator=new aa,this.events=new bs;const n=this.options.rendering||{},s=this.options.staticScene!==!1;this.renderLoopManager=new ca({enableIdleDetection:n.enableIdleDetection??s,idleDelay:n.idleDelay,targetFPS:n.targetFPS,enableFrameRateLimiting:n.enableFrameRateLimiting,alwaysRender:!1}),this.pathTracing=new pa({service:e.pathTracingService,events:this.events,renderLoopManager:this.renderLoopManager,renderer:this.renderer,getOptions:()=>this.options,isDisposed:()=>this.disposed,schedule:(r,a)=>this.schedule(r,a),replaceWithScreenshot:()=>this.replaceWithScreenshot()}),this.capture=new ga({renderer:this.renderer,scene:this.scene,camera:this.camera,events:this.events,renderLoopManager:this.renderLoopManager,pathTracing:this.pathTracing,getStatus:()=>this.stateManager.getStatus(),isDisposed:()=>this.disposed,awaitModelLoads:()=>this.modelLoadChain,reviveRenderLoop:()=>this.reviveRenderLoop(),isAutoRotating:()=>this.controls.autoRotate,isScreenshotActive:()=>this.screenshotManager.isActive()})}async initialize(){var e,t;try{const n=this.renderer.initialize(this.rendererOptions||{});return n.ok?(this.sceneSetupService&&this.sceneConfigurator.configureScene(this.scene,this.sceneSetupService,this.options),this.environmentService&&(await this.sceneConfigurator.configureEnvironment(this.scene,this.environmentService,this.sceneSetupService,this.renderer,this.options,()=>this.disposed),this.disposed)||(await this.pathTracing.initialize(),this.disposed)||(this.selectionService&&this.selectionService.initialize({canvas:this.renderer.getDomElement(),camera:this.camera,getPickRoot:()=>this.modelManager.getCurrentModel(),bvh:(e=this.options.selection)==null?void 0:e.bvh,onPick:s=>{s&&!this.disposed&&this.events.emit("object:selected",s)}}),this.stateManager.setInitialized(),this.startRenderLoop(),this.controlsChangeUnsubscribe=this.controls.onChange(()=>{this.disposed||(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}),this.options.staticScene?this.pathTracing.isEnabled()&&this.renderLoopManager.requireContinuous("path-tracing"):this.renderLoopManager.setAlwaysRender(!0),(t=this.options.controls)!=null&&t.autoRotate&&this.renderLoopManager.requireContinuous("turntable"),this.renderLoopManager.requestRender()),N.ok(void 0)):n}catch(n){const s=new Z("Failed to initialize viewer",K.INITIALIZATION_FAILED,{originalError:n});return this.stateManager.setError(s),this.events.emit("error",{error:s}),N.err(s)}}loadModel(e){const t=this.modelLoadChain.then(()=>this.runLoadModel(e));return this.modelLoadChain=t.then(()=>{},()=>{}),t}async runLoadModel(e){if(this.disposed)return N.err(new Z("Cannot load model after dispose",K.INVALID_STATE));if(!this.stateManager.canLoad())return N.err(new Z("Cannot load model in current state",K.INVALID_STATE,{currentState:this.stateManager.getStatus(),isInitialized:this.stateManager.isInitialized()}));try{this.stateManager.startLoading();const t=await this.modelManager.loadModel(e,this.events);return this.disposed?(t.ok&&this.modelManager.disposeCurrentModel(),N.err(new Z("Viewer was disposed while the model was loading",K.INVALID_STATE))):t.ok?(this.stateManager.setLoaded(t.value),this.attachAnimations(t.value),this.reviveRenderLoop(),this.renderLoopManager.requestRender(),this.pathTracing.resetAccumulation(!0),this.scheduleContactShadowBake(t.value),N.ok(void 0)):(this.stateManager.setError(t.error),t)}catch(t){const n=t instanceof Z?t:new Z("Failed to load model",K.MODEL_LOAD_FAILED,{originalError:t,source:e});return this.stateManager.setError(n),N.err(n)}}startRenderLoop(){this.renderLoopManager.start(e=>{var a;if(this.disposed){this.renderLoopManager.stop();return}if(!this.stateManager.isInitialized()||this.stateManager.getStatus()==="error")return;if(!this.renderer||this.renderer.isDisposed()){this.renderLoopManager.stop();return}const t=performance.now(),n=e>0?1e3/e:0,s=((a=this.animationService)==null?void 0:a.isPlaying())??!1;(this.controls.enabled?this.controls.update():!1)&&(this.events.emit("controls:change",{controls:this.controls}),s||this.pathTracing.resetAccumulation(),this.renderLoopManager.requestRender()),s&&this.animationService&&(this.animationService.update(e/1e3),this.pathTracing.suspendWhileAnimating());const r=this.pathTracing.beforeFrame();this.renderFrame().catch(c=>{console.error("[ViewerCore] Render frame error:",c)}),this.pathTracing.detectCompletion(r,t),this.frameCount++,this.stateManager.updateRenderInfo({frameCount:this.frameCount,fps:Math.round(n),lastRenderTime:performance.now()-t})})}stopRenderLoop(){this.renderLoopManager.stop()}schedule(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),!this.disposed&&e()},t);this.pendingTimers.add(n)}async renderFrame(){const e=performance.now();if(!this.renderer||!this.scene||!this.camera){console.warn("[ViewerCore] Cannot render - components not initialized");return}if(this.screenshotManager.isActive())return;this.stateManager.startRendering();const t=await(this.pathTracing.render(this.scene,this.camera)??Promise.resolve(this.renderRaster()));if(!t.ok){console.error("[ViewerCore] Render failed:",t.error),this.events.emit("error",{error:t.error});return}this.events.emit("render:complete",{frame:this.frameCount,renderTime:performance.now()-e,samples:this.pathTracing.getSampleCount()})}renderRaster(){return this.renderer.renderPostProcessed?this.renderer.renderPostProcessed(this.scene,this.camera):this.renderer.render(this.scene,this.camera)}updateOptions(e){var w,A,S,_,x,v,L,I,C,D,P,F,k,U,z;if(this.disposed)return;const t=(w=this.options.animations)==null?void 0:w.autoplay,n=(A=this.options.controls)==null?void 0:A.autoRotate,s=((S=this.options.pathTracing)==null?void 0:S.enabled)??!1,o=gs.postEffectsKey(this.options);this.options=on(this.options,e),"backgroundColorEdge"in e&&(this.options.backgroundColorEdge=e.backgroundColorEdge),e.renderer&&"colorGrade"in e.renderer&&this.options.renderer&&(this.options.renderer.colorGrade=e.renderer.colorGrade);let r=!1;(e.backgroundColor!==void 0||e.backgroundColorEdge!==void 0)&&this.options.backgroundColor!==void 0&&this.applyBackgroundColor(this.options.backgroundColor);const c=(_=e.renderer)==null?void 0:_.toneMappingExposure;c!==void 0&&(this.renderer.setToneMappingExposure(c),r=!0);const h=gs.postEffectsKey(this.options);e.renderer&&h!==o&&this.renderer.setPostProcessing&&(this.renderer.setPostProcessing({bloom:((x=this.options.renderer)==null?void 0:x.bloom)??!1,vignette:((v=this.options.renderer)==null?void 0:v.vignette)??!1,filmGrain:((L=this.options.renderer)==null?void 0:L.filmGrain)??!1,colorGrade:((I=this.options.renderer)==null?void 0:I.colorGrade)??!1}),this.pathTracing.resetAccumulation(!0),r=!0);const d=(C=e.environment)==null?void 0:C.environmentIntensity;d!==void 0&&(this.scene.setEnvironmentIntensity(d),r=!0);const u=(D=e.controls)==null?void 0:D.autoRotate;u!==void 0&&u!==n&&(this.controls.autoRotate=u,u?(this.renderLoopManager.requireContinuous("turntable"),this.capture.notifyTurntableEnabled()):this.renderLoopManager.releaseContinuous("turntable"),r=!0);const f=(P=e.controls)==null?void 0:P.autoRotateSpeed;f!==void 0&&(this.controls.autoRotateSpeed=f,r=!0);const m=(F=e.animations)==null?void 0:F.autoplay;m!==void 0&&m!==t&&(m?this.modelManager.getCurrentModel()&&this.autoplayFromOptions(m):this.pauseAnimations(),r=!0);const E=(k=e.animations)==null?void 0:k.speed;E!==void 0&&((U=this.animationService)==null||U.setSpeed(E),r=!0);const b=(z=e.pathTracing)==null?void 0:z.enabled;b!==void 0&&b!==s&&(this.setPathTracingEnabled(b),r=!0),r&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}static postEffectsKey(e){const t=e.renderer;return JSON.stringify([(t==null?void 0:t.bloom)??!1,(t==null?void 0:t.vignette)??!1,(t==null?void 0:t.filmGrain)??!1,(t==null?void 0:t.colorGrade)??!1])}backgroundGradient(e,t){return t!==void 0?{topColor:String(e),bottomColor:String(t),radial:!0}:{topColor:String(e),bottomColor:String(e)}}applyBackgroundColor(e){var s;if((s=this.options.environment)!=null&&s.url||!this.sceneSetupService)return;const t=this.backgroundGradient(e,this.options.backgroundColorEdge),n=this.sceneSetupService.createGradientBackground(this.scene,t);if(!n.ok){console.warn("Failed to update background color:",n.error);return}this.renderLoopManager.requestRender()}async setEnvironmentMap(e){var s,o,r;if(this.disposed)return N.ok(void 0);if(!this.environmentService)return N.err(new Z("Environment service unavailable",K.INVALID_STATE));const t=await this.environmentService.loadEnvironmentMap(e);if(this.disposed)return N.ok(void 0);if(!t.ok)return N.err(t.error);const n=this.environmentService.applyToScene(this.scene,t.value,{backgroundBlurriness:(s=this.options.environment)==null?void 0:s.backgroundBlurriness,backgroundIntensity:(o=this.options.environment)==null?void 0:o.backgroundIntensity,environmentIntensity:(r=this.options.environment)==null?void 0:r.environmentIntensity,setBackground:!0});return n.ok?(this.options=on(this.options,{environment:{url:e}}),this.repaintAfterEnvironmentChange(),N.ok(void 0)):n}resetEnvironment(){if(this.disposed)return N.ok(void 0);if(!this.environmentService)return N.err(new Z("Environment service unavailable",K.INVALID_STATE));const e=this.environmentService.createStudioEnvironment();return e.ok?(this.environmentService.applyToScene(this.scene,e.value,{setBackground:!1}),this.options.environment&&(this.options.environment.url=void 0),this.restoreBackgroundColor(),this.repaintAfterEnvironmentChange(),N.ok(void 0)):N.err(e.error)}async setBackgroundImage(e){if(this.disposed)return N.ok(void 0);if(!this.environmentService)return N.err(new Z("Environment service unavailable",K.INVALID_STATE));const t=await this.environmentService.setBackgroundImage(this.scene,e);return this.disposed?N.ok(void 0):t.ok?(this.repaintAfterEnvironmentChange(),N.ok(void 0)):t}setBackgroundColor(e){if(this.disposed)return N.ok(void 0);if(!this.sceneSetupService)return N.err(new Z("Scene setup service unavailable",K.INVALID_STATE));const t=this.sceneSetupService.createGradientBackground(this.scene,this.backgroundGradient(e,void 0));return t.ok?(this.options=on(this.options,{backgroundColor:e}),this.options.backgroundColorEdge=void 0,this.repaintAfterEnvironmentChange(),N.ok(void 0)):t}restoreBackgroundColor(){const e=this.options.backgroundColor;e===void 0||!this.sceneSetupService||this.sceneSetupService.createGradientBackground(this.scene,this.backgroundGradient(e,this.options.backgroundColorEdge))}repaintAfterEnvironmentChange(){this.pathTracing.resetAccumulation(!0),this.reviveRenderLoop(),this.renderLoopManager.requestRender()}resize(e,t){if(this.disposed)return;const n=e/t,s=this.renderer.getDomElement(),o=s.width===e&&s.height===t,a=!(this.camera.type==="perspective"&&"aspect"in this.camera)||Math.abs(this.camera.aspect-n)<1e-6;if(o&&a)return;const c=this.pathTracing.onResizeStart();ri(this.camera,n),o||this.renderer.setSize(e,t);try{this.renderer.render(this.scene,this.camera)}catch{}this.pathTracing.onResizeEnd(c),this.renderLoopManager.requestRender()}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.onStateChange(e)}getEvents(){return this.events}getDomElement(){return this.renderer.getDomElement()}getRenderer(){return this.renderer}getScene(){return this.scene}getCamera(){return this.camera}getControls(){return this.controls}getModel(){return this.modelManager.getCurrentModel()}requestRender(){this.renderLoopManager.requestRender()}reviveRenderLoop(){this.stateManager.isInitialized()&&!this.renderLoopManager.isRunning()&&this.startRenderLoop()}setPathTracingEnabled(e){e?this.pathTracing.enableRuntime().then(t=>{t&&!this.disposed&&(this.reviveRenderLoop(),this.renderLoopManager.requestRender())}):(this.pathTracing.disableRuntime(),this.reviveRenderLoop(),this.renderLoopManager.requestRender())}getAnimationNames(){var e;return((e=this.animationService)==null?void 0:e.getClipNames())??[]}playAnimations(e){var n;if(!this.animationService)return e!==void 0?N.err(new Z(`Cannot play animation clip '${e}': the viewer was assembled without an animation service`,K.INVALID_STATE)):N.ok(void 0);const t=this.animationService.play(e);return t.ok?(this.animationService.isPlaying()&&((n=this.sceneSetupService)==null||n.setContactShadowMode(this.scene,"live"),this.renderLoopManager.requireContinuous("animations"),this.reviveRenderLoop(),this.renderLoopManager.requestRender()),N.ok(void 0)):t}autoplayFromOptions(e){const t=this.playAnimations(typeof e=="string"?e:void 0);t.ok||console.error("animations.autoplay failed:",t.error.message)}pauseAnimations(){var e;(e=this.animationService)==null||e.pause(),this.renderLoopManager.releaseContinuous("animations"),this.rebakeContactShadowForCurrentPose(),this.pathTracing.resetAccumulation(!0),this.renderLoopManager.requestRender()}rebakeContactShadowForCurrentPose(){const e=this.modelManager.getCurrentModel();if(!e||!this.sceneSetupService)return;const t=this.sceneSetupService.bakeContactShadow(this.scene,e,this.renderer);t.ok||console.warn("Failed to bake contact shadow:",t.error)}scheduleContactShadowBake(e){this.deferToNextFrame(()=>{var t;this.disposed||this.modelManager.getCurrentModel()!==e||(t=this.animationService)!=null&&t.isPlaying()||(this.rebakeContactShadowForCurrentPose(),this.reviveRenderLoop(),this.renderLoopManager.requestRender())})}attachAnimations(e){if(!this.animationService)return;this.renderLoopManager.releaseContinuous("animations"),this.animationService.attach(e);const t=this.options.animations;(t==null?void 0:t.speed)!==void 0&&this.animationService.setSpeed(t.speed);const n=t==null?void 0:t.autoplay;n&&this.autoplayFromOptions(n)}createAnchorProjector(){return this.anchorProjectionService?this.anchorProjectionService.createProjector({camera:this.camera,getCanvas:()=>this.renderer.getDomElement(),getModel:()=>this.getModel()}):null}captureStill(e={}){return this.capture.captureStill(e)}captureVideo(e={}){return this.capture.captureVideo(e)}replaceWithScreenshot(){const e=this.modelManager.getLastModelUrl();this.screenshotManager.captureAndReplace(this.camera,this.controls,e,()=>{this.modelManager.disposeCurrentModel(),this.resourceManager.disposeSceneResources(!0)})}async restoreFromScreenshot(){const e=this.screenshotManager.getSerializedState();e&&await Nr.restore(e,this.camera,this.controls,async t=>{const n=await this.loadModel(t);n.ok||console.error("[ViewerCore] Failed to reload model:",n.error)}),this.renderLoopManager.isRunning()||this.startRenderLoop(),this.renderLoopManager.requestRender()}isDisposed(){return this.disposed}dispose(){var e,t,n;this.disposed=!0,this.pendingTimers.forEach(s=>clearTimeout(s)),this.pendingTimers.clear(),this.stopRenderLoop(),(e=this.controlsChangeUnsubscribe)==null||e.call(this),this.controlsChangeUnsubscribe=null,(t=this.selectionService)==null||t.dispose(),(n=this.animationService)==null||n.detach(),this.modelManager.dispose(),this.resourceManager.dispose(),this.screenshotManager.dispose(),this.controls.dispose(),this.renderer.dispose(),this.stateManager.setDisposed(),this.capture.settleOnDispose(),this.events.removeAllListeners(),this.stateManager.clearCallbacks()}}class Dt{constructor(e){this.vector=e}get x(){return this.vector.x}set x(e){this.vector.x=e}get y(){return this.vector.y}set y(e){this.vector.y=e}get z(){return this.vector.z}set z(e){this.vector.z=e}set(e,t,n){this.vector.set(e,t,n)}copy(e){this.vector.set(e.x,e.y,e.z)}add(e){this.vector.x+=e.x,this.vector.y+=e.y,this.vector.z+=e.z}multiply(e){this.vector.x*=e.x,this.vector.y*=e.y,this.vector.z*=e.z}normalize(){this.vector.normalize()}length(){return this.vector.length()}getThreeVector(){return this.vector}static fromThreeVector(e){return new Dt(e)}static create(e=0,t=0,n=0){return new Dt(new y.Vector3(e,t,n))}}const Br=0,ya=1,zr=2,Xi=2,Fs=1.25,Yi=1,He=32,De=He/4,Ai=65535,Ea=Ai<<16,fs=Math.pow(2,-24),vi=Symbol("SKIP_GENERATION"),Ur={strategy:Br,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[vi]:!1};function Ae(i,e,t){return t.min.x=e[i],t.min.y=e[i+1],t.min.z=e[i+2],t.max.x=e[i+3],t.max.y=e[i+4],t.max.z=e[i+5],t}function qi(i){let e=-1,t=-1/0;for(let n=0;n<3;n++){const s=i[n+3]-i[n];s>t&&(t=s,e=n)}return e}function $i(i,e){e.set(i)}function Qi(i,e,t){let n,s;for(let o=0;o<3;o++){const r=o+3;n=i[o],s=e[o],t[o]=n<s?n:s,n=i[r],s=e[r],t[r]=n>s?n:s}}function jn(i,e,t){for(let n=0;n<3;n++){const s=e[i+2*n],o=e[i+2*n+1],r=s-o,a=s+o;r<t[n]&&(t[n]=r),a>t[n+3]&&(t[n+3]=a)}}function fn(i){const e=i[3]-i[0],t=i[4]-i[1],n=i[5]-i[2];return 2*(e*t+t*n+n*e)}function Pe(i,e){return e[i+15]===Ai}function Ve(i,e){return e[i+6]}function Xe(i,e){return e[i+14]}function Fe(i){return i+De}function Be(i,e){const t=e[i+6];return i+t*De}function xs(i,e){return e[i+7]}function Ta(i){return i}function Bs(i,e,t,n,s){let o=1/0,r=1/0,a=1/0,c=-1/0,h=-1/0,d=-1/0,u=1/0,f=1/0,m=1/0,E=-1/0,b=-1/0,w=-1/0;const A=i.offset||0;for(let S=(e-A)*6,_=(e+t-A)*6;S<_;S+=6){const x=i[S+0],v=i[S+1],L=x-v,I=x+v;L<o&&(o=L),I>c&&(c=I),x<u&&(u=x),x>E&&(E=x);const C=i[S+2],D=i[S+3],P=C-D,F=C+D;P<r&&(r=P),F>h&&(h=F),C<f&&(f=C),C>b&&(b=C);const k=i[S+4],U=i[S+5],z=k-U,Y=k+U;z<a&&(a=z),Y>d&&(d=Y),k<m&&(m=k),k>w&&(w=k)}n[0]=o,n[1]=r,n[2]=a,n[3]=c,n[4]=h,n[5]=d,s[0]=u,s[1]=f,s[2]=m,s[3]=E,s[4]=b,s[5]=w}const _t=32,wa=(i,e)=>i.candidate-e.candidate,Rt=new Array(_t).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Wn=new Float32Array(6);function Sa(i,e,t,n,s,o){let r=-1,a=0;if(o===Br)r=qi(e),r!==-1&&(a=(e[r]+e[r+3])/2);else if(o===ya)r=qi(i),r!==-1&&(a=_a(t,n,s,r));else if(o===zr){const c=fn(i);let h=Fs*s;const d=t.offset||0,u=(n-d)*6,f=(n+s-d)*6;for(let m=0;m<3;m++){const E=e[m],A=(e[m+3]-E)/_t;if(s<_t/4){const S=[...Rt];S.length=s;let _=0;for(let v=u;v<f;v+=6,_++){const L=S[_];L.candidate=t[v+2*m],L.count=0;const{bounds:I,leftCacheBounds:C,rightCacheBounds:D}=L;for(let P=0;P<3;P++)D[P]=1/0,D[P+3]=-1/0,C[P]=1/0,C[P+3]=-1/0,I[P]=1/0,I[P+3]=-1/0;jn(v,t,I)}S.sort(wa);let x=s;for(let v=0;v<x;v++){const L=S[v];for(;v+1<x&&S[v+1].candidate===L.candidate;)S.splice(v+1,1),x--}for(let v=u;v<f;v+=6){const L=t[v+2*m];for(let I=0;I<x;I++){const C=S[I];L>=C.candidate?jn(v,t,C.rightCacheBounds):(jn(v,t,C.leftCacheBounds),C.count++)}}for(let v=0;v<x;v++){const L=S[v],I=L.count,C=s-L.count,D=L.leftCacheBounds,P=L.rightCacheBounds;let F=0;I!==0&&(F=fn(D)/c);let k=0;C!==0&&(k=fn(P)/c);const U=Yi+Fs*(F*I+k*C);U<h&&(r=m,h=U,a=L.candidate)}}else{for(let x=0;x<_t;x++){const v=Rt[x];v.count=0,v.candidate=E+A+x*A;const L=v.bounds;for(let I=0;I<3;I++)L[I]=1/0,L[I+3]=-1/0}for(let x=u;x<f;x+=6){let I=~~((t[x+2*m]-E)/A);I>=_t&&(I=_t-1);const C=Rt[I];C.count++,jn(x,t,C.bounds)}const S=Rt[_t-1];$i(S.bounds,S.rightCacheBounds);for(let x=_t-2;x>=0;x--){const v=Rt[x],L=Rt[x+1];Qi(v.bounds,L.rightCacheBounds,v.rightCacheBounds)}let _=0;for(let x=0;x<_t-1;x++){const v=Rt[x],L=v.count,I=v.bounds,D=Rt[x+1].rightCacheBounds;L!==0&&(_===0?$i(I,Wn):Qi(I,Wn,Wn)),_+=L;let P=0,F=0;_!==0&&(P=fn(Wn)/c);const k=s-_;k!==0&&(F=fn(D)/c);const U=Yi+Fs*(P*_+F*k);U<h&&(r=m,h=U,a=v.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${o} used.`);return{axis:r,pos:a}}function _a(i,e,t,n){let s=0;const o=i.offset;for(let r=e,a=e+t;r<a;r++)s+=i[(r-o)*6+n*2];return s/t}class zs{constructor(){this.boundingData=new Float32Array(6)}}function ba(i,e,t,n,s,o){let r=n,a=n+s-1;const c=o.pos,h=o.axis*2,d=t.offset||0;for(;;){for(;r<=a&&t[(r-d)*6+h]<c;)r++;for(;r<=a&&t[(a-d)*6+h]>=c;)a--;if(r<a){for(let u=0;u<e;u++){let f=i[r*e+u];i[r*e+u]=i[a*e+u],i[a*e+u]=f}for(let u=0;u<6;u++){const f=r-d,m=a-d,E=t[f*6+u];t[f*6+u]=t[m*6+u],t[m*6+u]=E}r++,a--}else return r}}let Hr,ps,oi,Vr;const xa=Math.pow(2,32);function ai(i){return"count"in i?1:1+ai(i.left)+ai(i.right)}function Aa(i,e,t){return Hr=new Float32Array(t),ps=new Uint32Array(t),oi=new Uint16Array(t),Vr=new Uint8Array(t),ci(i,e)}function ci(i,e){const t=i/4,n=i/2,s="count"in e,o=e.boundingData;for(let r=0;r<6;r++)Hr[t+r]=o[r];if(s)return e.buffer?(Vr.set(new Uint8Array(e.buffer),i),i+e.buffer.byteLength):(ps[t+6]=e.offset,oi[n+14]=e.count,oi[n+15]=Ai,i+He);{const{left:r,right:a,splitAxis:c}=e,h=i+He;let d=ci(h,r);const u=i/He,m=d/He-u;if(m>xa)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ps[t+6]=m,ps[t+7]=c,ci(d,a)}}function va(i,e,t,n,s,o){const{maxDepth:r,verbose:a,maxLeafSize:c,strategy:h,onProgress:d}=s,u=i.primitiveBuffer,f=i.primitiveBufferStride,m=new Float32Array(6);let E=!1;const b=new zs;return Bs(e,t,n,b.boundingData,m),A(b,t,n,m),b;function w(S){d&&d((S-o.offset)/o.count)}function A(S,_,x,v=null,L=0){if(!E&&L>=r&&(E=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`)),x<=c||L>=r)return w(_+x),S.offset=_,S.count=x,S;const I=Sa(S.boundingData,v,e,_,x,h);if(I.axis===-1)return w(_+x),S.offset=_,S.count=x,S;const C=ba(u,f,e,_,x,I);if(C===_||C===_+x)w(_+x),S.offset=_,S.count=x;else{S.splitAxis=I.axis;const D=new zs,P=_,F=C-_;S.left=D,Bs(e,P,F,D.boundingData,m),A(D,P,F,m,L+1);const k=new zs,U=C,z=x-F;S.right=k,Bs(e,U,z,k.boundingData,m),A(k,U,z,m,L+1)}return S}}function Ra(i,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=i.getRootRanges(e.range),s=n[0],o=n[n.length-1],r={offset:s.offset,count:o.offset+o.count-s.offset},a=new Float32Array(6*r.count);a.offset=r.offset,i.computePrimitiveBounds(r.offset,r.count,a),i._roots=n.map(c=>{const h=va(i,a,c.offset,c.count,e,r),d=ai(h),u=new t(He*d);return Aa(0,h,u),u})}class Ri{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 Ma{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 xe=new Ma;let Ot,sn;const Zt=[],Zn=new Ri(()=>new p.Box3);function Ca(i,e,t,n,s,o){Ot=Zn.getPrimitive(),sn=Zn.getPrimitive(),Zt.push(Ot,sn),xe.setBuffer(i._roots[e]);const r=li(0,i.geometry,t,n,s,o);xe.clearBuffer(),Zn.releasePrimitive(Ot),Zn.releasePrimitive(sn),Zt.pop(),Zt.pop();const a=Zt.length;return a>0&&(sn=Zt[a-1],Ot=Zt[a-2]),r}function li(i,e,t,n,s=null,o=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:h}=xe;let d=i*2;if(Pe(d,c)){const f=Ve(i,h),m=Xe(d,c);return Ae(i,a,Ot),n(f,m,!1,r,o+i/De,Ot)}else{let P=function(k){const{uint16Array:U,uint32Array:z}=xe;let Y=k*2;for(;!Pe(Y,U);)k=Fe(k),Y=k*2;return Ve(k,z)},F=function(k){const{uint16Array:U,uint32Array:z}=xe;let Y=k*2;for(;!Pe(Y,U);)k=Be(k,z),Y=k*2;return Ve(k,z)+Xe(Y,U)};const f=Fe(i),m=Be(i,h);let E=f,b=m,w,A,S,_;if(s&&(S=Ot,_=sn,Ae(E,a,S),Ae(b,a,_),w=s(S),A=s(_),A<w)){E=m,b=f;const k=w;w=A,A=k,S=_}S||(S=Ot,Ae(E,a,S));const x=Pe(E*2,c),v=t(S,x,w,r+1,o+E/De);let L;if(v===Xi){const k=P(E),z=F(E)-k;L=n(k,z,!0,r+1,o+E/De,S)}else L=v&&li(E,e,t,n,s,o,r+1);if(L)return!0;_=sn,Ae(b,a,_);const I=Pe(b*2,c),C=t(_,I,A,r+1,o+b/De);let D;if(C===Xi){const k=P(b),z=F(b)-k;D=n(k,z,!0,r+1,o+b/De,_)}else D=C&&li(b,e,t,n,s,o,r+1);return!!D}}const xn=new xe.constructor,ys=new xe.constructor,It=new Ri(()=>new p.Box3),Kt=new p.Box3,Xt=new p.Box3,Us=new p.Box3,Hs=new p.Box3;let Vs=!1;function Pa(i,e,t,n){if(Vs)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Vs=!0;const s=i._roots,o=e._roots;let r,a=0,c=0;const h=new p.Matrix4().copy(t).invert();for(let d=0,u=s.length;d<u;d++){xn.setBuffer(s[d]),c=0;const f=It.getPrimitive();Ae(0,xn.float32Array,f),f.applyMatrix4(h);for(let m=0,E=o.length;m<E&&(ys.setBuffer(o[m]),r=ut(0,0,t,h,n,a,c,0,0,f),ys.clearBuffer(),c+=o[m].byteLength/He,!r);m++);if(It.releasePrimitive(f),xn.clearBuffer(),a+=s[d].byteLength/He,r)break}return Vs=!1,r}function ut(i,e,t,n,s,o=0,r=0,a=0,c=0,h=null,d=!1){let u,f;d?(u=ys,f=xn):(u=xn,f=ys);const m=u.float32Array,E=u.uint32Array,b=u.uint16Array,w=f.float32Array,A=f.uint32Array,S=f.uint16Array,_=i*2,x=e*2,v=Pe(_,b),L=Pe(x,S);let I=!1;if(L&&v)d?I=s(Ve(e,A),Xe(e*2,S),Ve(i,E),Xe(i*2,b),c,r+e/De,a,o+i/De):I=s(Ve(i,E),Xe(i*2,b),Ve(e,A),Xe(e*2,S),a,o+i/De,c,r+e/De);else if(L){const C=It.getPrimitive();Ae(e,w,C),C.applyMatrix4(t);const D=Fe(i),P=Be(i,E);Ae(D,m,Kt),Ae(P,m,Xt);const F=C.intersectsBox(Kt),k=C.intersectsBox(Xt);I=F&&ut(e,D,n,t,s,r,o,c,a+1,C,!d)||k&&ut(e,P,n,t,s,r,o,c,a+1,C,!d),It.releasePrimitive(C)}else{const C=Fe(e),D=Be(e,A);Ae(C,w,Us),Ae(D,w,Hs);const P=h.intersectsBox(Us),F=h.intersectsBox(Hs);if(P&&F)I=ut(i,C,t,n,s,o,r,a,c+1,h,d)||ut(i,D,t,n,s,o,r,a,c+1,h,d);else if(P)if(v)I=ut(i,C,t,n,s,o,r,a,c+1,h,d);else{const k=It.getPrimitive();k.copy(Us).applyMatrix4(t);const U=Fe(i),z=Be(i,E);Ae(U,m,Kt),Ae(z,m,Xt);const Y=k.intersectsBox(Kt),re=k.intersectsBox(Xt);I=Y&&ut(C,U,n,t,s,r,o,c,a+1,k,!d)||re&&ut(C,z,n,t,s,r,o,c,a+1,k,!d),It.releasePrimitive(k)}else if(F)if(v)I=ut(i,D,t,n,s,o,r,a,c+1,h,d);else{const k=It.getPrimitive();k.copy(Hs).applyMatrix4(t);const U=Fe(i),z=Be(i,E);Ae(U,m,Kt),Ae(z,m,Xt);const Y=k.intersectsBox(Kt),re=k.intersectsBox(Xt);I=Y&&ut(D,U,n,t,s,r,o,c,a+1,k,!d)||re&&ut(D,z,n,t,s,r,o,c,a+1,k,!d),It.releasePrimitive(k)}}return I}const Ji=new p.Box3,Yt=new Float32Array(6);class Ia{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Ur,...e},Ra(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,n,s){let o=1/0,r=1/0,a=1/0,c=-1/0,h=-1/0,d=-1/0;for(let u=e,f=e+t;u<f;u++){this.writePrimitiveBounds(u,Yt,0);const[m,E,b,w,A,S]=Yt;m<o&&(o=m),w>c&&(c=w),E<r&&(r=E),A>h&&(h=A),b<a&&(a=b),S>d&&(d=S)}return n[s+0]=o,n[s+1]=r,n[s+2]=a,n[s+3]=c,n[s+4]=h,n[s+5]=d,n}computePrimitiveBounds(e,t,n){const s=n.offset||0;for(let o=e,r=e+t;o<r;o++){this.writePrimitiveBounds(o,Yt,0);const[a,c,h,d,u,f]=Yt,m=(a+d)/2,E=(c+u)/2,b=(h+f)/2,w=(d-a)/2,A=(u-c)/2,S=(f-h)/2,_=(o-s)*6;n[_+0]=m,n[_+1]=w+(Math.abs(m)+w)*fs,n[_+2]=E,n[_+3]=A+(Math.abs(E)+A)*fs,n[_+4]=b,n[_+5]=S+(Math.abs(b)+S)*fs}return n}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,s=t.length;n<s;n++)t[n]+=e;else{const n=this._roots;for(let s=0;s<n.length;s++){const o=n[s],r=new Uint32Array(o),a=new Uint16Array(o),c=o.byteLength/He;for(let h=0;h<c;h++){const d=De*h,u=2*d;Pe(u,a)&&(r[d+6]+=e)}}}}traverse(e,t=0){const n=this._roots[t],s=new Uint32Array(n),o=new Uint16Array(n);r(0);function r(a,c=0){const h=a*2,d=Pe(h,o);if(d){const u=s[a+6],f=o[h+14];e(c,d,new Float32Array(n,a*4,6),u,f)}else{const u=Fe(a),f=Be(a,s),m=xs(a,s);e(c,d,new Float32Array(n,a*4,6),m)||(r(u,c+1),r(f,c+1))}}}refit(){const e=this._roots;for(let t=0,n=e.length;t<n;t++){const s=e[t],o=new Uint32Array(s),r=new Uint16Array(s),a=new Float32Array(s),c=s.byteLength/He;for(let h=c-1;h>=0;h--){const d=h*De,u=d*2;if(Pe(u,r)){const m=Ve(d,o),E=Xe(u,r);this.writePrimitiveRangeBounds(m,E,Yt,0),a.set(Yt,d)}else{const m=Fe(d),E=Be(d,o);for(let b=0;b<3;b++){const w=a[m+b],A=a[m+b+3],S=a[E+b],_=a[E+b+3];a[d+b]=w<S?w:S,a[d+b+3]=A>_?A:_}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{Ae(0,new Float32Array(n),Ji),e.union(Ji)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:n,intersectsRange:s,intersectsPrimitive:o,scratchPrimitive:r,iterate:a}=e;if(s&&o){const u=s;s=(f,m,E,b,w)=>u(f,m,E,b,w)?!0:a(f,m,this,o,E,b,r)}else s||(o?s=(u,f,m,E)=>a(u,f,this,o,m,E,r):s=(u,f,m)=>m);let c=!1,h=0;const d=this._roots;for(let u=0,f=d.length;u<f;u++){const m=d[u];if(c=Ca(this,u,n,s,t,h),c)break;h+=m.byteLength/He}return c}bvhcast(e,t,n){let{intersectsRanges:s}=n;return Pa(this,e,t,s)}}function La(){return typeof SharedArrayBuffer<"u"}function As(i){return i.index?i.index.count:i.attributes.position.count}function vs(i){return As(i)/3}function Gr(i,e=ArrayBuffer){return i>65535?new Uint32Array(new e(4*i)):new Uint16Array(new e(2*i))}function Oa(i,e){if(!i.index){const t=i.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=Gr(t,n);i.setIndex(new p.BufferAttribute(s,1));for(let o=0;o<t;o++)s[o]=o}}function Da(i,e,t){const n=As(i)/t,s=e||i.drawRange,o=s.start/t,r=(s.start+s.count)/t,a=Math.max(0,o),c=Math.min(n,r)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function Na(i,e){return i.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function er(i,e,t){const n=Da(i,e,t),s=Na(i,t);if(!s.length)return[n];const o=[],r=n.offset,a=n.offset+n.count,c=As(i)/t,h=[];for(const f of s){const{offset:m,count:E}=f,b=m,w=isFinite(E)?E:c-m,A=m+w;b<a&&A>r&&(h.push({pos:Math.max(r,b),isStart:!0}),h.push({pos:Math.min(a,A),isStart:!1}))}h.sort((f,m)=>f.pos!==m.pos?f.pos-m.pos:f.type==="end"?-1:1);let d=0,u=null;for(const f of h){const m=f.pos;d!==0&&m!==u&&o.push({offset:u,count:m-u}),d+=f.isStart?1:-1,u=m}return o}function ka(i,e){const t=i[i.length-1],n=t.offset+t.count>2**16,s=i.reduce((h,d)=>h+d.count,0),o=n?4:2,r=e?new SharedArrayBuffer(s*o):new ArrayBuffer(s*o),a=n?new Uint32Array(r):new Uint16Array(r);let c=0;for(let h=0;h<i.length;h++){const{offset:d,count:u}=i[h];for(let f=0;f<u;f++)a[c+f]=d+f;c+=u}return a}class Fa extends Ia{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&&!La())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={...Ur,...t},t[vi]||this.init(t)}init(e){const{geometry:t,primitiveStride:n}=this;if(e.indirect){const s=er(t,e.range,n),o=ka(s,e.useSharedArrayBuffer);this._indirectBuffer=o}else Oa(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new p.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:er(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class xt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,s=-1/0;for(let o=0,r=e.length;o<r;o++){const c=e[o][t];n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}setFromPoints(e,t){let n=1/0,s=-1/0;for(let o=0,r=t.length;o<r;o++){const a=t[o],c=e.dot(a);n=c<n?c:n,s=c>s?c:s}this.min=n,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}xt.prototype.setFromBox=(function(){const i=new p.Vector3;return function(t,n){const s=n.min,o=n.max;let r=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){i.x=s.x*c+o.x*(1-c),i.y=s.y*h+o.y*(1-h),i.z=s.z*d+o.z*(1-d);const u=t.dot(i);r=Math.min(u,r),a=Math.max(u,a)}this.min=r,this.max=a}})();const Ba=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Vector3;return function(s,o,r){const a=s.start,c=i,h=o.start,d=e;t.subVectors(a,h),i.subVectors(s.end,s.start),e.subVectors(o.end,o.start);const u=t.dot(d),f=d.dot(c),m=d.dot(d),E=t.dot(c),w=c.dot(c)*m-f*f;let A,S;w!==0?A=(u*f-E*m)/w:A=0,S=(u+A*f)/m,r.x=A,r.y=S}})(),Mi=(function(){const i=new p.Vector2,e=new p.Vector3,t=new p.Vector3;return function(s,o,r,a){Ba(s,o,i);let c=i.x,h=i.y;if(c>=0&&c<=1&&h>=0&&h<=1){s.at(c,r),o.at(h,a);return}else if(c>=0&&c<=1){h<0?o.at(0,a):o.at(1,a),s.closestPointToPoint(a,!0,r);return}else if(h>=0&&h<=1){c<0?s.at(0,r):s.at(1,r),o.closestPointToPoint(r,!0,a);return}else{let d;c<0?d=s.start:d=s.end;let u;h<0?u=o.start:u=o.end;const f=e,m=t;if(s.closestPointToPoint(u,!0,e),o.closestPointToPoint(d,!0,t),f.distanceToSquared(u)<=m.distanceToSquared(d)){r.copy(f),a.copy(u);return}else{r.copy(d),a.copy(m);return}}}})(),za=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Plane,n=new p.Line3;return function(o,r){const{radius:a,center:c}=o,{a:h,b:d,c:u}=r;if(n.start=h,n.end=d,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a||(n.start=h,n.end=u,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a)||(n.start=d,n.end=u,n.closestPointToPoint(c,!0,i).distanceTo(c)<=a))return!0;const b=r.getPlane(t);if(Math.abs(b.distanceToPoint(c))<=a){const A=b.projectPoint(c,e);if(r.containsPoint(A))return!0}return!1}})(),Ua=["x","y","z"],bt=1e-15,tr=bt*bt;function nt(i){return Math.abs(i)<bt}class ft extends p.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new p.Vector3),this.satBounds=new Array(4).fill().map(()=>new xt),this.points=[this.a,this.b,this.c],this.plane=new p.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new p.Line3,this.needsUpdate=!0}intersectsSphere(e){return za(e,this)}update(){const e=this.a,t=this.b,n=this.c,s=this.points,o=this.satAxes,r=this.satBounds,a=o[0],c=r[0];this.getNormal(a),c.setFromPoints(a,s);const h=o[1],d=r[1];h.subVectors(e,t),d.setFromPoints(h,s);const u=o[2],f=r[2];u.subVectors(t,n),f.setFromPoints(u,s);const m=o[3],E=r[3];m.subVectors(n,e),E.setFromPoints(m,s);const b=h.length(),w=u.length(),A=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,b<bt?w<bt||A<bt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):w<bt?A<bt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<bt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}ft.prototype.closestPointToSegment=(function(){const i=new p.Vector3,e=new p.Vector3,t=new p.Line3;return function(s,o=null,r=null){const{start:a,end:c}=s,h=this.points;let d,u=1/0;for(let f=0;f<3;f++){const m=(f+1)%3;t.start.copy(h[f]),t.end.copy(h[m]),Mi(t,s,i,e),d=i.distanceToSquared(e),d<u&&(u=d,o&&o.copy(i),r&&r.copy(e))}return this.closestPointToPoint(a,i),d=a.distanceToSquared(i),d<u&&(u=d,o&&o.copy(i),r&&r.copy(a)),this.closestPointToPoint(c,i),d=c.distanceToSquared(i),d<u&&(u=d,o&&o.copy(i),r&&r.copy(c)),Math.sqrt(u)}})();ft.prototype.intersectsTriangle=(function(){const i=new ft,e=new xt,t=new xt,n=new p.Vector3,s=new p.Vector3,o=new p.Vector3,r=new p.Vector3,a=new p.Line3,c=new p.Line3,h=new p.Vector3,d=new p.Vector2,u=new p.Vector2;function f(_,x,v,L){const I=n;!_.isDegenerateIntoPoint&&!_.isDegenerateIntoSegment?I.copy(_.plane.normal):I.copy(x.plane.normal);const C=_.satBounds,D=_.satAxes;for(let k=1;k<4;k++){const U=C[k],z=D[k];if(e.setFromPoints(z,x.points),U.isSeparated(e)||(r.copy(I).cross(z),e.setFromPoints(r,_.points),t.setFromPoints(r,x.points),e.isSeparated(t)))return!1}const P=x.satBounds,F=x.satAxes;for(let k=1;k<4;k++){const U=P[k],z=F[k];if(e.setFromPoints(z,_.points),U.isSeparated(e)||(r.crossVectors(I,z),e.setFromPoints(r,_.points),t.setFromPoints(r,x.points),e.isSeparated(t)))return!1}return v&&(L||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),v.start.set(0,0,0),v.end.set(0,0,0)),!0}function m(_,x,v,L,I,C,D,P,F,k,U){let z=D/(D-P);k.x=L+(I-L)*z,U.start.subVectors(x,_).multiplyScalar(z).add(_),z=D/(D-F),k.y=L+(C-L)*z,U.end.subVectors(v,_).multiplyScalar(z).add(_)}function E(_,x,v,L,I,C,D,P,F,k,U){if(I>0)m(_.c,_.a,_.b,L,x,v,F,D,P,k,U);else if(C>0)m(_.b,_.a,_.c,v,x,L,P,D,F,k,U);else if(P*F>0||D!=0)m(_.a,_.b,_.c,x,v,L,D,P,F,k,U);else if(P!=0)m(_.b,_.a,_.c,v,x,L,P,D,F,k,U);else if(F!=0)m(_.c,_.a,_.b,L,x,v,F,D,P,k,U);else return!0;return!1}function b(_,x,v,L){const I=x.degenerateSegment,C=_.plane.distanceToPoint(I.start),D=_.plane.distanceToPoint(I.end);return nt(C)?nt(D)?f(_,x,v,L):(v&&(v.start.copy(I.start),v.end.copy(I.start)),_.containsPoint(I.start)):nt(D)?(v&&(v.start.copy(I.end),v.end.copy(I.end)),_.containsPoint(I.end)):_.plane.intersectLine(I,n)!=null?(v&&(v.start.copy(n),v.end.copy(n)),_.containsPoint(n)):!1}function w(_,x,v){const L=x.a;return nt(_.plane.distanceToPoint(L))&&_.containsPoint(L)?(v&&(v.start.copy(L),v.end.copy(L)),!0):!1}function A(_,x,v){const L=_.degenerateSegment,I=x.a;return L.closestPointToPoint(I,!0,n),I.distanceToSquared(n)<tr?(v&&(v.start.copy(I),v.end.copy(I)),!0):!1}function S(_,x,v,L){if(_.isDegenerateIntoSegment)if(x.isDegenerateIntoSegment){const I=_.degenerateSegment,C=x.degenerateSegment,D=s,P=o;I.delta(D),C.delta(P);const F=n.subVectors(C.start,I.start),k=D.x*P.y-D.y*P.x;if(nt(k))return!1;const U=(F.x*P.y-F.y*P.x)/k,z=-(D.x*F.y-D.y*F.x)/k;if(U<0||U>1||z<0||z>1)return!1;const Y=I.start.z+D.z*U,re=C.start.z+P.z*z;return nt(Y-re)?(v&&(v.start.copy(I.start).addScaledVector(D,U),v.end.copy(I.start).addScaledVector(D,U)),!0):!1}else return x.isDegenerateIntoPoint?A(_,x,v):b(x,_,v,L);else{if(_.isDegenerateIntoPoint)return x.isDegenerateIntoPoint?x.a.distanceToSquared(_.a)<tr?(v&&(v.start.copy(_.a),v.end.copy(_.a)),!0):!1:x.isDegenerateIntoSegment?A(x,_,v):w(x,_,v);if(x.isDegenerateIntoPoint)return w(_,x,v);if(x.isDegenerateIntoSegment)return b(_,x,v,L)}}return function(x,v=null,L=!1){this.needsUpdate&&this.update(),x.isExtendedTriangle?x.needsUpdate&&x.update():(i.copy(x),i.update(),x=i);const I=S(this,x,v,L);if(I!==void 0)return I;const C=this.plane,D=x.plane;let P=D.distanceToPoint(this.a),F=D.distanceToPoint(this.b),k=D.distanceToPoint(this.c);nt(P)&&(P=0),nt(F)&&(F=0),nt(k)&&(k=0);const U=P*F,z=P*k;if(U>0&&z>0)return!1;let Y=C.distanceToPoint(x.a),re=C.distanceToPoint(x.b),Ne=C.distanceToPoint(x.c);nt(Y)&&(Y=0),nt(re)&&(re=0),nt(Ne)&&(Ne=0);const at=Y*re,Me=Y*Ne;if(at>0&&Me>0)return!1;s.copy(C.normal),o.copy(D.normal);const ze=s.cross(o);let Ge=0,ve=Math.abs(ze.x);const Ee=Math.abs(ze.y);Ee>ve&&(ve=Ee,Ge=1),Math.abs(ze.z)>ve&&(Ge=2);const je=Ua[Ge],At=this.a[je],ye=this.b[je],ct=this.c[je],lt=x.a[je],ln=x.b[je],Gt=x.c[je];if(E(this,At,ye,ct,U,z,P,F,k,d,a))return f(this,x,v,L);if(E(x,lt,ln,Gt,at,Me,Y,re,Ne,u,c))return f(this,x,v,L);if(d.y<d.x){const St=d.y;d.y=d.x,d.x=St,h.copy(a.start),a.start.copy(a.end),a.end.copy(h)}if(u.y<u.x){const St=u.y;u.y=u.x,u.x=St,h.copy(c.start),c.start.copy(c.end),c.end.copy(h)}return d.y<u.x||u.y<d.x?!1:(v&&(u.x>d.x?v.start.copy(c.start):v.start.copy(a.start),u.y<d.y?v.end.copy(c.end):v.end.copy(a.end)),!0)}})();ft.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();ft.prototype.distanceToTriangle=(function(){const i=new p.Vector3,e=new p.Vector3,t=["a","b","c"],n=new p.Line3,s=new p.Line3;return function(r,a=null,c=null){const h=a||c?n:null;if(this.intersectsTriangle(r,h,!0))return(a||c)&&(a&&h.getCenter(a),c&&h.getCenter(c)),0;let d=1/0;for(let u=0;u<3;u++){let f;const m=t[u],E=r[m];this.closestPointToPoint(E,i),f=E.distanceToSquared(i),f<d&&(d=f,a&&a.copy(i),c&&c.copy(E));const b=this[m];r.closestPointToPoint(b,i),f=b.distanceToSquared(i),f<d&&(d=f,a&&a.copy(b),c&&c.copy(i))}for(let u=0;u<3;u++){const f=t[u],m=t[(u+1)%3];n.set(this[f],this[m]);for(let E=0;E<3;E++){const b=t[E],w=t[(E+1)%3];s.set(r[b],r[w]),Mi(n,s,i,e);const A=i.distanceToSquared(e);A<d&&(d=A,a&&a.copy(i),c&&c.copy(e))}}return Math.sqrt(d)}})();class Ye{constructor(e,t,n){this.isOrientedBox=!0,this.min=new p.Vector3,this.max=new p.Vector3,this.matrix=new p.Matrix4,this.invMatrix=new p.Matrix4,this.points=new Array(8).fill().map(()=>new p.Vector3),this.satAxes=new Array(3).fill().map(()=>new p.Vector3),this.satBounds=new Array(3).fill().map(()=>new xt),this.alignedSatBounds=new Array(3).fill().map(()=>new xt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ye.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,s=this.points;for(let h=0;h<=1;h++)for(let d=0;d<=1;d++)for(let u=0;u<=1;u++){const f=1*h|2*d|4*u,m=s[f];m.x=h?n.x:t.x,m.y=d?n.y:t.y,m.z=u?n.z:t.z,m.applyMatrix4(e)}const o=this.satBounds,r=this.satAxes,a=s[0];for(let h=0;h<3;h++){const d=r[h],u=o[h],f=1<<h,m=s[f];d.subVectors(a,m),u.setFromPoints(d,s)}const c=this.alignedSatBounds;c[0].setFromPointsField(s,"x"),c[1].setFromPointsField(s,"y"),c[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();Ye.prototype.intersectsBox=(function(){const i=new xt;return function(t){this.needsUpdate&&this.update();const n=t.min,s=t.max,o=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(i.min=n.x,i.max=s.x,a[0].isSeparated(i)||(i.min=n.y,i.max=s.y,a[1].isSeparated(i))||(i.min=n.z,i.max=s.z,a[2].isSeparated(i)))return!1;for(let c=0;c<3;c++){const h=r[c],d=o[c];if(i.setFromBox(h,t),d.isSeparated(i))return!1}return!0}})();Ye.prototype.intersectsTriangle=(function(){const i=new ft,e=new Array(3),t=new xt,n=new xt,s=new p.Vector3;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(i.copy(r),i.update(),r=i);const a=this.satBounds,c=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let f=0;f<3;f++){const m=a[f],E=c[f];if(t.setFromPoints(E,e),m.isSeparated(t))return!1}const h=r.satBounds,d=r.satAxes,u=this.points;for(let f=0;f<3;f++){const m=h[f],E=d[f];if(t.setFromPoints(E,u),m.isSeparated(t))return!1}for(let f=0;f<3;f++){const m=c[f];for(let E=0;E<4;E++){const b=d[E];if(s.crossVectors(m,b),t.setFromPoints(s,e),n.setFromPoints(s,u),t.isSeparated(n))return!1}}return!0}})();Ye.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();Ye.prototype.distanceToPoint=(function(){const i=new p.Vector3;return function(t){return this.closestPointToPoint(t,i),t.distanceTo(i)}})();Ye.prototype.distanceToBox=(function(){const i=["x","y","z"],e=new Array(12).fill().map(()=>new p.Line3),t=new Array(12).fill().map(()=>new p.Line3),n=new p.Vector3,s=new p.Vector3;return function(r,a=0,c=null,h=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(c||h)&&(r.getCenter(s),this.closestPointToPoint(s,n),r.closestPointToPoint(n,s),c&&c.copy(n),h&&h.copy(s)),0;const d=a*a,u=r.min,f=r.max,m=this.points;let E=1/0;for(let w=0;w<8;w++){const A=m[w];s.copy(A).clamp(u,f);const S=A.distanceToSquared(s);if(S<E&&(E=S,c&&c.copy(A),h&&h.copy(s),S<d))return Math.sqrt(S)}let b=0;for(let w=0;w<3;w++)for(let A=0;A<=1;A++)for(let S=0;S<=1;S++){const _=(w+1)%3,x=(w+2)%3,v=A<<_|S<<x,L=1<<w|A<<_|S<<x,I=m[v],C=m[L];e[b].set(I,C);const P=i[w],F=i[_],k=i[x],U=t[b],z=U.start,Y=U.end;z[P]=u[P],z[F]=A?u[F]:f[F],z[k]=S?u[k]:f[F],Y[P]=f[P],Y[F]=A?u[F]:f[F],Y[k]=S?u[k]:f[F],b++}for(let w=0;w<=1;w++)for(let A=0;A<=1;A++)for(let S=0;S<=1;S++){s.x=w?f.x:u.x,s.y=A?f.y:u.y,s.z=S?f.z:u.z,this.closestPointToPoint(s,n);const _=s.distanceToSquared(n);if(_<E&&(E=_,c&&c.copy(n),h&&h.copy(s),_<d))return Math.sqrt(_)}for(let w=0;w<12;w++){const A=e[w];for(let S=0;S<12;S++){const _=t[S];Mi(A,_,n,s);const x=n.distanceToSquared(s);if(x<E&&(E=x,c&&c.copy(n),h&&h.copy(s),x<d))return Math.sqrt(x)}}return Math.sqrt(E)}})();class Ha extends Ri{constructor(){super(()=>new ft)}}const rt=new Ha,pn=new p.Vector3,Gs=new p.Vector3;function Va(i,e,t={},n=0,s=1/0){const o=n*n,r=s*s;let a=1/0,c=null;if(i.shapecast({boundsTraverseOrder:d=>(pn.copy(e).clamp(d.min,d.max),pn.distanceToSquared(e)),intersectsBounds:(d,u,f)=>f<a&&f<r,intersectsTriangle:(d,u)=>{d.closestPointToPoint(e,pn);const f=e.distanceToSquared(pn);return f<a&&(Gs.copy(pn),a=f,c=u),f<o}}),a===1/0)return null;const h=Math.sqrt(a);return t.point?t.point.copy(Gs):t.point=Gs.clone(),t.distance=h,t.faceIndex=c,t}const Kn=parseInt(p.REVISION)>=169,Ga=parseInt(p.REVISION)<=161,Ft=new p.Vector3,Bt=new p.Vector3,zt=new p.Vector3,Xn=new p.Vector2,Yn=new p.Vector2,qn=new p.Vector2,nr=new p.Vector3,sr=new p.Vector3,ir=new p.Vector3,mn=new p.Vector3;function ja(i,e,t,n,s,o,r,a){let c;if(o===p.BackSide?c=i.intersectTriangle(n,t,e,!0,s):c=i.intersectTriangle(e,t,n,o!==p.DoubleSide,s),c===null)return null;const h=i.origin.distanceTo(s);return h<r||h>a?null:{distance:h,point:s.clone()}}function rr(i,e,t,n,s,o,r,a,c,h,d){Ft.fromBufferAttribute(e,o),Bt.fromBufferAttribute(e,r),zt.fromBufferAttribute(e,a);const u=ja(i,Ft,Bt,zt,mn,c,h,d);if(u){if(n){Xn.fromBufferAttribute(n,o),Yn.fromBufferAttribute(n,r),qn.fromBufferAttribute(n,a),u.uv=new p.Vector2;const m=p.Triangle.getInterpolation(mn,Ft,Bt,zt,Xn,Yn,qn,u.uv);Kn||(u.uv=m)}if(s){Xn.fromBufferAttribute(s,o),Yn.fromBufferAttribute(s,r),qn.fromBufferAttribute(s,a),u.uv1=new p.Vector2;const m=p.Triangle.getInterpolation(mn,Ft,Bt,zt,Xn,Yn,qn,u.uv1);Kn||(u.uv1=m),Ga&&(u.uv2=u.uv1)}if(t){nr.fromBufferAttribute(t,o),sr.fromBufferAttribute(t,r),ir.fromBufferAttribute(t,a),u.normal=new p.Vector3;const m=p.Triangle.getInterpolation(mn,Ft,Bt,zt,nr,sr,ir,u.normal);u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1),Kn||(u.normal=m)}const f={a:o,b:r,c:a,normal:new p.Vector3,materialIndex:0};if(p.Triangle.getNormal(Ft,Bt,zt,f.normal),u.face=f,u.faceIndex=o,Kn){const m=new p.Vector3;p.Triangle.getBarycoord(mn,Ft,Bt,zt,m),u.barycoord=m}}return u}function or(i){return i&&i.isMaterial?i.side:i}function Rs(i,e,t,n,s,o,r){const a=n*3;let c=a+0,h=a+1,d=a+2;const{index:u,groups:f}=i;i.index&&(c=u.getX(c),h=u.getX(h),d=u.getX(d));const{position:m,normal:E,uv:b,uv1:w}=i.attributes;if(Array.isArray(e)){const A=n*3;for(let S=0,_=f.length;S<_;S++){const{start:x,count:v,materialIndex:L}=f[S];if(A>=x&&A<x+v){const I=or(e[L]),C=rr(t,m,E,b,w,c,h,d,I,o,r);if(C)if(C.faceIndex=n,C.face.materialIndex=L,s)s.push(C);else return C}}}else{const A=or(e),S=rr(t,m,E,b,w,c,h,d,A,o,r);if(S)if(S.faceIndex=n,S.face.materialIndex=0,s)s.push(S);else return S}return null}function Ie(i,e,t,n){const s=i.a,o=i.b,r=i.c;let a=e,c=e+1,h=e+2;t&&(a=t.getX(a),c=t.getX(c),h=t.getX(h)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c),r.x=n.getX(h),r.y=n.getY(h),r.z=n.getZ(h)}function Wa(i,e,t,n,s,o,r,a){const{geometry:c,_indirectBuffer:h}=i;for(let d=n,u=n+s;d<u;d++)Rs(c,e,t,d,o,r,a)}function Za(i,e,t,n,s,o,r){const{geometry:a,_indirectBuffer:c}=i;let h=1/0,d=null;for(let u=n,f=n+s;u<f;u++){let m;m=Rs(a,e,t,u,null,o,r),m&&m.distance<h&&(d=m,h=m.distance)}return d}function Ka(i,e,t,n,s,o,r){const{geometry:a}=t,{index:c}=a,h=a.attributes.position;for(let d=i,u=e+i;d<u;d++){let f;if(f=d,Ie(r,f*3,c,h),r.needsUpdate=!0,n(r,f,s,o))return!0}return!1}function Xa(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let o,r,a,c,h=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)o=d[f],r=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,h),h+=o.byteLength;function u(f,m,E=!1){const b=f*2;if(Pe(b,a)){const w=Ve(f,r),A=Xe(b,a);let S=1/0,_=1/0,x=1/0,v=-1/0,L=-1/0,I=-1/0;for(let C=3*w,D=3*(w+A);C<D;C++){let P=n[C];const F=s.getX(P),k=s.getY(P),U=s.getZ(P);F<S&&(S=F),F>v&&(v=F),k<_&&(_=k),k>L&&(L=k),U<x&&(x=U),U>I&&(I=U)}return c[f+0]!==S||c[f+1]!==_||c[f+2]!==x||c[f+3]!==v||c[f+4]!==L||c[f+5]!==I?(c[f+0]=S,c[f+1]=_,c[f+2]=x,c[f+3]=v,c[f+4]=L,c[f+5]=I,!0):!1}else{const w=Fe(f),A=Be(f,r);let S=E,_=!1,x=!1;if(e){if(!S){const P=w/De+m/He,F=A/De+m/He;_=e.has(P),x=e.has(F),S=!_&&!x}}else _=!0,x=!0;const v=S||_,L=S||x;let I=!1;v&&(I=u(w,m,S));let C=!1;L&&(C=u(A,m,S));const D=I||C;if(D)for(let P=0;P<3;P++){const F=w+P,k=A+P,U=c[F],z=c[F+3],Y=c[k],re=c[k+3];c[f+P]=U<Y?U:Y,c[f+P+3]=z>re?z:re}return D}}}function Nt(i,e,t,n,s){let o,r,a,c,h,d;const u=1/t.direction.x,f=1/t.direction.y,m=1/t.direction.z,E=t.origin.x,b=t.origin.y,w=t.origin.z;let A=e[i],S=e[i+3],_=e[i+1],x=e[i+3+1],v=e[i+2],L=e[i+3+2];return u>=0?(o=(A-E)*u,r=(S-E)*u):(o=(S-E)*u,r=(A-E)*u),f>=0?(a=(_-b)*f,c=(x-b)*f):(a=(x-b)*f,c=(_-b)*f),o>c||a>r||((a>o||isNaN(o))&&(o=a),(c<r||isNaN(r))&&(r=c),m>=0?(h=(v-w)*m,d=(L-w)*m):(h=(L-w)*m,d=(v-w)*m),o>d||h>r)?!1:((h>o||o!==o)&&(o=h),(d<r||r!==r)&&(r=d),o<=s&&r>=n)}function Ya(i,e,t,n,s,o,r,a){const{geometry:c,_indirectBuffer:h}=i;for(let d=n,u=n+s;d<u;d++){let f=h?h[d]:d;Rs(c,e,t,f,o,r,a)}}function qa(i,e,t,n,s,o,r){const{geometry:a,_indirectBuffer:c}=i;let h=1/0,d=null;for(let u=n,f=n+s;u<f;u++){let m;m=Rs(a,e,t,c?c[u]:u,null,o,r),m&&m.distance<h&&(d=m,h=m.distance)}return d}function $a(i,e,t,n,s,o,r){const{geometry:a}=t,{index:c}=a,h=a.attributes.position;for(let d=i,u=e+i;d<u;d++){let f;if(f=t.resolveTriangleIndex(d),Ie(r,f*3,c,h),r.needsUpdate=!0,n(r,f,s,o))return!0}return!1}function Qa(i,e,t,n,s,o,r){xe.setBuffer(i._roots[e]),hi(0,i,t,n,s,o,r),xe.clearBuffer()}function hi(i,e,t,n,s,o,r){const{float32Array:a,uint16Array:c,uint32Array:h}=xe,d=i*2;if(Pe(d,c)){const f=Ve(i,h),m=Xe(d,c);Wa(e,t,n,f,m,s,o,r)}else{const f=Fe(i);Nt(f,a,n,o,r)&&hi(f,e,t,n,s,o,r);const m=Be(i,h);Nt(m,a,n,o,r)&&hi(m,e,t,n,s,o,r)}}const Ja=["x","y","z"];function ec(i,e,t,n,s,o){xe.setBuffer(i._roots[e]);const r=ui(0,i,t,n,s,o);return xe.clearBuffer(),r}function ui(i,e,t,n,s,o){const{float32Array:r,uint16Array:a,uint32Array:c}=xe;let h=i*2;if(Pe(h,a)){const u=Ve(i,c),f=Xe(h,a);return Za(e,t,n,u,f,s,o)}else{const u=xs(i,c),f=Ja[u],E=n.direction[f]>=0;let b,w;E?(b=Fe(i),w=Be(i,c)):(b=Be(i,c),w=Fe(i));const S=Nt(b,r,n,s,o)?ui(b,e,t,n,s,o):null;if(S){const v=S.point[f];if(E?v<=r[w+u]:v>=r[w+u+3])return S}const x=Nt(w,r,n,s,o)?ui(w,e,t,n,s,o):null;return S&&x?S.distance<=x.distance?S:x:S||x||null}}const $n=new p.Box3,qt=new ft,$t=new ft,gn=new p.Matrix4,ar=new Ye,Qn=new Ye;function tc(i,e,t,n){xe.setBuffer(i._roots[e]);const s=di(0,i,t,n);return xe.clearBuffer(),s}function di(i,e,t,n,s=null){const{float32Array:o,uint16Array:r,uint32Array:a}=xe;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),ar.set(t.boundingBox.min,t.boundingBox.max,n),s=ar),Pe(c,r)){const d=e.geometry,u=d.index,f=d.attributes.position,m=t.index,E=t.attributes.position,b=Ve(i,a),w=Xe(c,r);if(gn.copy(n).invert(),t.boundsTree)return Ae(i,o,Qn),Qn.matrix.copy(gn),Qn.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:S=>Qn.intersectsBox(S),intersectsTriangle:S=>{S.a.applyMatrix4(n),S.b.applyMatrix4(n),S.c.applyMatrix4(n),S.needsUpdate=!0;for(let _=b*3,x=(w+b)*3;_<x;_+=3)if(Ie($t,_,u,f),$t.needsUpdate=!0,S.intersectsTriangle($t))return!0;return!1}});{const A=vs(t);for(let S=b*3,_=(w+b)*3;S<_;S+=3){Ie(qt,S,u,f),qt.a.applyMatrix4(gn),qt.b.applyMatrix4(gn),qt.c.applyMatrix4(gn),qt.needsUpdate=!0;for(let x=0,v=A*3;x<v;x+=3)if(Ie($t,x,m,E),$t.needsUpdate=!0,qt.intersectsTriangle($t))return!0}}}else{const d=Fe(i),u=Be(i,a);return Ae(d,o,$n),!!(s.intersectsBox($n)&&di(d,e,t,n,s)||(Ae(u,o,$n),s.intersectsBox($n)&&di(u,e,t,n,s)))}}const Jn=new p.Matrix4,js=new Ye,yn=new Ye,nc=new p.Vector3,sc=new p.Vector3,ic=new p.Vector3,rc=new p.Vector3;function oc(i,e,t,n={},s={},o=0,r=1/0){e.boundingBox||e.computeBoundingBox(),js.set(e.boundingBox.min,e.boundingBox.max,t),js.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,h=a.index,d=e.attributes.position,u=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let E=nc,b=sc,w=null,A=null;s&&(w=ic,A=rc);let S=1/0,_=null,x=null;return Jn.copy(t).invert(),yn.matrix.copy(Jn),i.shapecast({boundsTraverseOrder:v=>js.distanceToBox(v),intersectsBounds:(v,L,I)=>I<S&&I<r?(L&&(yn.min.copy(v.min),yn.max.copy(v.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(v,L)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:C=>yn.distanceToBox(C),intersectsBounds:(C,D,P)=>P<S&&P<r,intersectsRange:(C,D)=>{for(let P=C,F=C+D;P<F;P++){Ie(m,3*P,u,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let k=v,U=v+L;k<U;k++){Ie(f,3*k,h,c),f.needsUpdate=!0;const z=f.distanceToTriangle(m,E,w);if(z<S&&(b.copy(E),A&&A.copy(w),S=z,_=k,x=P),z<o)return!0}}}});{const I=vs(e);for(let C=0,D=I;C<D;C++){Ie(m,3*C,u,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let P=v,F=v+L;P<F;P++){Ie(f,3*P,h,c),f.needsUpdate=!0;const k=f.distanceToTriangle(m,E,w);if(k<S&&(b.copy(E),A&&A.copy(w),S=k,_=P,x=C),k<o)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),S===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=S,n.faceIndex=_,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Jn),b.applyMatrix4(Jn),s.distance=b.sub(s.point).length(),s.faceIndex=x),n)}function ac(i,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=i.geometry,n=t.index?t.index.array:null,s=t.attributes.position;let o,r,a,c,h=0;const d=i._roots;for(let f=0,m=d.length;f<m;f++)o=d[f],r=new Uint32Array(o),a=new Uint16Array(o),c=new Float32Array(o),u(0,h),h+=o.byteLength;function u(f,m,E=!1){const b=f*2;if(Pe(b,a)){const w=Ve(f,r),A=Xe(b,a);let S=1/0,_=1/0,x=1/0,v=-1/0,L=-1/0,I=-1/0;for(let C=w,D=w+A;C<D;C++){const P=3*i.resolveTriangleIndex(C);for(let F=0;F<3;F++){let k=P+F;k=n?n[k]:k;const U=s.getX(k),z=s.getY(k),Y=s.getZ(k);U<S&&(S=U),U>v&&(v=U),z<_&&(_=z),z>L&&(L=z),Y<x&&(x=Y),Y>I&&(I=Y)}}return c[f+0]!==S||c[f+1]!==_||c[f+2]!==x||c[f+3]!==v||c[f+4]!==L||c[f+5]!==I?(c[f+0]=S,c[f+1]=_,c[f+2]=x,c[f+3]=v,c[f+4]=L,c[f+5]=I,!0):!1}else{const w=Fe(f),A=Be(f,r);let S=E,_=!1,x=!1;if(e){if(!S){const P=w/De+m/He,F=A/De+m/He;_=e.has(P),x=e.has(F),S=!_&&!x}}else _=!0,x=!0;const v=S||_,L=S||x;let I=!1;v&&(I=u(w,m,S));let C=!1;L&&(C=u(A,m,S));const D=I||C;if(D)for(let P=0;P<3;P++){const F=w+P,k=A+P,U=c[F],z=c[F+3],Y=c[k],re=c[k+3];c[f+P]=U<Y?U:Y,c[f+P+3]=z>re?z:re}return D}}}function cc(i,e,t,n,s,o,r){xe.setBuffer(i._roots[e]),fi(0,i,t,n,s,o,r),xe.clearBuffer()}function fi(i,e,t,n,s,o,r){const{float32Array:a,uint16Array:c,uint32Array:h}=xe,d=i*2;if(Pe(d,c)){const f=Ve(i,h),m=Xe(d,c);Ya(e,t,n,f,m,s,o,r)}else{const f=Fe(i);Nt(f,a,n,o,r)&&fi(f,e,t,n,s,o,r);const m=Be(i,h);Nt(m,a,n,o,r)&&fi(m,e,t,n,s,o,r)}}const lc=["x","y","z"];function hc(i,e,t,n,s,o){xe.setBuffer(i._roots[e]);const r=pi(0,i,t,n,s,o);return xe.clearBuffer(),r}function pi(i,e,t,n,s,o){const{float32Array:r,uint16Array:a,uint32Array:c}=xe;let h=i*2;if(Pe(h,a)){const u=Ve(i,c),f=Xe(h,a);return qa(e,t,n,u,f,s,o)}else{const u=xs(i,c),f=lc[u],E=n.direction[f]>=0;let b,w;E?(b=Fe(i),w=Be(i,c)):(b=Be(i,c),w=Fe(i));const S=Nt(b,r,n,s,o)?pi(b,e,t,n,s,o):null;if(S){const v=S.point[f];if(E?v<=r[w+u]:v>=r[w+u+3])return S}const x=Nt(w,r,n,s,o)?pi(w,e,t,n,s,o):null;return S&&x?S.distance<=x.distance?S:x:S||x||null}}const es=new p.Box3,Qt=new ft,Jt=new ft,En=new p.Matrix4,cr=new Ye,ts=new Ye;function uc(i,e,t,n){xe.setBuffer(i._roots[e]);const s=mi(0,i,t,n);return xe.clearBuffer(),s}function mi(i,e,t,n,s=null){const{float32Array:o,uint16Array:r,uint32Array:a}=xe;let c=i*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),cr.set(t.boundingBox.min,t.boundingBox.max,n),s=cr),Pe(c,r)){const d=e.geometry,u=d.index,f=d.attributes.position,m=t.index,E=t.attributes.position,b=Ve(i,a),w=Xe(c,r);if(En.copy(n).invert(),t.boundsTree)return Ae(i,o,ts),ts.matrix.copy(En),ts.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:S=>ts.intersectsBox(S),intersectsTriangle:S=>{S.a.applyMatrix4(n),S.b.applyMatrix4(n),S.c.applyMatrix4(n),S.needsUpdate=!0;for(let _=b,x=w+b;_<x;_++)if(Ie(Jt,3*e.resolveTriangleIndex(_),u,f),Jt.needsUpdate=!0,S.intersectsTriangle(Jt))return!0;return!1}});{const A=vs(t);for(let S=b,_=w+b;S<_;S++){const x=e.resolveTriangleIndex(S);Ie(Qt,3*x,u,f),Qt.a.applyMatrix4(En),Qt.b.applyMatrix4(En),Qt.c.applyMatrix4(En),Qt.needsUpdate=!0;for(let v=0,L=A*3;v<L;v+=3)if(Ie(Jt,v,m,E),Jt.needsUpdate=!0,Qt.intersectsTriangle(Jt))return!0}}}else{const d=Fe(i),u=Be(i,a);return Ae(d,o,es),!!(s.intersectsBox(es)&&mi(d,e,t,n,s)||(Ae(u,o,es),s.intersectsBox(es)&&mi(u,e,t,n,s)))}}const ns=new p.Matrix4,Ws=new Ye,Tn=new Ye,dc=new p.Vector3,fc=new p.Vector3,pc=new p.Vector3,mc=new p.Vector3;function gc(i,e,t,n={},s={},o=0,r=1/0){e.boundingBox||e.computeBoundingBox(),Ws.set(e.boundingBox.min,e.boundingBox.max,t),Ws.needsUpdate=!0;const a=i.geometry,c=a.attributes.position,h=a.index,d=e.attributes.position,u=e.index,f=rt.getPrimitive(),m=rt.getPrimitive();let E=dc,b=fc,w=null,A=null;s&&(w=pc,A=mc);let S=1/0,_=null,x=null;return ns.copy(t).invert(),Tn.matrix.copy(ns),i.shapecast({boundsTraverseOrder:v=>Ws.distanceToBox(v),intersectsBounds:(v,L,I)=>I<S&&I<r?(L&&(Tn.min.copy(v.min),Tn.max.copy(v.max),Tn.needsUpdate=!0),!0):!1,intersectsRange:(v,L)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:C=>Tn.distanceToBox(C),intersectsBounds:(C,D,P)=>P<S&&P<r,intersectsRange:(C,D)=>{for(let P=C,F=C+D;P<F;P++){const k=I.resolveTriangleIndex(P);Ie(m,3*k,u,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let U=v,z=v+L;U<z;U++){const Y=i.resolveTriangleIndex(U);Ie(f,3*Y,h,c),f.needsUpdate=!0;const re=f.distanceToTriangle(m,E,w);if(re<S&&(b.copy(E),A&&A.copy(w),S=re,_=U,x=P),re<o)return!0}}}})}else{const I=vs(e);for(let C=0,D=I;C<D;C++){Ie(m,3*C,u,d),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let P=v,F=v+L;P<F;P++){const k=i.resolveTriangleIndex(P);Ie(f,3*k,h,c),f.needsUpdate=!0;const U=f.distanceToTriangle(m,E,w);if(U<S&&(b.copy(E),A&&A.copy(w),S=U,_=P,x=C),U<o)return!0}}}}}),rt.releasePrimitive(f),rt.releasePrimitive(m),S===1/0?null:(n.point?n.point.copy(b):n.point=b.clone(),n.distance=S,n.faceIndex=_,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(ns),b.applyMatrix4(ns),s.distance=b.sub(s.point).length(),s.faceIndex=x),n)}function lr(i,e,t){return i===null?null:(i.point.applyMatrix4(e.matrixWorld),i.distance=i.point.distanceTo(t.ray.origin),i.object=e,i)}const ss=new Ye,is=new p.Ray,hr=new p.Vector3,ur=new p.Matrix4,dr=new p.Vector3,Zs=["getX","getY","getZ"];class Rn extends Fa{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,s=e._roots,o=e._indirectBuffer,r=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(c=>c.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=o?o.slice():null):(a.roots=s,a.index=r?r.array:null,a.indirectBuffer=o),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:s,roots:o,indirectBuffer:r}=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 Rn(t,{...n,[vi]:!0});if(a._roots=o,a._indirectBuffer=r||null,n.setIndex){const h=t.getIndex();if(h===null){const d=new p.BufferAttribute(e.index,1,!1);t.setIndex(d)}else h.array!==s&&(h.array.set(s),h.needsUpdate=!0)}return a;function c(h){for(let d=0;d<h.length;d++){const u=h[d],f=new Uint32Array(u),m=new Uint16Array(u);for(let E=0,b=u.byteLength/He;E<b;E++){const w=De*E,A=2*w;Pe(A,m)||(f[w+6]=f[w+6]/De-E)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,n){const s=this.geometry,o=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,h=(o?o[e]:e)*3;let d=h+0,u=h+1,f=h+2;a&&(d=a[d],u=a[u],f=a[f]);for(let m=0;m<3;m++){const E=r[Zs[m]](d),b=r[Zs[m]](u),w=r[Zs[m]](f);let A=E;b<A&&(A=b),w<A&&(A=w);let S=E;b>S&&(S=b),w>S&&(S=w),t[n+m]=A,t[n+m+3]=S}return t}computePrimitiveBounds(e,t,n){const s=this.geometry,o=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,c=r.normalized;if(e<0||t+e-n.offset>n.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const h=r.array,d=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const f=["getX","getY","getZ"],m=n.offset;for(let E=e,b=e+t;E<b;E++){const A=(o?o[E]:E)*3,S=(E-m)*6;let _=A+0,x=A+1,v=A+2;a&&(_=a[_],x=a[x],v=a[v]),c||(_=_*u+d,x=x*u+d,v=v*u+d);for(let L=0;L<3;L++){let I,C,D;c?(I=r[f[L]](_),C=r[f[L]](x),D=r[f[L]](v)):(I=h[_+L],C=h[x+L],D=h[v+L]);let P=I;C<P&&(P=C),D<P&&(P=D);let F=I;C>F&&(F=C),D>F&&(F=D);const k=(F-P)/2,U=L*2;n[S+U+0]=P+k,n[S+U+1]=k+(Math.abs(P)+k)*fs}}return n}raycastObject3D(e,t,n=[]){const{material:s}=e;if(s===void 0)return;ur.copy(e.matrixWorld).invert(),is.copy(t.ray).applyMatrix4(ur),dr.setFromMatrixScale(e.matrixWorld),hr.copy(is.direction).multiply(dr);const o=hr.length(),r=t.near/o,a=t.far/o;if(t.firstHitOnly===!0){let c=this.raycastFirst(is,s,r,a);c=lr(c,e,t),c&&n.push(c)}else{const c=this.raycast(is,s,r,a);for(let h=0,d=c.length;h<d;h++){const u=lr(c[h],e,t);u&&n.push(u)}}return n}refit(e=null){return(this.indirect?ac:Xa)(this,e)}raycast(e,t=p.FrontSide,n=0,s=1/0){const o=this._roots,r=[],a=this.indirect?cc:Qa;for(let c=0,h=o.length;c<h;c++)a(this,c,t,e,r,n,s);return r}raycastFirst(e,t=p.FrontSide,n=0,s=1/0){const o=this._roots;let r=null;const a=this.indirect?hc:ec;for(let c=0,h=o.length;c<h;c++){const d=a(this,c,t,e,n,s);d!=null&&(r==null||d.distance<r.distance)&&(r=d)}return r}intersectsGeometry(e,t){let n=!1;const s=this._roots,o=this.indirect?uc:tc;for(let r=0,a=s.length;r<a&&(n=o(this,r,e,t),!n);r++);return n}shapecast(e){const t=rt.getPrimitive(),n=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?$a:Ka});return rt.releasePrimitive(t),n}bvhcast(e,t,n){let{intersectsRanges:s,intersectsTriangles:o}=n;const r=rt.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,h=this.indirect?E=>{const b=this.resolveTriangleIndex(E);Ie(r,b*3,a,c)}:E=>{Ie(r,E*3,a,c)},d=rt.getPrimitive(),u=e.geometry.index,f=e.geometry.attributes.position,m=e.indirect?E=>{const b=e.resolveTriangleIndex(E);Ie(d,b*3,u,f)}:E=>{Ie(d,E*3,u,f)};if(o){if(!(e instanceof Rn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const E=(b,w,A,S,_,x,v,L)=>{for(let I=A,C=A+S;I<C;I++){m(I),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let D=b,P=b+w;D<P;D++)if(h(D),r.needsUpdate=!0,o(r,d,D,I,_,x,v,L))return!0}return!1};if(s){const b=s;s=function(w,A,S,_,x,v,L,I){return b(w,A,S,_,x,v,L,I)?!0:E(w,A,S,_,x,v,L,I)}}else s=E}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return ss.set(e.min,e.max,t),ss.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ss.intersectsBox(n),intersectsTriangle:n=>ss.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},s={},o=0,r=1/0){return(this.indirect?gc:oc)(this,e,t,n,s,o,r)}closestPointToPoint(e,t={},n=0,s=1/0){return Va(this,e,t,n,s)}}const nn={Mesh:p.Mesh.prototype.raycast,Line:p.Line.prototype.raycast,LineSegments:p.LineSegments.prototype.raycast,LineLoop:p.LineLoop.prototype.raycast,Points:p.Points.prototype.raycast,BatchedMesh:p.BatchedMesh.prototype.raycast},Ue=new p.Mesh,rs=[];function yc(i,e){if(this.isBatchedMesh)Ec.call(this,i,e);else{const{geometry:t}=this;if(t.boundsTree)t.boundsTree.raycastObject3D(this,i,e);else{let n;if(this instanceof p.Mesh)n=nn.Mesh;else if(this instanceof p.LineSegments)n=nn.LineSegments;else if(this instanceof p.LineLoop)n=nn.LineLoop;else if(this instanceof p.Line)n=nn.Line;else if(this instanceof p.Points)n=nn.Points;else throw new Error("BVH: Fallback raycast function not found.");n.call(this,i,e)}}}function Ec(i,e){if(this.boundsTrees){const t=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,o=this.matrixWorld;Ue.material=this.material,Ue.geometry=this.geometry;const r=Ue.geometry.boundsTree,a=Ue.geometry.drawRange;Ue.geometry.boundingSphere===null&&(Ue.geometry.boundingSphere=new p.Sphere);for(let c=0,h=n.length;c<h;c++){if(!this.getVisibleAt(c))continue;const d=n[c].geometryIndex;if(Ue.geometry.boundsTree=t[d],this.getMatrixAt(c,Ue.matrixWorld).premultiply(o),!Ue.geometry.boundsTree){this.getBoundingBoxAt(d,Ue.geometry.boundingBox),this.getBoundingSphereAt(d,Ue.geometry.boundingSphere);const u=s[d];Ue.geometry.setDrawRange(u.start,u.count)}Ue.raycast(i,rs);for(let u=0,f=rs.length;u<f;u++){const m=rs[u];m.object=this,m.batchId=c,e.push(m)}rs.length=0}Ue.geometry.boundsTree=r,Ue.geometry.drawRange=a,Ue.material=null,Ue.geometry=null}else nn.BatchedMesh.call(this,i,e)}function jr(i){i.traverse(e=>{var s,o,r;const t=e;if(!t.isMesh||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh)return;const n=t.geometry;!((s=n==null?void 0:n.attributes)!=null&&s.position)||(r=(o=n.morphAttributes)==null?void 0:o.position)!=null&&r.length||(n.boundsTree||(n.boundsTree=new Rn(n)),t.raycast=yc)})}function Tc(i){i.boundsTree&&(i.boundsTree=void 0)}function fr(i){const e=i;for(const n of Object.keys(e)){const s=e[n];s instanceof y.Texture&&s.dispose()}const t=i;if(t.isShaderMaterial&&t.uniforms)for(const n of Object.values(t.uniforms))(n==null?void 0:n.value)instanceof y.Texture&&n.value.dispose();i.dispose()}function Ms(i){i.traverse(e=>{var o;const t=e;t.geometry&&typeof t.geometry.dispose=="function"&&(Tc(t.geometry),t.geometry.dispose());const n=t.material;Array.isArray(n)?n.forEach(fr):n&&fr(n);const s=e;s.isLight&&((o=s.shadow)!=null&&o.dispose)&&s.shadow.dispose()})}function wc(i,e){if(!(e!=null&&e.keepBackgrounds)){i.background instanceof y.Texture&&(i.background.dispose(),i.background=null),i.environment instanceof y.Texture&&(i.environment.dispose(),i.environment=null);const t=i;t.__originalEnvironmentTexture&&(t.__originalEnvironmentTexture=void 0)}for(const t of[...i.children])Ms(t),i.remove(t)}class Ke{constructor(e){this.object=e,this.positionAdapter=Dt.fromThreeVector(e.position),this.rotationAdapter=Dt.fromThreeVector(e.rotation),this.scaleAdapter=Dt.fromThreeVector(e.scale)}get id(){return this.object.uuid}get name(){return this.object.name}set name(e){this.object.name=e}get visible(){return this.object.visible}set visible(e){this.object.visible=e}get castShadow(){return this.object.castShadow}set castShadow(e){this.object.castShadow=e}get receiveShadow(){return this.object.receiveShadow}set receiveShadow(e){this.object.receiveShadow=e}get position(){return this.positionAdapter}get rotation(){return this.rotationAdapter}get scale(){return this.scaleAdapter}add(e){try{return e instanceof Ke?(this.object.add(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Child must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to add child object",K.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ke?(this.object.remove(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Child must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to remove child object",K.SCENE_OPERATION_FAILED,{originalError:t}))}}traverse(e){this.object.traverse(t=>{e(new Ke(t))})}clone(){return new Ke(this.object.clone())}dispose(){Ms(this.object)}getThreeObject(){return this.object}static fromThreeObject(e){return new Ke(e)}static create(){return new Ke(new y.Object3D)}}class gi{constructor(e){this.scene=e||new y.Scene}get id(){return this.scene.uuid}get name(){return this.scene.name}set name(e){this.scene.name=e}add(e){try{return e instanceof Ke?(this.scene.add(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Object must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to add object to scene",K.SCENE_OPERATION_FAILED,{originalError:t}))}}remove(e){try{return e instanceof Ke?(this.scene.remove(e.getThreeObject()),N.ok(void 0)):N.err(new Z("Object must be a ThreeObject3DAdapter",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to remove object from scene",K.SCENE_OPERATION_FAILED,{originalError:t}))}}clear(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeContents(e){wc(this.scene,e)}traverse(e){this.scene.traverse(t=>{e(new Ke(t))})}get background(){return this.scene.background instanceof y.Color?new yi(this.scene.background):this.scene.background instanceof y.Texture?new os(this.scene.background):null}set background(e){e instanceof yi?this.scene.background=e.getThreeColor():e instanceof os?this.scene.background=e.getThreeTexture():this.scene.background=null}get fog(){return this.scene.fog?new pr(this.scene.fog):null}set fog(e){e instanceof pr?this.scene.fog=e.getThreeFog():this.scene.fog=null}get environment(){return this.scene.environment?new os(this.scene.environment):null}set environment(e){e instanceof os?this.scene.environment=e.getThreeTexture():this.scene.environment=null}setEnvironmentIntensity(e){this.scene.environmentIntensity=e}getInternalRenderer(){return this.scene}getThreeScene(){return this.scene}}class yi{constructor(e){this.color=e}get r(){return this.color.r}set r(e){this.color.r=e}get g(){return this.color.g}set g(e){this.color.g=e}get b(){return this.color.b}set b(e){this.color.b=e}setHex(e){this.color.setHex(e)}setRGB(e,t,n){this.color.setRGB(e,t,n)}getHex(){return this.color.getHex()}getThreeColor(){return this.color}}let os=class{constructor(e){this.texture=e}get id(){return this.texture.uuid}get image(){return this.texture.image||null}get needsUpdate(){return this.texture.needsUpdate}set needsUpdate(e){this.texture.needsUpdate=e}dispose(){this.texture.dispose()}getThreeTexture(){return this.texture}};class pr{constructor(e){this.fog=e}get color(){return new yi(this.fog.color)}get near(){return this.fog.near||0}get far(){return this.fog.far||1e3}getThreeFog(){return this.fog}}class Ei extends Ke{constructor(e){super(e),this.camera=e}get near(){return this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera?this.camera.near:.1}set near(e){(this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera)&&(this.camera.near=e)}get far(){return this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera?this.camera.far:1e3}set far(e){(this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera)&&(this.camera.far=e)}lookAt(e){e instanceof Dt?this.camera.lookAt(e.getThreeVector()):this.camera.lookAt(e.x,e.y,e.z)}updateProjectionMatrix(){(this.camera instanceof y.PerspectiveCamera||this.camera instanceof y.OrthographicCamera)&&this.camera.updateProjectionMatrix()}getWorldDirection(e){const t=new y.Vector3;this.camera.getWorldDirection(t),e.set(t.x,t.y,t.z)}getInternalRenderer(){return this.camera}getThreeCamera(){return this.camera}}class Ci extends Ei{constructor(e){const t=e||new y.PerspectiveCamera;super(t),this.perspectiveCamera=t}get type(){return"perspective"}get fov(){return this.perspectiveCamera.fov}set fov(e){this.perspectiveCamera.fov=e}get aspect(){return this.perspectiveCamera.aspect}set aspect(e){this.perspectiveCamera.aspect=e}static create(e=30,t=1,n=.1,s=1e3){return new Ci(new y.PerspectiveCamera(e,t,n,s))}}const _s=class _s{static convertRendererOptions(e){const t={antialias:e.antialias,alpha:e.alpha,premultipliedAlpha:e.premultipliedAlpha,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference,pixelRatio:e.pixelRatio};(e.shadowMapEnabled!==void 0||e.shadowMapType!==void 0)&&(t.shadowMap={enabled:e.shadowMapEnabled??!0,type:this.convertShadowMapType(e.shadowMapType)}),(e.toneMapping!==void 0||e.toneMappingExposure!==void 0)&&(t.toneMapping={type:this.convertToneMappingType(e.toneMapping),exposure:e.toneMappingExposure??1});const n=e.bloom,s=e.vignette,o=e.filmGrain,r=this.resolveColorGrade(e.colorGrade);return(n||s||o||r)&&(t.postProcessing={bloom:n??!1,vignette:s??!1,filmGrain:o??!1,colorGrade:r}),t}static resolveColorGrade(e){if(e){if(e===!0)return{contrast:this.DEFAULT_GRADE_CONTRAST,saturation:this.DEFAULT_GRADE_SATURATION};if(typeof e=="object"){const t=e;return{contrast:t.contrast??this.DEFAULT_GRADE_CONTRAST,saturation:t.saturation??this.DEFAULT_GRADE_SATURATION}}}}static convertShadowMapType(e){if(typeof e=="number"){if(e===y.BasicShadowMap)return"basic";if(e===y.PCFShadowMap)return"pcf";if(e===y.PCFSoftShadowMap)return"pcfsoft";if(e===y.VSMShadowMap)return"vsm"}return typeof e=="string"?e:void 0}static convertToneMappingType(e){if(typeof e=="number"){if(e===y.NoToneMapping)return"none";if(e===y.LinearToneMapping)return"linear";if(e===y.ReinhardToneMapping)return"reinhard";if(e===y.CineonToneMapping)return"cineon";if(e===y.ACESFilmicToneMapping)return"aces";if(e===y.AgXToneMapping)return"agx";if(e===y.NeutralToneMapping)return"neutral"}return typeof e=="string"?e:"neutral"}};_s.DEFAULT_GRADE_CONTRAST=.12,_s.DEFAULT_GRADE_SATURATION=.15;let Es=_s;function mr(i){return i.bloom||i.vignette||i.filmGrain||i.colorGrade!==null}const Sc=.08,_c=.25,bc=2.5,xc=1.15,Ac=1.05,vc=.05,Rc={uniforms:{tDiffuse:{value:null},intensity:{value:vc}},vertexShader:`
|
|
2
|
-
varying vec2 vUv;
|
|
3
|
-
void main() {
|
|
4
|
-
vUv = uv;
|
|
5
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
6
|
-
}
|
|
7
|
-
`,fragmentShader:`
|
|
8
|
-
uniform sampler2D tDiffuse;
|
|
9
|
-
uniform float intensity;
|
|
10
|
-
varying vec2 vUv;
|
|
11
|
-
float hash( vec2 p ) {
|
|
12
|
-
return fract( sin( dot( p, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );
|
|
13
|
-
}
|
|
14
|
-
void main() {
|
|
15
|
-
vec4 color = texture2D( tDiffuse, vUv );
|
|
16
|
-
float grain = hash( floor( gl_FragCoord.xy ) ) - 0.5;
|
|
17
|
-
gl_FragColor = vec4( color.rgb + grain * intensity, color.a );
|
|
18
|
-
}
|
|
19
|
-
`};class gr{constructor(e,t){this.modules=null,this.composer=null,this.renderPass=null,this.disposed=!1,this.loadFailed=!1,this.renderer=e,this.config=t,this.load()}async load(){try{const e=this.config.colorGrade!==null,t=this.config.vignette||this.config.filmGrain||e,[n,s,o,r,a,c,h]=await Promise.all([Promise.resolve().then(()=>require("./EffectComposer-D2IQ0sek.cjs")),Promise.resolve().then(()=>require("./RenderPass-BVzyKWsC.cjs")),Promise.resolve().then(()=>require("./OutputPass-Dy4KNHYF.cjs")),this.config.bloom?Promise.resolve().then(()=>require("./UnrealBloomPass-Kx7djcld.cjs")):Promise.resolve(null),t?Promise.resolve().then(()=>require("./ShaderPass-BQRqK8zp.cjs")):Promise.resolve(null),this.config.vignette?Promise.resolve().then(()=>require("./VignetteShader-Drpo9YxI.cjs")):Promise.resolve(null),e?Promise.all([Promise.resolve().then(()=>require("./BrightnessContrastShader-BN6FBcLV.cjs")),Promise.resolve().then(()=>require("./HueSaturationShader-BEp7jjxf.cjs"))]):Promise.resolve(null)]);if(this.disposed)return;this.modules={EffectComposer:n.EffectComposer,RenderPass:s.RenderPass,OutputPass:o.OutputPass,UnrealBloomPass:r==null?void 0:r.UnrealBloomPass,ShaderPass:a==null?void 0:a.ShaderPass,VignetteShader:c==null?void 0:c.VignetteShader,BrightnessContrastShader:h==null?void 0:h[0].BrightnessContrastShader,HueSaturationShader:h==null?void 0:h[1].HueSaturationShader}}catch(e){this.loadFailed=!0,console.warn("Failed to load post-processing effects; falling back to the plain renderer:",e)}}isReady(){return this.modules!==null&&!this.disposed&&!this.loadFailed}render(e,t){const n=this.modules;if(n===null||this.disposed||this.loadFailed)return!1;const s=this.composer??this.build(n,e,t);return this.renderPass&&(this.renderPass.scene=e,this.renderPass.camera=t),s.render(),!0}build(e,t,n){const s=this.renderer.getDrawingBufferSize(new y.Vector2),o=new e.EffectComposer(this.renderer),r=Math.min(4,this.renderer.capabilities.maxSamples||0);r>0&&(o.renderTarget1.samples=r,o.renderTarget2.samples=r);const a=new e.RenderPass(t,n);this.renderPass=a,o.addPass(a),this.config.bloom&&e.UnrealBloomPass&&o.addPass(new e.UnrealBloomPass(new y.Vector2(s.x,s.y),Sc,_c,bc)),o.addPass(new e.OutputPass);const c=this.config.colorGrade;if(c&&e.ShaderPass&&e.BrightnessContrastShader&&e.HueSaturationShader){const h=new e.ShaderPass(e.BrightnessContrastShader);h.uniforms.contrast.value=c.contrast,o.addPass(h);const d=new e.ShaderPass(e.HueSaturationShader);d.uniforms.saturation.value=c.saturation,o.addPass(d)}if(this.config.vignette&&e.ShaderPass&&e.VignetteShader){const h=new e.ShaderPass(e.VignetteShader);h.uniforms.offset.value=xc,h.uniforms.darkness.value=Ac,o.addPass(h)}return this.config.filmGrain&&e.ShaderPass&&o.addPass(new e.ShaderPass(Rc)),this.composer=o,o}setSize(e,t){var n;(n=this.composer)==null||n.setSize(e,t)}setPixelRatio(e){var t,n;(n=(t=this.composer)==null?void 0:t.setPixelRatio)==null||n.call(t,e)}dispose(){var e,t;this.disposed=!0,(t=(e=this.composer)==null?void 0:e.dispose)==null||t.call(e),this.composer=null,this.renderPass=null,this.modules=null}}class Mc{constructor(e){this.renderer=null,this._id=Fr(),this.postPipeline=null,this.requestedPixelRatio=1,this.canvas=e}get id(){return this._id}initialize(e){var t,n,s,o;try{if(this.renderer=new y.WebGLRenderer({canvas:this.canvas,antialias:e.antialias??!0,alpha:e.alpha??!1,premultipliedAlpha:e.premultipliedAlpha??!0,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"default"}),e.shadowMap&&(this.renderer.shadowMap.enabled=e.shadowMap.enabled,this.renderer.shadowMap.autoUpdate=!0,e.shadowMap.type)){const c={basic:y.BasicShadowMap,pcf:y.PCFShadowMap,pcfsoft:y.PCFSoftShadowMap,vsm:y.VSMShadowMap};this.renderer.shadowMap.type=c[e.shadowMap.type]}if(e.toneMapping){const c={none:y.NoToneMapping,linear:y.LinearToneMapping,reinhard:y.ReinhardToneMapping,cineon:y.CineonToneMapping,aces:y.ACESFilmicToneMapping,agx:y.AgXToneMapping,neutral:y.NeutralToneMapping};this.renderer.toneMapping=c[e.toneMapping.type],this.renderer.toneMappingExposure=e.toneMapping.exposure}const r={bloom:((t=e.postProcessing)==null?void 0:t.bloom)??!1,vignette:((n=e.postProcessing)==null?void 0:n.vignette)??!1,filmGrain:((s=e.postProcessing)==null?void 0:s.filmGrain)??!1,colorGrade:((o=e.postProcessing)==null?void 0:o.colorGrade)??null},a=mr(r);if(this.requestedPixelRatio=e.pixelRatio??window.devicePixelRatio,this.renderer.setPixelRatio(a?Math.min(this.requestedPixelRatio,2):this.requestedPixelRatio),this.canvas){const{clientWidth:c,clientHeight:h}=this.canvas.parentElement||this.canvas;c&&h&&this.renderer.setSize(c,h)}return this.renderer.outputColorSpace=y.SRGBColorSpace,a&&(this.postPipeline=new gr(this.renderer,r)),N.ok(void 0)}catch(r){return N.err(new Z("Failed to initialize renderer",K.RENDERER_INIT_FAILED,{originalError:r,options:e}))}}render(e,t){if(!this.renderer)return N.err(new Z("Renderer not initialized",K.RENDERER_NOT_INITIALIZED));try{if(!(e instanceof gi))return N.err(new Z("Scene must be a ThreeSceneAdapter",K.INVALID_PARAMETER));if(!(t instanceof Ei))return N.err(new Z("Camera must be a ThreeCameraAdapter",K.INVALID_PARAMETER));const n=e.getThreeScene(),s=t.getThreeCamera();return this.renderer.render(n,s),N.ok(void 0)}catch(n){return N.err(new Z("Failed to render frame",K.RENDER_FAILED,{originalError:n}))}}renderPostProcessed(e,t){if(!this.postPipeline||!this.renderer||!(e instanceof gi)||!(t instanceof Ei))return this.render(e,t);try{return this.postPipeline.render(e.getThreeScene(),t.getThreeCamera())?N.ok(void 0):this.render(e,t)}catch(n){return N.err(new Z("Failed to render frame with post-processing",K.RENDER_FAILED,{originalError:n}))}}setSize(e,t){var n;if(this.renderer){this.renderer.setSize(e,t,!1),(n=this.postPipeline)==null||n.setSize(e,t);const s=this.renderer.domElement;s.style.width="100%",s.style.height="100%"}}setPixelRatio(e){var t;this.renderer&&(this.renderer.setPixelRatio(e),(t=this.postPipeline)==null||t.setPixelRatio(e))}getPixelRatio(){return this.renderer?this.renderer.getPixelRatio():1}setToneMappingExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}setPostProcessing(e){var s;if(!this.renderer)return;const t={bloom:e.bloom,vignette:e.vignette,filmGrain:e.filmGrain,colorGrade:Es.resolveColorGrade(e.colorGrade)??null};(s=this.postPipeline)==null||s.dispose(),this.postPipeline=null;const n=mr(t);this.renderer.setPixelRatio(n?Math.min(this.requestedPixelRatio,2):this.requestedPixelRatio),n&&(this.postPipeline=new gr(this.renderer,t))}getDomElement(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.domElement}getContext(){if(!this.renderer)throw new Error("Renderer not initialized");return this.renderer.getContext()}get capabilities(){if(!this.renderer)return{maxTextureSize:0,maxCubemapSize:0,maxAttributes:0,maxVertexUniforms:0,maxFragmentUniforms:0,maxSamples:0,isWebGL2:!1};const e=this.renderer.capabilities;return{maxTextureSize:e.maxTextureSize,maxCubemapSize:e.maxCubemapSize,maxAttributes:e.maxAttributes,maxVertexUniforms:e.maxVertexUniforms,maxFragmentUniforms:e.maxFragmentUniforms,maxSamples:e.maxSamples||0,isWebGL2:e.isWebGL2}}dispose(){var e;(e=this.postPipeline)==null||e.dispose(),this.postPipeline=null,this.renderer&&(this.renderer.dispose(),this.renderer=null)}isDisposed(){return this.renderer===null}getInternalRenderer(){return this.renderer}getThreeRenderer(){return this.getInternalRenderer()}}function yr(i,e){if(e===p.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===p.TriangleFanDrawMode||e===p.TriangleStripDrawMode){let t=i.getIndex();if(t===null){const r=[],a=i.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)r.push(c);i.setIndex(r),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===p.TriangleFanDrawMode)for(let r=1;r<=n;r++)s.push(t.getX(0)),s.push(t.getX(r)),s.push(t.getX(r+1));else for(let r=0;r<n;r++)r%2===0?(s.push(t.getX(r)),s.push(t.getX(r+1)),s.push(t.getX(r+2))):(s.push(t.getX(r+2)),s.push(t.getX(r+1)),s.push(t.getX(r)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=i.clone();return o.setIndex(s),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}function Cc(i){const e=new Map,t=new Map,n=i.clone();return Wr(i,n,function(s,o){e.set(o,s),t.set(s,o)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const o=s,r=e.get(s),a=r.skeleton.bones;o.skeleton=r.skeleton.clone(),o.bindMatrix.copy(r.bindMatrix),o.skeleton.bones=a.map(function(c){return t.get(c)}),o.bind(o.skeleton,o.bindMatrix)}),n}function Wr(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)Wr(i.children[n],e.children[n],t)}class Pc extends p.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Nc(t)}),this.register(function(t){return new kc(t)}),this.register(function(t){return new Wc(t)}),this.register(function(t){return new Zc(t)}),this.register(function(t){return new Kc(t)}),this.register(function(t){return new Bc(t)}),this.register(function(t){return new zc(t)}),this.register(function(t){return new Uc(t)}),this.register(function(t){return new Hc(t)}),this.register(function(t){return new Dc(t)}),this.register(function(t){return new Vc(t)}),this.register(function(t){return new Fc(t)}),this.register(function(t){return new jc(t)}),this.register(function(t){return new Gc(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new Er(t,le.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new Er(t,le.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Xc(t)})}load(e,t,n,s){const o=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const h=p.LoaderUtils.extractUrlBase(e);r=p.LoaderUtils.resolveURL(h,this.path)}else r=p.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(h){s?s(h):console.error(h),o.manager.itemError(e),o.manager.itemEnd(e)},c=new p.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(h){try{o.parse(h,r,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,s){let o;const r={},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))===Zr){try{r[le.KHR_BINARY_GLTF]=new Yc(e)}catch(u){s&&s(u);return}o=JSON.parse(r[le.KHR_BINARY_GLTF].content)}else o=JSON.parse(c.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new cl(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const u=this.pluginCallbacks[d](h);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,r[u.name]=!0}if(o.extensionsUsed)for(let d=0;d<o.extensionsUsed.length;++d){const u=o.extensionsUsed[d],f=o.extensionsRequired||[];switch(u){case le.KHR_MATERIALS_UNLIT:r[u]=new Oc;break;case le.KHR_DRACO_MESH_COMPRESSION:r[u]=new qc(o,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:r[u]=new $c;break;case le.KHR_MESH_QUANTIZATION:r[u]=new Qc;break;default:f.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}h.setExtensions(r),h.setPlugins(a),h.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,o){n.parse(e,t,s,o)})}}function Ic(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function Re(i,e,t){const n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class Lc{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const 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 s=t.cache.get(n);if(s)return s;const o=t.json,c=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let h;const d=new p.Color(16777215);c.color!==void 0&&d.setRGB(c.color[0],c.color[1],c.color[2],p.LinearSRGBColorSpace);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":h=new p.DirectionalLight(d),h.target.position.set(0,0,-1),h.add(h.target);break;case"point":h=new p.PointLight(d),h.distance=u;break;case"spot":h=new p.SpotLight(d),h.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,h.angle=c.spot.outerConeAngle,h.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,h.target.position.set(0,0,-1),h.add(h.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return h.position.set(0,0,0),Et(h,c),c.intensity!==void 0&&(h.intensity=c.intensity),h.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(h),t.cache.add(n,s),s}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 Oc{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return p.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new p.Color(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const r=o.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],p.LinearSRGBColorSpace),e.opacity=r[3]}o.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",o.baseColorTexture,p.SRGBColorSpace))}return Promise.all(s)}}class Dc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class Nc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const o=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new p.Vector2(o,o)}return Promise.all(s)}}class kc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class Fc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class Bc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];if(t.sheenColor=new p.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){const o=n.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,p.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class zc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class Uc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;const o=n.attenuationColor||[1,1,1];return t.attenuationColor=new p.Color().setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),Promise.all(s)}}class Hc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}}class Vc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));const o=n.specularColorFactor||[1,1,1];return t.specularColor=new p.Color().setRGB(o[0],o[1],o[2],p.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,p.SRGBColorSpace)),Promise.all(s)}}class Gc{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(s)}}class jc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Re(this.parser,e,this.name)!==null?p.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const n=Re(this.parser,e,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class Wc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const o=s.extensions[this.name],r=t.options.ktx2Loader;if(!r){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,r)}}class Zc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,o=s.textures[e];if(!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=s.images[r.source];let c=n.textureLoader;if(a.uri){const h=n.options.manager.getHandler(a.uri);h!==null&&(c=h)}return n.loadTextureImage(e,r.source,c)}}class Kc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,o=s.textures[e];if(!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=s.images[r.source];let c=n.textureLoader;if(a.uri){const h=n.options.manager.getHandler(a.uri);h!==null&&(c=h)}return n.loadTextureImage(e,r.source,c)}}class Er{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],o=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.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=s.byteOffset||0,h=s.byteLength||0,d=s.count,u=s.byteStride,f=new Uint8Array(a,c,h);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(d,u,f,s.mode,s.filter).then(function(m){return m.buffer}):r.ready.then(function(){const m=new ArrayBuffer(d*u);return r.decodeGltfBuffer(new Uint8Array(m),d,u,f,s.mode,s.filter),m})})}else return null}}class Xc{constructor(e){this.name=le.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const h of s.primitives)if(h.mode!==st.TRIANGLES&&h.mode!==st.TRIANGLE_STRIP&&h.mode!==st.TRIANGLE_FAN&&h.mode!==void 0)return null;const r=n.extensions[this.name].attributes,a=[],c={};for(const h in r)a.push(this.parser.getDependency("accessor",r[h]).then(d=>(c[h]=d,c[h])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(h=>{const d=h.pop(),u=d.isGroup?d.children:[d],f=h[0].count,m=[];for(const E of u){const b=new p.Matrix4,w=new p.Vector3,A=new p.Quaternion,S=new p.Vector3(1,1,1),_=new p.InstancedMesh(E.geometry,E.material,f);for(let x=0;x<f;x++)c.TRANSLATION&&w.fromBufferAttribute(c.TRANSLATION,x),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,x),c.SCALE&&S.fromBufferAttribute(c.SCALE,x),_.setMatrixAt(x,b.compose(w,A,S));for(const x in c)if(x==="_COLOR_0"){const v=c[x];_.instanceColor=new p.InstancedBufferAttribute(v.array,v.itemSize,v.normalized)}else x!=="TRANSLATION"&&x!=="ROTATION"&&x!=="SCALE"&&E.geometry.setAttribute(x,c[x]);p.Object3D.prototype.copy.call(_,E),this.parser.assignFinalMaterial(_),m.push(_)}return d.isGroup?(d.clear(),d.add(...m),d):m[0]}))}}const Zr="glTF",wn=12,Tr={JSON:1313821514,BIN:5130562};class Yc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,wn),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Zr)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-wn,o=new DataView(e,wn);let r=0;for(;r<s;){const a=o.getUint32(r,!0);r+=4;const c=o.getUint32(r,!0);if(r+=4,c===Tr.JSON){const h=new Uint8Array(e,wn+r,a);this.content=n.decode(h)}else if(c===Tr.BIN){const h=wn+r;this.body=e.slice(h,h+a)}r+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class qc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,o=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,a={},c={},h={};for(const d in r){const u=Ti[d]||d.toLowerCase();a[u]=r[d]}for(const d in e.attributes){const u=Ti[d]||d.toLowerCase();if(r[d]!==void 0){const f=n.accessors[e.attributes[d]],m=an[f.componentType];h[u]=m.name,c[u]=f.normalized===!0}}return t.getDependency("bufferView",o).then(function(d){return new Promise(function(u,f){s.decodeDracoFile(d,function(m){for(const E in m.attributes){const b=m.attributes[E],w=c[E];w!==void 0&&(b.normalized=w)}u(m)},a,h,p.LinearSRGBColorSpace,f)})})}}class $c{constructor(){this.name=le.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class Qc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Kr extends p.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,o=e*s*3+s;for(let r=0;r!==s;r++)t[r]=n[o+r];return t}interpolate_(e,t,n,s){const o=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=a*2,h=a*3,d=s-t,u=(n-t)/d,f=u*u,m=f*u,E=e*h,b=E-h,w=-2*m+3*f,A=m-f,S=1-w,_=A-f+u;for(let x=0;x!==a;x++){const v=r[b+x+a],L=r[b+x+c]*d,I=r[E+x+a],C=r[E+x]*d;o[x]=S*v+_*L+w*I+A*C}return o}}const Jc=new p.Quaternion;class el extends Kr{interpolate_(e,t,n,s){const o=super.interpolate_(e,t,n,s);return Jc.fromArray(o).normalize().toArray(o),o}}const st={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},an={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},wr={9728:p.NearestFilter,9729:p.LinearFilter,9984:p.NearestMipmapNearestFilter,9985:p.LinearMipmapNearestFilter,9986:p.NearestMipmapLinearFilter,9987:p.LinearMipmapLinearFilter},Sr={33071:p.ClampToEdgeWrapping,33648:p.MirroredRepeatWrapping,10497:p.RepeatWrapping},Ks={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Ti={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"},Mt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},tl={CUBICSPLINE:void 0,LINEAR:p.InterpolateLinear,STEP:p.InterpolateDiscrete},Xs={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function nl(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new p.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:p.FrontSide})),i.DefaultMaterial}function Ut(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Et(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function sl(i,e,t){let n=!1,s=!1,o=!1;for(let h=0,d=e.length;h<d;h++){const u=e[h];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(s=!0),u.COLOR_0!==void 0&&(o=!0),n&&s&&o)break}if(!n&&!s&&!o)return Promise.resolve(i);const r=[],a=[],c=[];for(let h=0,d=e.length;h<d;h++){const u=e[h];if(n){const f=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):i.attributes.position;r.push(f)}if(s){const f=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):i.attributes.normal;a.push(f)}if(o){const f=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):i.attributes.color;c.push(f)}}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(c)]).then(function(h){const d=h[0],u=h[1],f=h[2];return n&&(i.morphAttributes.position=d),s&&(i.morphAttributes.normal=u),o&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function il(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function rl(i){let e;const t=i.extensions&&i.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Ys(t.attributes):e=i.indices+":"+Ys(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Ys(i.targets[n]);return e}function Ys(i){let e="";const t=Object.keys(i).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+i[t[n]]+";";return e}function wi(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function ol(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const al=new p.Matrix4;class cl{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Ic,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,o=!1,r=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const c=a.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,o=a.indexOf("Firefox")>-1,r=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||o&&r<98?this.textureLoader=new p.TextureLoader(this.options.manager):this.textureLoader=new p.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new p.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(r){const a={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:n,userData:{}};return Ut(o,a,s),Et(a,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(const c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,o=t.length;s<o;s++){const r=t[s].joints;for(let a=0,c=r.length;a<c;a++)e[r[a]].isBone=!0}for(let s=0,o=e.length;s<o;s++){const r=e[s];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),o=(r,a)=>{const c=this.associations.get(r);c!=null&&this.associations.set(a,c);for(const[h,d]of r.children.entries())o(d,a.children[h])};return o(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const o=e(t[s]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":s=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(o,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(o,r){n.load(p.LoaderUtils.resolveURL(t.uri,s.path),o,void 0,function(){r(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const r=Ks[s.type],a=an[s.componentType],c=s.normalized===!0,h=new a(s.count*r);return Promise.resolve(new p.BufferAttribute(h,r,c))}const o=[];return s.bufferView!==void 0?o.push(this.getDependency("bufferView",s.bufferView)):o.push(null),s.sparse!==void 0&&(o.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(o).then(function(r){const a=r[0],c=Ks[s.type],h=an[s.componentType],d=h.BYTES_PER_ELEMENT,u=d*c,f=s.byteOffset||0,m=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,E=s.normalized===!0;let b,w;if(m&&m!==u){const A=Math.floor(f/m),S="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let _=t.cache.get(S);_||(b=new h(a,A*m,s.count*m/d),_=new p.InterleavedBuffer(b,m/d),t.cache.add(S,_)),w=new p.InterleavedBufferAttribute(_,c,f%m/d,E)}else a===null?b=new h(s.count*c):b=new h(a,f,s.count*c),w=new p.BufferAttribute(b,c,E);if(s.sparse!==void 0){const A=Ks.SCALAR,S=an[s.sparse.indices.componentType],_=s.sparse.indices.byteOffset||0,x=s.sparse.values.byteOffset||0,v=new S(r[1],_,s.sparse.count*A),L=new h(r[2],x,s.sparse.count*c);a!==null&&(w=new p.BufferAttribute(w.array.slice(),w.itemSize,w.normalized)),w.normalized=!1;for(let I=0,C=v.length;I<C;I++){const D=v[I];if(w.setX(D,L[I*c]),c>=2&&w.setY(D,L[I*c+1]),c>=3&&w.setZ(D,L[I*c+2]),c>=4&&w.setW(D,L[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}w.normalized=E}return w})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,r=t.images[o];let a=this.textureLoader;if(r.uri){const c=n.manager.getHandler(r.uri);c!==null&&(a=c)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,n){const s=this,o=this.json,r=o.textures[e],a=o.images[t],c=(a.uri||a.bufferView)+":"+r.sampler;if(this.textureCache[c])return this.textureCache[c];const h=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=r.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const f=(o.samplers||{})[r.sampler]||{};return d.magFilter=wr[f.magFilter]||p.LinearFilter,d.minFilter=wr[f.minFilter]||p.LinearMipmapLinearFilter,d.wrapS=Sr[f.wrapS]||p.RepeatWrapping,d.wrapT=Sr[f.wrapT]||p.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==p.NearestFilter&&d.minFilter!==p.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[c]=h,h}loadImageSource(e,t){const n=this,s=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const r=s.images[e],a=self.URL||self.webkitURL;let c=r.uri||"",h=!1;if(r.bufferView!==void 0)c=n.getDependency("bufferView",r.bufferView).then(function(u){h=!0;const f=new Blob([u],{type:r.mimeType});return c=a.createObjectURL(f),c});else if(r.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(f,m){let E=f;t.isImageBitmapLoader===!0&&(E=function(b){const w=new p.Texture(b);w.needsUpdate=!0,f(w)}),t.load(p.LoaderUtils.resolveURL(u,o.path),E,void 0,m)})}).then(function(u){return h===!0&&a.revokeObjectURL(c),Et(u,r),u.userData.mimeType=r.mimeType||ol(r.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,s){const o=this;return this.getDependency("texture",n.index).then(function(r){if(!r)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(r=r.clone(),r.channel=n.texCoord),o.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const c=o.associations.get(r);r=o.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(r,a),o.associations.set(r,c)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.PointsMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let c=this.cache.get(a);c||(c=new p.LineBasicMaterial,p.Material.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(s||o||r){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),r&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),o&&(c.vertexColors=!0),r&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return p.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,o=n.materials[e];let r;const a={},c=o.extensions||{},h=[];if(c[le.KHR_MATERIALS_UNLIT]){const u=s[le.KHR_MATERIALS_UNLIT];r=u.getMaterialType(),h.push(u.extendParams(a,o,t))}else{const u=o.pbrMetallicRoughness||{};if(a.color=new p.Color(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const f=u.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],p.LinearSRGBColorSpace),a.opacity=f[3]}u.baseColorTexture!==void 0&&h.push(t.assignTexture(a,"map",u.baseColorTexture,p.SRGBColorSpace)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(h.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),h.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),r=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),h.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=p.DoubleSide);const d=o.alphaMode||Xs.OPAQUE;if(d===Xs.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Xs.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&r!==p.MeshBasicMaterial&&(h.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new p.Vector2(1,1),o.normalTexture.scale!==void 0)){const u=o.normalTexture.scale;a.normalScale.set(u,u)}if(o.occlusionTexture!==void 0&&r!==p.MeshBasicMaterial&&(h.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&r!==p.MeshBasicMaterial){const u=o.emissiveFactor;a.emissive=new p.Color().setRGB(u[0],u[1],u[2],p.LinearSRGBColorSpace)}return o.emissiveTexture!==void 0&&r!==p.MeshBasicMaterial&&h.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,p.SRGBColorSpace)),Promise.all(h).then(function(){const u=new r(a);return o.name&&(u.name=o.name),Et(u,o),t.associations.set(u,{materials:e}),o.extensions&&Ut(s,u,o),u})}createUniqueName(e){const t=p.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function o(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return _r(c,a,t)})}const r=[];for(let a=0,c=e.length;a<c;a++){const h=e[a],d=rl(h),u=s[d];if(u)r.push(u.promise);else{let f;h.extensions&&h.extensions[le.KHR_DRACO_MESH_COMPRESSION]?f=o(h):f=_r(new p.BufferGeometry,h,t),s[d]={primitive:h,promise:f},r.push(f)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,s=this.extensions,o=n.meshes[e],r=o.primitives,a=[];for(let c=0,h=r.length;c<h;c++){const d=r[c].material===void 0?nl(this.cache):this.getDependency("material",r[c].material);a.push(d)}return a.push(t.loadGeometries(r)),Promise.all(a).then(function(c){const h=c.slice(0,c.length-1),d=c[c.length-1],u=[];for(let m=0,E=d.length;m<E;m++){const b=d[m],w=r[m];let A;const S=h[m];if(w.mode===st.TRIANGLES||w.mode===st.TRIANGLE_STRIP||w.mode===st.TRIANGLE_FAN||w.mode===void 0)A=o.isSkinnedMesh===!0?new p.SkinnedMesh(b,S):new p.Mesh(b,S),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),w.mode===st.TRIANGLE_STRIP?A.geometry=yr(A.geometry,p.TriangleStripDrawMode):w.mode===st.TRIANGLE_FAN&&(A.geometry=yr(A.geometry,p.TriangleFanDrawMode));else if(w.mode===st.LINES)A=new p.LineSegments(b,S);else if(w.mode===st.LINE_STRIP)A=new p.Line(b,S);else if(w.mode===st.LINE_LOOP)A=new p.LineLoop(b,S);else if(w.mode===st.POINTS)A=new p.Points(b,S);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+w.mode);Object.keys(A.geometry.morphAttributes).length>0&&il(A,o),A.name=t.createUniqueName(o.name||"mesh_"+e),Et(A,o),w.extensions&&Ut(s,A,w),t.assignFinalMaterial(A),u.push(A)}for(let m=0,E=u.length;m<E;m++)t.associations.set(u[m],{meshes:e,primitives:m});if(u.length===1)return o.extensions&&Ut(s,u[0],o),u[0];const f=new p.Group;o.extensions&&Ut(s,f,o),t.associations.set(f,{meshes:e});for(let m=0,E=u.length;m<E;m++)f.add(u[m]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new p.PerspectiveCamera(p.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new p.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Et(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,o=t.joints.length;s<o;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const o=s.pop(),r=s,a=[],c=[];for(let h=0,d=r.length;h<d;h++){const u=r[h];if(u){a.push(u);const f=new p.Matrix4;o!==null&&f.fromArray(o.array,h*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[h])}return new p.Skeleton(a,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],o=s.name?s.name:"animation_"+e,r=[],a=[],c=[],h=[],d=[];for(let u=0,f=s.channels.length;u<f;u++){const m=s.channels[u],E=s.samplers[m.sampler],b=m.target,w=b.node,A=s.parameters!==void 0?s.parameters[E.input]:E.input,S=s.parameters!==void 0?s.parameters[E.output]:E.output;b.node!==void 0&&(r.push(this.getDependency("node",w)),a.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",S)),h.push(E),d.push(b))}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(c),Promise.all(h),Promise.all(d)]).then(function(u){const f=u[0],m=u[1],E=u[2],b=u[3],w=u[4],A=[];for(let _=0,x=f.length;_<x;_++){const v=f[_],L=m[_],I=E[_],C=b[_],D=w[_];if(v===void 0)continue;v.updateMatrix&&v.updateMatrix();const P=n._createAnimationTracks(v,L,I,C,D);if(P)for(let F=0;F<P.length;F++)A.push(P[F])}const S=new p.AnimationClip(o,void 0,A);return Et(S,s),S})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(o){const r=n._getNodeRef(n.meshCache,s.mesh,o);return s.weights!==void 0&&r.traverse(function(a){if(a.isMesh)for(let c=0,h=s.weights.length;c<h;c++)a.morphTargetInfluences[c]=s.weights[c]}),r})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],o=n._loadNodeShallow(e),r=[],a=s.children||[];for(let h=0,d=a.length;h<d;h++)r.push(n.getDependency("node",a[h]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([o,Promise.all(r),c]).then(function(h){const d=h[0],u=h[1],f=h[2];f!==null&&d.traverse(function(m){m.isSkinnedMesh&&m.bind(f,al)});for(let m=0,E=u.length;m<E;m++)d.add(u[m]);if(d.userData.pivot!==void 0&&u.length>0){const m=d.userData.pivot,E=u[0];d.pivot=new p.Vector3().fromArray(m),d.position.x-=m[0],d.position.y-=m[1],d.position.z-=m[2],E.position.set(0,0,0),delete d.userData.pivot}return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],r=o.name?s.createUniqueName(o.name):"",a=[],c=s._invokeOne(function(h){return h.createNodeMesh&&h.createNodeMesh(e)});return c&&a.push(c),o.camera!==void 0&&a.push(s.getDependency("camera",o.camera).then(function(h){return s._getNodeRef(s.cameraCache,o.camera,h)})),s._invokeAll(function(h){return h.createNodeAttachment&&h.createNodeAttachment(e)}).forEach(function(h){a.push(h)}),this.nodeCache[e]=Promise.all(a).then(function(h){let d;if(o.isBone===!0?d=new p.Bone:h.length>1?d=new p.Group:h.length===1?d=h[0]:d=new p.Object3D,d!==h[0])for(let u=0,f=h.length;u<f;u++)d.add(h[u]);if(o.name&&(d.userData.name=o.name,d.name=r),Et(d,o),o.extensions&&Ut(n,d,o),o.matrix!==void 0){const u=new p.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(!s.associations.has(d))s.associations.set(d,{});else if(o.mesh!==void 0&&s.meshCache.refs[o.mesh]>1){const u=s.associations.get(d);s.associations.set(d,{...u})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,o=new p.Group;n.name&&(o.name=s.createUniqueName(n.name)),Et(o,n),n.extensions&&Ut(t,o,n);const r=n.nodes||[],a=[];for(let c=0,h=r.length;c<h;c++)a.push(s.getDependency("node",r[c]));return Promise.all(a).then(function(c){for(let d=0,u=c.length;d<u;d++){const f=c[d];f.parent!==null?o.add(Cc(f)):o.add(f)}const h=d=>{const u=new Map;for(const[f,m]of s.associations)(f instanceof p.Material||f instanceof p.Texture)&&u.set(f,m);return d.traverse(f=>{const m=s.associations.get(f);m!=null&&u.set(f,m)}),u};return s.associations=h(o),o})}_createAnimationTracks(e,t,n,s,o){const r=[],a=e.name?e.name:e.uuid,c=[];function h(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}Mt[o.path]===Mt.weights?(h(e),e.isGroup&&e.children.forEach(h)):c.push(a);let d;switch(Mt[o.path]){case Mt.weights:d=p.NumberKeyframeTrack;break;case Mt.rotation:d=p.QuaternionKeyframeTrack;break;case Mt.translation:case Mt.scale:d=p.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:d=p.NumberKeyframeTrack;break;case 2:case 3:default:d=p.VectorKeyframeTrack;break}break}const u=s.interpolation!==void 0?tl[s.interpolation]:p.InterpolateLinear,f=this._getArrayFromAccessor(n);for(let m=0,E=c.length;m<E;m++){const b=new d(c[m]+"."+Mt[o.path],t.array,f,u);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),r.push(b)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=wi(t.constructor),s=new Float32Array(t.length);for(let o=0,r=t.length;o<r;o++)s[o]=t[o]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof p.QuaternionKeyframeTrack?el:Kr;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function ll(i,e,t){const n=e.attributes,s=new p.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],c=a.min,h=a.max;if(c!==void 0&&h!==void 0){if(s.set(new p.Vector3(c[0],c[1],c[2]),new p.Vector3(h[0],h[1],h[2])),a.normalized){const d=wi(an[a.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const a=new p.Vector3,c=new p.Vector3;for(let h=0,d=o.length;h<d;h++){const u=o[h];if(u.POSITION!==void 0){const f=t.json.accessors[u.POSITION],m=f.min,E=f.max;if(m!==void 0&&E!==void 0){if(c.setX(Math.max(Math.abs(m[0]),Math.abs(E[0]))),c.setY(Math.max(Math.abs(m[1]),Math.abs(E[1]))),c.setZ(Math.max(Math.abs(m[2]),Math.abs(E[2]))),f.normalized){const b=wi(an[f.componentType]);c.multiplyScalar(b)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}i.boundingBox=s;const r=new p.Sphere;s.getCenter(r.center),r.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=r}function _r(i,e,t){const n=e.attributes,s=[];function o(r,a){return t.getDependency("accessor",r).then(function(c){i.setAttribute(a,c)})}for(const r in n){const a=Ti[r]||r.toLowerCase();a in i.attributes||s.push(o(n[r],a))}if(e.indices!==void 0&&!i.index){const r=t.getDependency("accessor",e.indices).then(function(a){i.setIndex(a)});s.push(r)}return p.ColorManagement.workingColorSpace!==p.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${p.ColorManagement.workingColorSpace}" not supported.`),Et(i,e),ll(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?sl(i,e.targets,t):i})}const hl=y.REVISION.replace(/\D/g,""),Xr=`https://cdn.jsdelivr.net/npm/three@0.${hl}/examples/jsm/libs`,ul=`${Xr}/draco/`,dl=`${Xr}/basis/`;class fl{constructor(e={}){this.loadingManager=new y.LoadingManager,this.loader=new Pc(this.loadingManager),this.config=e}ensureDecoders(){return this.decodersReady||(this.decodersReady=this.configureDecoders()),this.decodersReady}async configureDecoders(){const e=this.config,t=[];(e.draco??!0)&&t.push(this.configureDraco(e)),(e.ktx2??!0)&&t.push(this.configureKtx2(e)),(e.meshopt??!0)&&t.push(this.configureMeshopt());const n=await Promise.allSettled(t);for(const s of n)s.status==="rejected"&&console.warn("softbox: a compression decoder failed to initialize; compressed assets using it may not load.",s.reason)}async configureDraco(e){const{DRACOLoader:t}=await import("three/examples/jsm/loaders/DRACOLoader.js"),n=new t(this.loadingManager);n.setDecoderPath(e.dracoDecoderPath??ul),this.dracoLoader=n,this.loader.setDRACOLoader(n)}async configureKtx2(e){const{KTX2Loader:t}=await import("three/examples/jsm/loaders/KTX2Loader.js"),n=new t(this.loadingManager);n.setTranscoderPath(e.ktx2TranscoderPath??dl),e.renderer&&n.detectSupport(e.renderer),this.ktx2Loader=n,this.loader.setKTX2Loader(n)}async configureMeshopt(){const e=await import("three/examples/jsm/libs/meshopt_decoder.module.js");this.loader.setMeshoptDecoder(e.MeshoptDecoder)}async load(e,t){try{return await this.ensureDecoders(),new Promise(n=>{this.loader.load(e,s=>{var r;(this.config.bvh??!0)&&jr(s.scene),s.scene.animations=s.animations;const o={scene:new Ke(s.scene),animations:this.convertAnimations(s.animations),cameras:(r=s.cameras)==null?void 0:r.map(a=>{const c=a instanceof y.PerspectiveCamera,h=a instanceof y.OrthographicCamera;return{name:a.name,type:a.type,fov:c?a.fov:void 0,aspect:c?a.aspect:void 0,near:c||h?a.near:.1,far:c||h?a.far:1e3}}),userData:s.userData};n(N.ok(o))},s=>{s.total>0&&(t==null||t(s.loaded,s.total))},s=>{n(N.err(new Z("Failed to load GLTF model",K.MODEL_LOAD_FAILED,{url:e,originalError:s})))})})}catch(n){return N.err(new Z("Failed to initiate model loading",K.MODEL_LOAD_FAILED,{url:e,originalError:n}))}}supports(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return t==="gltf"||t==="glb"}dispose(){var e,t;(e=this.dracoLoader)==null||e.dispose(),(t=this.ktx2Loader)==null||t.dispose()}convertAnimations(e){return e.map(t=>({name:t.name,duration:t.duration,tracks:t.tracks.map(n=>({name:n.name,type:this.getTrackType(n),times:n.times,values:n.values}))}))}getTrackType(e){return e instanceof y.VectorKeyframeTrack?"vector":e instanceof y.QuaternionKeyframeTrack?"quaternion":e instanceof y.NumberKeyframeTrack?"number":e instanceof y.BooleanKeyframeTrack?"boolean":"number"}}class br{static createLoader(e,t={}){var s;const n=(s=e.split(".").pop())==null?void 0:s.toLowerCase();switch(n){case"gltf":case"glb":return new fl(t);default:throw new Z(`Unsupported file format: ${n}`,K.UNSUPPORTED_FORMAT,{url:e,extension:n})}}}const xr={type:"change"},Pi={type:"start"},Yr={type:"end"},as=new p.Ray,Ar=new p.Plane,pl=Math.cos(70*p.MathUtils.DEG2RAD),Le=new p.Vector3,$e=2*Math.PI,we={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},qs=1e-6;class qr extends p.Controls{constructor(e,t=null){super(e,t),this.state=we.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=gl.bind(this),this._onPointerDown=ml.bind(this),this._onPointerUp=yl.bind(this),this._onContextMenu=xl.bind(this),this._onMouseWheel=wl.bind(this),this._onKeyDown=Sl.bind(this),this._onTouchStart=_l.bind(this),this._onTouchMove=bl.bind(this),this._onMouseDown=El.bind(this),this._onMouseMove=Tl.bind(this),this._interceptControlDown=Al.bind(this),this._interceptControlUp=vl.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(xr),this.update(),this.state=we.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Le.copy(t).sub(this.target),Le.applyQuaternion(this._quat),this._spherical.setFromVector3(Le),this.autoRotate&&this.state===we.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=$e:n>Math.PI&&(n-=$e),s<-Math.PI?s+=$e:s>Math.PI&&(s-=$e),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=r!=this._spherical.radius}if(Le.setFromSpherical(this._spherical),Le.applyQuaternion(this._quatInverse),t.copy(this.target).add(Le),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const a=Le.length();r=this._clampDistance(a*this._scale);const c=a-r;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=c!==this.object.zoom;const h=new p.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),r=Le.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(as.origin.copy(this.object.position),as.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(as.direction))<pl?this.object.lookAt(this.target):(Ar.setFromNormalAndCoplanarPoint(this.object.up,this.target),as.intersectPlane(Ar,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>qs||8*(1-this._lastQuaternion.dot(this.object.quaternion))>qs||this._lastTargetPosition.distanceToSquared(this.target)>qs?(this.dispatchEvent(xr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?$e/60*this.autoRotateSpeed*e:$e/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Le.setFromMatrixColumn(t,0),Le.multiplyScalar(-e),this._panOffset.add(Le)}_panUp(e,t){this.screenSpacePanning===!0?Le.setFromMatrixColumn(t,1):(Le.setFromMatrixColumn(t,0),Le.crossVectors(this.object.up,Le)),Le.multiplyScalar(e),this._panOffset.add(Le)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Le.copy(s).sub(this.target);let o=Le.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(),s=e-n.left,o=t-n.top,r=n.width,a=n.height;this._mouse.x=s/r*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($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$e*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,o=Math.sqrt(n*n+s*s);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),s=.5*(e.pageX+n.x),o=.5*(e.pageY+n.y);this._rotateEnd.set(s,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($e*this._rotateDelta.x/t.clientHeight),this._rotateUp($e*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,o=Math.sqrt(n*n+s*s);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 r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function ml(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function gl(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function yl(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Yr),this.state=we.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 El(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=we.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=we.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=we.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=we.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=we.PAN}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(Pi)}function Tl(i){switch(this.state){case we.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case we.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case we.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function wl(i){this.enabled===!1||this.enableZoom===!1||this.state!==we.NONE||(i.preventDefault(),this.dispatchEvent(Pi),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(Yr))}function Sl(i){this.enabled!==!1&&this._handleKeyDown(i)}function _l(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=we.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=we.TOUCH_PAN;break;default:this.state=we.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=we.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=we.TOUCH_DOLLY_ROTATE;break;default:this.state=we.NONE}break;default:this.state=we.NONE}this.state!==we.NONE&&this.dispatchEvent(Pi)}function bl(i){switch(this._trackPointer(i),this.state){case we.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case we.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case we.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case we.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=we.NONE}}function xl(i){this.enabled!==!1&&i.preventDefault()}function Al(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function vl(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const $s=new p.Plane,cs=new p.Raycaster,en=new p.Vector2,Qs=new p.Vector3;class Rl extends qr{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE},this._panWorldStart=new p.Vector3}_handleMouseDownPan(e){if(super._handleMouseDownPan(e),this._panOffset.set(0,0,0),this.screenSpacePanning===!0)return;$s.setFromNormalAndCoplanarPoint(this.object.up,this.target);const n=this.domElement.getBoundingClientRect();en.x=(e.clientX-n.left)/n.width*2-1,en.y=-((e.clientY-n.top)/n.height)*2+1,cs.setFromCamera(en,this.object),cs.ray.intersectPlane($s,this._panWorldStart)}_handleMouseMovePan(e){if(this.screenSpacePanning===!0){super._handleMouseMovePan(e);return}const n=this.domElement.getBoundingClientRect();en.x=(e.clientX-n.left)/n.width*2-1,en.y=-((e.clientY-n.top)/n.height)*2+1,cs.setFromCamera(en,this.object),cs.ray.intersectPlane($s,Qs)&&(Qs.sub(this._panWorldStart),this._panOffset.copy(Qs).negate(),this.update())}}class $r{constructor(e){this.controls=e,this.targetAdapter=Dt.fromThreeVector(e.target)}get enabled(){return this.controls.enabled}set enabled(e){this.controls.enabled=e}get enableDamping(){return this.controls.enableDamping}set enableDamping(e){this.controls.enableDamping=e}get dampingFactor(){return this.controls.dampingFactor}set dampingFactor(e){this.controls.dampingFactor=e}get enableZoom(){return this.controls.enableZoom}set enableZoom(e){this.controls.enableZoom=e}get enableRotate(){return this.controls.enableRotate}set enableRotate(e){this.controls.enableRotate=e}get enablePan(){return this.controls.enablePan}set enablePan(e){this.controls.enablePan=e}get zoomSpeed(){return this.controls.zoomSpeed}set zoomSpeed(e){this.controls.zoomSpeed=e}get minDistance(){return this.controls.minDistance}set minDistance(e){this.controls.minDistance=e}get maxDistance(){return this.controls.maxDistance}set maxDistance(e){this.controls.maxDistance=e}get rotateSpeed(){return this.controls.rotateSpeed}set rotateSpeed(e){this.controls.rotateSpeed=e}get minPolarAngle(){return this.controls.minPolarAngle}set minPolarAngle(e){this.controls.minPolarAngle=e}get maxPolarAngle(){return this.controls.maxPolarAngle}set maxPolarAngle(e){this.controls.maxPolarAngle=e}get minAzimuthAngle(){return this.controls.minAzimuthAngle}set minAzimuthAngle(e){this.controls.minAzimuthAngle=e}get maxAzimuthAngle(){return this.controls.maxAzimuthAngle}set maxAzimuthAngle(e){this.controls.maxAzimuthAngle=e}get panSpeed(){return this.controls.panSpeed}set panSpeed(e){this.controls.panSpeed=e}get screenSpacePanning(){return this.controls.screenSpacePanning}set screenSpacePanning(e){this.controls.screenSpacePanning=e}get target(){return this.targetAdapter}update(){return this.controls.update()}onChange(e){return this.controls.addEventListener("change",e),()=>this.controls.removeEventListener("change",e)}reset(){this.controls.reset()}dispose(){this.controls.dispose()}connect(e){}disconnect(){this.controls.dispose()}get autoRotate(){return this.controls.autoRotate}set autoRotate(e){this.controls.autoRotate=e}get autoRotateSpeed(){return this.controls.autoRotateSpeed}set autoRotateSpeed(e){this.controls.autoRotateSpeed=e}getThreeControls(){return this.controls}}class Ml extends $r{constructor(e,t){super(new qr(e,t))}get type(){return"orbit"}}class Cl extends $r{constructor(e,t){const n=new Rl(e,t);super(n),n.screenSpacePanning=!0}get type(){return"map"}get screenSpacePanning(){return!0}set screenSpacePanning(e){}}const Ii="contact-shadow-baked",Ht="contact-shadow-live",Cs="softboxContactShadowHelper",Ps="softboxPathTracingFloor",vr=Math.PI*(3-Math.sqrt(5));function Qr(i){const e=i.getObjectByName(Ii);e&&(i.remove(e),Ms(e))}function Jr(i){Qr(i);const e=i.getObjectByName(Ht);e&&(e.visible=!0)}const pe=class pe{constructor(e){this.explicitPasses=e==null?void 0:e.passes}bake(e){const{renderer:t,scene:n,object:s,light:o}=e;if(t.getContext().isContextLost()){this.leaveLiveCatcherInCharge(n);return}const r=this.measureBakeRegion(s);if(!r)return;const a=n.getObjectByName(Ht);(a==null?void 0:a.geometry)instanceof y.CircleGeometry&&(r.halfExtent=Math.min(r.halfExtent,a.geometry.parameters.radius));const c=new y.WebGLRenderTarget(pe.ACCUMULATION_TEXTURE_SIZE,pe.ACCUMULATION_TEXTURE_SIZE,{type:t.capabilities.isWebGL2?y.HalfFloatType:y.UnsignedByteType,depthBuffer:!1,stencilBuffer:!1}),h=new y.CircleGeometry(r.halfExtent,64);if(this.accumulateShadowPasses(t,s,o,r,c,h),t.getContext().isContextLost()){c.dispose(),h.dispose(),this.leaveLiveCatcherInCharge(n),console.warn("Contact-shadow bake aborted: WebGL context was lost mid-bake");return}this.installBakedMesh(n,r,c,h)}leaveLiveCatcherInCharge(e){Jr(e)}evictBakedMesh(e){Qr(e)}measureBakeRegion(e){const t=new y.Box3().setFromObject(e);if(t.isEmpty()||!Number.isFinite(t.min.x)||!Number.isFinite(t.max.x))return null;const n=t.getSize(new y.Vector3),s=t.getCenter(new y.Vector3),o=Math.max(n.x,n.z),r=Math.max(o*pe.DISC_FOOTPRINT_MARGIN+n.y*pe.DISC_HEIGHT_STRETCH,pe.DISC_MIN_HALF_EXTENT);return{center:s,halfExtent:r,objectHeight:n.y,boundingRadius:n.length()/2}}accumulateShadowPasses(e,t,n,s,o,r){const a=new y.Scene,c=t.parent;a.add(t);const h=this.disableColorWrite(t),d=this.createBakeLight(n);a.add(d),a.add(d.target),d.target.position.copy(n.target.parent?n.target.getWorldPosition(new y.Vector3):n.target.position);const u=new y.ShadowMaterial({transparent:!0,opacity:0,depthWrite:!1});u.blending=y.CustomBlending,u.blendEquation=y.AddEquation,u.blendSrc=y.OneFactor,u.blendDst=y.OneFactor;const f=new y.Mesh(r,u);f.rotation.x=-Math.PI/2,f.position.set(s.center.x,0,s.center.z),f.receiveShadow=!0,a.add(f);const m=this.createBakeCamera(s);a.add(m);const E=e.getRenderTarget(),b=e.autoClear,w=e.getClearColor(new y.Color),A=e.getClearAlpha(),S=e.shadowMap.autoUpdate;try{e.shadowMap.autoUpdate=!0,e.setRenderTarget(o),e.setClearColor(0,0),e.clear(!0,!1,!1),e.autoClear=!1;const _=this.explicitPasses??this.measureAffordablePasses(e,a,m,n,d,o);u.opacity=1/_;for(const x of this.sampleLightPositions(n,_))d.position.copy(x),this.fitBakeDepthRange(d,s),e.render(a,m)}finally{e.autoClear=b,e.setClearColor(w,A),e.setRenderTarget(E),e.shadowMap.autoUpdate=S,this.restoreColorWrite(h),c?c.add(t):a.remove(t),d.dispose(),u.dispose()}}measureAffordablePasses(e,t,n,s,o,r){o.position.copy(s.position),e.render(t,n),this.awaitGpuIdle(e,r);const a=performance.now();e.render(t,n),this.awaitGpuIdle(e,r);const c=Math.max(performance.now()-a,.01);return y.MathUtils.clamp(Math.round(pe.BAKE_BUDGET_MS/c),pe.MIN_PASSES,pe.MAX_PASSES)}awaitGpuIdle(e,t){if(!e.capabilities.textureTypeReadable(t.texture.type))return;const n=t.texture.type===y.HalfFloatType?new Uint16Array(4):new Uint8Array(4);e.readRenderTargetPixels(t,0,0,1,1,n)}createBakeLight(e){const t=new y.DirectionalLight(16777215,1);t.castShadow=!0,t.shadow.mapSize.set(pe.BAKE_SHADOW_MAP_SIZE,pe.BAKE_SHADOW_MAP_SIZE),t.shadow.bias=0,t.shadow.normalBias=0,t.shadow.radius=6;const n=e.shadow.camera,s=t.shadow.camera;return s.left=n.left,s.right=n.right,s.top=n.top,s.bottom=n.bottom,s.updateProjectionMatrix(),t}fitBakeDepthRange(e,t){const n=e.target.position.clone().sub(e.position).normalize(),o=t.center.clone().sub(e.position).dot(n),r=t.boundingRadius*1.5+t.halfExtent,a=e.shadow.camera;a.near=Math.max(o-r,o*.01),a.far=o+r,a.updateProjectionMatrix()}createBakeCamera(e){const t=new y.OrthographicCamera(-e.halfExtent,e.halfExtent,e.halfExtent,-e.halfExtent,.1,Math.max(e.objectHeight,1)*4);return t.position.set(e.center.x,Math.max(e.objectHeight,1)*2,e.center.z),t.up.set(0,0,-1),t.lookAt(e.center.x,0,e.center.z),t.updateProjectionMatrix(),t.updateMatrixWorld(!0),t}sampleLightPositions(e,t){const n=e.position.clone(),s=e.target.parent?e.target.getWorldPosition(new y.Vector3):e.target.position.clone(),o=s.clone().sub(n),r=o.length(),a=o.normalize(),c=new y.Vector3().crossVectors(a,new y.Vector3(0,1,0));c.lengthSq()<1e-6&&c.set(1,0,0),c.normalize();const h=new y.Vector3().crossVectors(a,c),d=Math.round(t*pe.AMBIENT_RATIO),u=t-d,f=y.MathUtils.degToRad(pe.LIGHT_APERTURE_DEGREES),m=Math.tan(f/2)*r,E=[];for(let A=0;A<u;A++){const S=m*Math.sqrt((A+.5)/u),_=A*vr;E.push(n.clone().addScaledVector(c,S*Math.cos(_)).addScaledVector(h,S*Math.sin(_)))}const b=Math.sin(y.MathUtils.degToRad(pe.AMBIENT_MIN_ELEVATION_DEGREES)),w=.98;for(let A=0;A<d;A++){const S=Math.sqrt((A+.5)/d),_=b+(w-b)*S,x=Math.sqrt(1-_*_),v=A*vr;E.push(new y.Vector3(x*Math.cos(v),_,x*Math.sin(v)).multiplyScalar(r).add(s))}return E}installBakedMesh(e,t,n,s){this.evictBakedMesh(e);const o=new y.MeshBasicMaterial({map:n.texture,transparent:!0,opacity:pe.SHADOW_STRENGTH,depthWrite:!1,toneMapped:!1});o.onBeforeCompile=h=>{h.fragmentShader=h.fragmentShader.replace("#include <map_fragment>",`#include <map_fragment>
|
|
20
|
-
diffuseColor.a = pow(diffuseColor.a, 0.75);`)},o.customProgramCacheKey=()=>"contact-shadow-alpha-gamma",o.addEventListener("dispose",()=>n.dispose());const r=new y.Mesh(s,o);r.name=Ii,r.userData[Cs]=!0,r.rotation.x=-Math.PI/2;const a=y.MathUtils.clamp(t.objectHeight*pe.FLOOR_LIFT_PER_HEIGHT,pe.FLOOR_LIFT_MIN,pe.FLOOR_LIFT_MAX);r.position.set(t.center.x,a,t.center.z),r.userData.renderTarget=n,e.add(r);const c=e.getObjectByName(Ht);c&&(c.visible=!1)}disableColorWrite(e){const t=new Map;return e.traverse(n=>{const s=n;if(!s.isMesh)return;const o=Array.isArray(s.material)?s.material:[s.material];for(const r of o)r&&!t.has(r)&&(t.set(r,r.colorWrite),r.colorWrite=!1)}),t}restoreColorWrite(e){e.forEach((t,n)=>{n.colorWrite=t})}};pe.AMBIENT_RATIO=.62,pe.LIGHT_APERTURE_DEGREES=13,pe.AMBIENT_MIN_ELEVATION_DEGREES=55,pe.ACCUMULATION_TEXTURE_SIZE=1024,pe.BAKE_SHADOW_MAP_SIZE=1024,pe.SHADOW_STRENGTH=.55,pe.DISC_FOOTPRINT_MARGIN=1.4,pe.DISC_HEIGHT_STRETCH=.45,pe.DISC_MIN_HALF_EXTENT=.05,pe.FLOOR_LIFT_PER_HEIGHT=.0025,pe.FLOOR_LIFT_MIN=2e-4,pe.FLOOR_LIFT_MAX=.01,pe.BAKE_BUDGET_MS=100,pe.MIN_PASSES=24,pe.MAX_PASSES=96;let Si=pe;const cn=(i,e)=>{if(i&&typeof i=="object"){const t=i[e];if(typeof t=="function")return t.call(i)}return null};function wt(i){return cn(i,"getThreeObject")??(i instanceof y.Object3D?i:null)}function Pn(i){return cn(i,"getThreeCamera")??(i instanceof y.Camera?i:null)}function ot(i){return cn(i,"getThreeScene")??(i instanceof y.Scene?i:null)}function Pl(i){return cn(i,"getThreeTexture")??(i instanceof y.Texture?i:null)}function eo(i){return cn(i,"getThreeRenderer")??(i instanceof y.WebGLRenderer?i:null)}function Li(i){return cn(i,"getThreeControls")}var Tt=(i=>(i.SHADOW_FLOOR="shadow_floor",i.SQUARE_WIRE="square_wire",i.HEXAGONAL_WIRE="hexagonal_wire",i.HEXAGONAL_GLASS="hexagonal_glass",i.STONE_TILES="stone_tiles",i.CUSTOM="custom",i))(Tt||{});class Il{constructor(){this.name="Square Wire Grid"}createGrid(e){const t=e.size||10,n=e.divisions||10,s=new y.Color(e.color||8947848),o=new y.Color(e.centerLineColor||e.color||4473924),r=new y.GridHelper(t,n,o,s);if(e.opacity!==void 0&&e.opacity<1){const a=r.material;a.transparent=!0,a.opacity=e.opacity}return r}dispose(){}}class Ll{constructor(){this.name="Hexagonal Wire Grid"}createGrid(e){var d;const t=new y.Group,n=((d=e.styleOptions)==null?void 0:d.hexRadius)??Math.floor(e.divisions/2),s=e.size/Math.max(1,n*2),o=new y.Color(e.color||8947848),r=e.opacity||.4,a=new y.LineBasicMaterial({color:o,transparent:!0,opacity:r}),c=s*Math.sqrt(3),h=s*2;for(let u=-n;u<=n;u++){const f=Math.max(-n,-u-n),m=Math.min(n,-u+n);for(let E=f;E<=m;E++){const b=c*(u+E/2),w=h*.75*E,A=[],S=Math.PI*2/6;for(let v=0;v<=6;v++){const L=v*S+Math.PI/6,I=b+s*Math.cos(L),C=w+s*Math.sin(L);A.push(new y.Vector3(I,0,C))}const _=new y.BufferGeometry().setFromPoints(A),x=new y.Line(_,a);t.add(x)}}return t}dispose(){}}const vn=class vn{static getHeight(e){return e*this.HEIGHT_RATIO}static getBevelSize(e){return e*this.BEVEL_RATIO}static getBevelThickness(e){return this.getBevelSize(e)}static getBaseSize(e){return e+this.getBevelSize(e)+this.getBevelThickness(e)}static getGapFactor(){return this.GAP_FACTOR}static getGridSpacing(e){const t=this.getBaseSize(e),n=this.getGapFactor();return{width:Math.sqrt(3)*t*n,height:2*t*n}}static getYPosition(e){return-this.getBevelSize(e)}};vn.HEIGHT_RATIO=.075,vn.BEVEL_RATIO=.04,vn.GAP_FACTOR=1.05;let Vt=vn;class Ol{constructor(e,t,n,s={}){this.position=e,this.size=t,this.color=n,this.materialOptions=s,this.height=Vt.getHeight(this.size),this.bevel=Vt.getBevelSize(this.size)}createGeometry(){const e=new y.Shape,t=this.size+this.bevel,n=Math.PI*2/6;for(let r=0;r<6;r++){const a=t*Math.cos(r*n),c=t*Math.sin(r*n);r===0?e.moveTo(a,c):e.lineTo(a,c)}e.closePath();const s={depth:this.height,bevelEnabled:!0,bevelSize:this.bevel,bevelThickness:this.bevel,bevelSegments:2},o=new y.ExtrudeGeometry(e,s);return o.rotateZ(Math.PI/6),o.rotateX(Math.PI/2),o.translate(this.position.x,this.position.y,this.position.z),o}createMaterial(){const{metalness:e=0,roughness:t=.15,transmission:n=1,thickness:s=.4,ior:o=1.5}=this.materialOptions,r=n>0;return new y.MeshPhysicalMaterial({color:new y.Color(this.color),metalness:e,roughness:t,transparent:r,transmission:n,thickness:s,ior:o,opacity:1,clearcoat:r?1:0,clearcoatRoughness:.05,sheen:r?1:0,sheenColor:new y.Color(16777215),envMapIntensity:1})}}function Dl(i,e){var d;const t=i.getIndex()?i.toNonIndexed():i,n=t.getAttribute("position").array,s=t.getAttribute("normal").array,o=(d=t.getAttribute("uv"))==null?void 0:d.array,r=new Float32Array(n.length*e.length),a=new Float32Array(s.length*e.length),c=o?new Float32Array(o.length*e.length):void 0;e.forEach((u,f)=>{const m=f*n.length;r.set(n,m);for(let E=m;E<m+n.length;E+=3)r[E]+=u.x,r[E+1]+=u.y,r[E+2]+=u.z;a.set(s,f*s.length),c&&o&&c.set(o,f*o.length)});const h=new y.BufferGeometry;return h.setAttribute("position",new y.BufferAttribute(r,3)),h.setAttribute("normal",new y.BufferAttribute(a,3)),c&&h.setAttribute("uv",new y.BufferAttribute(c,2)),h}class Nl{constructor(){this.name="Hexagonal Glass Grid"}createGrid(e){var E,b,w,A,S,_,x;const t=new y.Group,n=((E=e.styleOptions)==null?void 0:E.hexRadius)??Math.floor(e.divisions/2),s=((b=e.styleOptions)==null?void 0:b.tileSize)||1,o=String(e.color||"#ffffff"),r=Vt.getGridSpacing(s),a=r.width,c=r.height,h=new Ol(new y.Vector3(0,0,0),s,o,{metalness:(w=e.styleOptions)==null?void 0:w.metalness,roughness:(A=e.styleOptions)==null?void 0:A.roughness,transmission:(S=e.styleOptions)==null?void 0:S.transmission,thickness:(_=e.styleOptions)==null?void 0:_.thickness,ior:(x=e.styleOptions)==null?void 0:x.ior}),d=h.createGeometry(),u=Vt.getYPosition(s),f=[];for(let v=-n;v<=n;v++){const L=Math.max(-n,-v-n),I=Math.min(n,-v+n);for(let C=L;C<=I;C++)f.push(new y.Vector3(a*(v+C/2),u,c*.75*C))}const m=new y.Mesh(Dl(d,f),h.createMaterial());return m.receiveShadow=!0,t.add(m),d.dispose(),t.add(this.createShadowCatcher(a*(n+.5))),t}createShadowCatcher(e){const t=new y.Mesh(new y.CircleGeometry(Math.max(e,1),64),new y.ShadowMaterial({opacity:.35}));return t.name=Ht,t.userData[Cs]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}dispose(){}}class kl{constructor(){this.name="Stone Tile Grid",this.textureLoader=new y.TextureLoader}createGrid(e){var m,E,b,w;const t=new y.Group,n=e.size,s=Math.max(1,e.divisions),o=n/s,r=o*.02,a=o-r,c=((m=e.styleOptions)==null?void 0:m.height)||o*.05,h=((E=e.styleOptions)==null?void 0:E.bevelSize)||c*.2,d=((b=e.styleOptions)==null?void 0:b.randomHeight)||!1,u=((w=e.styleOptions)==null?void 0:w.randomRotation)||!1,f=this.createStoneMaterial(e);for(let A=0;A<s;A++)for(let S=0;S<s;S++){const _=(A-s/2)*o+o/2,x=(S-s/2)*o+o/2,v=d?c*(.8+Math.random()*.4):c,L=new y.Shape,I=a/2;L.moveTo(-I,-I),L.lineTo(I,-I),L.lineTo(I,I),L.lineTo(-I,I),L.closePath();const C={depth:v,bevelEnabled:!0,bevelSize:h,bevelThickness:h,bevelSegments:2},D=new y.ExtrudeGeometry(L,C);D.rotateX(-Math.PI/2);const P=new y.Mesh(D,f);P.position.set(_,-v/2,x),P.castShadow=!0,P.receiveShadow=!0,u&&(P.rotation.y=Math.floor(Math.random()*4)*(Math.PI/2)),t.add(P)}return t}createStoneMaterial(e){var r,a,c,h,d;const t=new y.Color(e.color||8421504),n=((r=e.styleOptions)==null?void 0:r.metalness)||0,s=((a=e.styleOptions)==null?void 0:a.roughness)||.8,o={color:t,metalness:n,roughness:s};if((c=e.styleOptions)!=null&&c.texture){const u=this.loadTexture(e.styleOptions.texture);u&&(o.map=u,u.wrapS=u.wrapT=y.RepeatWrapping,u.repeat.set(1,1))}if((h=e.styleOptions)!=null&&h.normalMap){const u=this.loadTexture(e.styleOptions.normalMap);u&&(o.normalMap=u,u.wrapS=u.wrapT=y.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=y.RepeatWrapping,u.repeat.set(1,1))}return new y.MeshStandardMaterial(o)}loadTexture(e){try{return this.textureLoader.load(e)}catch(t){return console.warn("Failed to load texture:",e,t),null}}}class Fl{constructor(){this.name="Shadow Floor"}createGrid(e){const t=new y.Group,n=Math.max(e.size||1,1)*1.5;return t.add(this.createShadowCatcher(n)),t.add(this.createPathTracingDome(n)),t}createShadowCatcher(e){const t=new y.Mesh(new y.CircleGeometry(Math.max(e,1),64),new y.ShadowMaterial({opacity:.28}));return t.name=Ht,t.userData[Cs]=!0,t.rotation.x=-Math.PI/2,t.position.y=.002,t.receiveShadow=!0,t}createPathTracingDome(e){const t=Math.max(e,1),n=t*1.6,s=t*2,o=t*.5,r=n-o,a=[new y.Vector2(0,0),new y.Vector2(r,0)],c=16;for(let d=1;d<=c;d+=1){const u=d/c*(Math.PI/2);a.push(new y.Vector2(r+o*Math.sin(u),o*(1-Math.cos(u))))}a.push(new y.Vector2(n,s));const h=new y.Mesh(new y.LatheGeometry(a,96),new y.MeshStandardMaterial({color:"#f0f0f0",roughness:1,metalness:0,side:y.DoubleSide}));return h.userData[Ps]=!0,h.position.y=.001,h.receiveShadow=!0,h.visible=!1,h}dispose(){}}const Ni=class Ni{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(Tt.SQUARE_WIRE);if(!o)throw new Error("Square wire grid style not found");return o.createGrid(t)}const s=n.createGrid(t);return s.name=`Grid_${e}`,s}static registerGridStyle(e,t){this.gridStyles.set(e,t)}static getAvailableTypes(){return Array.from(this.gridStyles.keys())}static disposeGridStyle(e){const t=this.gridStyles.get(e);t&&t.dispose&&t.dispose()}};Ni.gridStyles=new Map([[Tt.SHADOW_FLOOR,new Fl],[Tt.SQUARE_WIRE,new Il],[Tt.HEXAGONAL_WIRE,new Ll],[Tt.HEXAGONAL_GLASS,new Nl],[Tt.STONE_TILES,new kl]]);let Ts=Ni;function Bl(i,e){try{const t=ot(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));if(e.grid){const n=t.userData,s=typeof e.grid=="object"?e.grid:null,o={enabled:!0,color:(s==null?void 0:s.colorGrid)||e.gridColor||"#AAAAAA",type:s!=null&&s.type?s.type:Tt.HEXAGONAL_GLASS,opacity:s==null?void 0:s.opacity,styleOptions:s==null?void 0:s.styleOptions};if(t.userData={...n,gridOptions:o},s!=null&&s.size||s!=null&&s.divisions){const r=o.type||Tt.HEXAGONAL_GLASS,a=s.size||10,c=s.divisions||10,h={size:a,divisions:c,color:o.color,opacity:o.opacity,styleOptions:{hexRadius:Math.floor(c/2),tileSize:1,...o.styleOptions}},d=Ts.createGrid(r,h);d.userData.isGrid=!0,d.userData.isDefaultGrid=!0,t.add(d)}}if(e.axes){const n=e.axesSize||5,s=new y.AxesHelper(n);t.add(s)}return N.ok(void 0)}catch(t){return N.err(new Z("Failed to add helpers to scene",K.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function zl(i,e,t=1.2){var n;try{const s=ot(i);if(!s)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const o=s.userData,r=o==null?void 0:o.gridOptions;if(!(r!=null&&r.enabled))return N.ok(void 0);const a=[];s.traverse(D=>{var P,F,k;((P=D.userData)!=null&&P.isGrid||(F=D.userData)!=null&&F.isHexGrid||(k=D.userData)!=null&&k.isDefaultGrid)&&a.push(D)}),a.forEach(D=>{Ms(D),s.remove(D)});const c=wt(e);if(!c)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const h=new y.Box3().setFromObject(c),d=h.getSize(new y.Vector3);if(h.isEmpty()||!Number.isFinite(d.x)||!Number.isFinite(d.z))return console.warn("Skipping dynamic grid: object has an empty or non-finite bounding box"),N.ok(void 0);const u=(n=r.styleOptions)==null?void 0:n.tileSize,f=typeof u=="number"?u:1,E=Vt.getGridSpacing(f).width,b=Math.max(d.x,d.z)*t+d.y;let w=b<=E?0:Math.ceil((b/E-1)/2);const A=60;w>A&&(console.warn(`Dynamic grid would need ${w} rings to cover the object; capping at ${A}. The floor will not fully reach the configured coverage for this tileSize/object-size combination.`),w=A),b<E*.8?w=0:w<3&&b>E*2&&(w=3);const S=r.type||Tt.HEXAGONAL_GLASS,x={size:Math.max(d.x,d.z)*t,divisions:w*2+1,color:r.color,opacity:r.opacity,styleOptions:{hexRadius:w,tileSize:f,...r.styleOptions}},v=Ts.createGrid(S,x);v.userData.isGrid=!0,v.userData.isHexGrid=!0;const L=y.MathUtils.clamp(d.y*.0025,2e-4,.002),I=v.getObjectByName(Ht);I&&(I.position.y=L),v.traverse(D=>{var P;(P=D.userData)!=null&&P[Ps]&&(D.position.y=L)});const C=h.getCenter(new y.Vector3);return v.position.set(C.x,0,C.z),s.add(v),N.ok(void 0)}catch(s){return N.err(new Z("Failed to add dynamic grid",K.SCENE_OPERATION_FAILED,{originalError:s}))}}function Ul(i,e){try{const t=ot(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=wt(e);if(!n)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const s=_=>{var v,L,I;let x=_;for(;x;){if((v=x.userData)!=null&&v.isGrid||(L=x.userData)!=null&&L.isHexGrid||(I=x.userData)!=null&&I.isDefaultGrid)return!0;x=x.parent}return!1};t.updateMatrixWorld(!0);const o=[];t.traverse(_=>{var x;(x=_.userData)!=null&&x[Ps]||_.isMesh&&s(_)&&o.push(_)});const r=[];if(n.traverse(_=>{_.isMesh&&r.push(_)}),o.length===0||r.length===0)return N.ok(void 0);let a=-1/0;const c=new y.Box3;for(const _ of o)c.setFromObject(_),Number.isFinite(c.max.y)&&(a=Math.max(a,c.max.y));if(!Number.isFinite(a))return N.ok(void 0);const h=new y.Box3().setFromObject(n);if(h.isEmpty()||!Number.isFinite(h.min.x)||!Number.isFinite(h.max.x))return N.ok(void 0);const d=40,u=Math.max(1,h.max.y-h.min.y),f=h.max.y+u,m=h.min.y-u,E=new y.Raycaster,b=new y.Vector3(0,-1,0),w=new y.Vector3(0,1,0);let A=1/0;const S=(_,x,v,L)=>{E.set(new y.Vector3(_,x,v),L);for(const I of E.intersectObjects(r,!1))I.point.y<A&&(A=I.point.y)};for(let _=0;_<=d;_++)for(let x=0;x<=d;x++){const v=h.min.x+(h.max.x-h.min.x)*(_/d),L=h.min.z+(h.max.z-h.min.z)*(x/d);S(v,f,L,b),S(v,m,L,w)}if(Number.isFinite(A)){const _=A-a;Math.abs(_)>1e-4&&(n.position.y-=_)}return N.ok(void 0)}catch(t){return N.err(new Z("Failed to snap object to floor",K.SCENE_OPERATION_FAILED,{originalError:t}))}}const to=i=>{let e=null;return i.traverse(t=>{!e&&t.isDirectionalLight&&(e=t)}),e};function Hl(i,e){try{const t=ot(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=wt(e);if(!n)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const s=new y.Box3().setFromObject(n);if(s.isEmpty()||!Number.isFinite(s.min.x)||!Number.isFinite(s.max.x))return N.ok(void 0);const o=s.getSize(new y.Vector3),r=s.getCenter(new y.Vector3),a=to(t);if(!a||!a.castShadow)return N.ok(void 0);if(a.parent===t&&a.target.parent===t){const S=a.position.clone().sub(a.target.position);a.target.position.copy(r),a.position.copy(r).add(S)}const u=Math.max(o.x,o.y,o.z,.1)*2,f=a.shadow.camera;f.left=-u,f.right=u,f.top=u,f.bottom=-u;const m=a.getWorldPosition(new y.Vector3),b=a.target.getWorldPosition(new y.Vector3).sub(m).normalize(),w=r.clone().sub(m).dot(b),A=u*2;return f.near=Math.max(w-A,w*.01),f.far=w+A,f.updateProjectionMatrix(),N.ok(void 0)}catch(t){return N.err(new Z("Failed to fit shadow camera to object",K.SCENE_OPERATION_FAILED,{originalError:t}))}}function Vl(i,e,t,n){try{const s=ot(i);if(!s)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const o=wt(e);if(!o)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const r=eo(t.getInternalRenderer());if(!r||!r.shadowMap.enabled)return N.ok(void 0);const a=to(s);return!a||!a.castShadow||n.bake({renderer:r,scene:s,object:o,light:a}),N.ok(void 0)}catch(s){return N.err(new Z("Failed to bake contact shadow",K.SCENE_OPERATION_FAILED,{originalError:s}))}}function Gl(i){try{const e=ot(i);return e?(Jr(e),N.ok(void 0)):N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER))}catch(e){return N.err(new Z("Failed to reset the contact shadow",K.SCENE_OPERATION_FAILED,{originalError:e}))}}function jl(i,e){try{const t=ot(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=t.getObjectByName(Ii),s=t.getObjectByName(Ht);return e==="baked"&&!n||(n&&(n.visible=e==="baked"),s&&(s.visible=e==="live")),N.ok(void 0)}catch(t){return N.err(new Z("Failed to switch contact shadow mode",K.SCENE_OPERATION_FAILED,{originalError:t}))}}function Wl(i,e){try{const t=wt(i);if(!t)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const n=new y.Group;return n.name=oa,n.scale.setScalar(e),n.add(t),N.ok(new Ke(n))}catch(t){return N.err(new Z("Failed to apply the units scale to the model",K.SCENE_OPERATION_FAILED,{originalError:t}))}}function Zl(i,e){try{const t=ot(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));if(e.ambient){const s=new y.Color(e.ambient.color||"#404040"),o=e.ambient.intensity??Math.PI,r=new y.AmbientLight(s,o);t.add(r)}if(e.hemisphere){const s=new y.Color(e.hemisphere.skyColor||"#ffffbb"),o=new y.Color(e.hemisphere.groundColor||"#080820"),r=e.hemisphere.intensity??1,a=new y.HemisphereLight(s,o,r);t.add(a)}if(e.directional){const s=new y.Color(e.directional.color||"#ffffff"),o=e.directional.intensity??Math.PI,r=new y.DirectionalLight(s,o);if(e.directional.position){const a=e.directional.position;if(a instanceof y.Vector3)r.position.copy(a);else if(Array.isArray(a))r.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;r.position.set(c.x,c.y,c.z)}}else r.position.set(6,6,6);if(e.directional.castShadow&&(r.castShadow=!0,e.directional.shadow)){const a=e.directional.shadow;if(a.mapSize&&(r.shadow.mapSize.width=a.mapSize.width,r.shadow.mapSize.height=a.mapSize.height),a.camera){const c=r.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&&(r.shadow.bias=a.bias),a.radius!==void 0&&(r.shadow.radius=a.radius)}r.target.position.set(0,0,0),t.add(r),t.add(r.target),r.shadow&&r.shadow.camera.updateProjectionMatrix()}const n=(s,o)=>{const r=new y.DirectionalLight(new y.Color(s.color||"#ffffff"),s.intensity??1),a=s.position??o;r.position.set(a[0],a[1],a[2]),r.target.position.set(0,0,0),t.add(r),t.add(r.target)};return e.fill&&n(e.fill,[-60,30,30]),e.rim&&n(e.rim,[20,50,-70]),N.ok(void 0)}catch(t){return N.err(new Z("Failed to add lighting to scene",K.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function Kl(i,e){try{const t=ot(i);if(!t)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const n=document.createElement("canvas");n.width=e.radial?512:2,n.height=512;const s=n.getContext("2d");if(!s)return N.err(new Z("Failed to create canvas context",K.SCENE_OPERATION_FAILED));const o=e.radial?s.createRadialGradient(256,205,0,256,256,380):s.createLinearGradient(0,0,0,n.height);o.addColorStop(0,e.topColor),o.addColorStop(1,e.bottomColor),s.fillStyle=o,s.fillRect(0,0,n.width,n.height);const r=new y.CanvasTexture(n);r.needsUpdate=!0;const a=t.background;return a instanceof y.Texture&&a!==t.environment&&a.dispose(),t.background=r,N.ok(void 0)}catch(t){return N.err(new Z("Failed to create gradient background",K.SCENE_OPERATION_FAILED,{originalError:t,options:e}))}}function Xl(i,e,t){try{const n=wt(i);if(!n)return N.err(new Z("Object must expose a Three.js Object3D",K.INVALID_PARAMETER));const s=Pn(e);if(!(s instanceof y.PerspectiveCamera)&&!(s instanceof y.OrthographicCamera))return N.err(new Z("Camera must expose a perspective or orthographic Three.js camera",K.INVALID_PARAMETER));const o=Li(t);if(!o)return N.err(new Z("Controls must expose the underlying Three.js controls",K.INVALID_PARAMETER));const r=new y.Box3().setFromObject(n),a=r.getCenter(new y.Vector3),c=r.getSize(new y.Vector3),h=Math.max(c.x,c.y,c.z);let d;"fov"in s?d=s.fov*(Math.PI/180):d=50*(Math.PI/180);let u=Math.abs(h/2/Math.tan(d/2));u*=1.65;const f=-Math.PI/4,m=Math.PI/8,E=a.x+u*Math.sin(f)*Math.cos(m),b=a.y+u*Math.sin(m),w=a.z+u*Math.cos(f)*Math.cos(m);return s.position.set(E,b,w),s.lookAt(a),s.updateProjectionMatrix(),o.target&&(o.target.copy(a),o.update()),N.ok(void 0)}catch(n){return N.err(new Z("Failed to fit camera to object",K.CAMERA_INIT_FAILED,{originalError:n}))}}class Yl{constructor(){this.contactShadowBaker=new Si}addHelpers(e,t){return Bl(e,t)}addDynamicGrid(e,t,n=1.2){return zl(e,t,n)}snapObjectToFloor(e,t){return Ul(e,t)}fitShadowCameraToObject(e,t){return Hl(e,t)}bakeContactShadow(e,t,n){return Vl(e,t,n,this.contactShadowBaker)}resetContactShadow(e){return Gl(e)}setContactShadowMode(e,t){return jl(e,t)}wrapInUnitsScaleGroup(e,t){return Wl(e,t)}addLighting(e,t){return Zl(e,t)}createGradientBackground(e,t){return Kl(e,t)}fitCameraToObject(e,t,n){return Xl(e,t,n)}}class ql{constructor(){this.events=new bs,this.disposed=!1}async initialize(e){const{ThreePathTracingService:t}=await Promise.resolve().then(()=>require("./ThreePathTracingService-VOgJGtMH.cjs"));if(this.disposed)return N.ok(void 0);const n=new t;return this.inner=n,n.events.on("pathtracing:paused",s=>{this.events.emit("pathtracing:paused",s)}),this.pendingSettings&&(n.updateSettings(this.pendingSettings),this.pendingSettings=void 0),this.pendingEnabled!==void 0&&(n.setEnabled(this.pendingEnabled),this.pendingEnabled=void 0),n.initialize(e)}setEnabled(e){this.inner?this.inner.setEnabled(e):this.pendingEnabled=e}updateSettings(e){this.inner?this.inner.updateSettings(e):this.pendingSettings={...this.pendingSettings,...e}}render(e,t){return this.inner?this.inner.render(e,t):Promise.resolve(N.ok(void 0))}getSampleCount(){var e;return((e=this.inner)==null?void 0:e.getSampleCount())??0}isEnabled(){var e;return((e=this.inner)==null?void 0:e.isEnabled())??!1}isPathTracerDisposed(){var e;return((e=this.inner)==null?void 0:e.isPathTracerDisposed())??!1}canResume(){var e;return((e=this.inner)==null?void 0:e.canResume())??!1}reset(e){var t;(t=this.inner)==null||t.reset(e)}dispose(){var e;this.disposed=!0,(e=this.inner)==null||e.dispose()}isSupported(){var e;return((e=this.inner)==null?void 0:e.isSupported())??!0}}/*!
|
|
21
|
-
fflate - fast JavaScript compression/decompression
|
|
22
|
-
<https://101arrowz.github.io/fflate>
|
|
23
|
-
Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
|
|
24
|
-
version 0.8.2
|
|
25
|
-
*/var it=Uint8Array,rn=Uint16Array,$l=Int32Array,no=new it([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),so=new it([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ql=new it([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),io=function(i,e){for(var t=new rn(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new $l(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)s[o]=o-t[n]<<5|n;return{b:t,r:s}},ro=io(no,2),oo=ro.b,Jl=ro.r;oo[28]=258,Jl[258]=28;var eh=io(so,0),th=eh.b,_i=new rn(32768);for(var be=0;be<32768;++be){var Ct=(be&43690)>>1|(be&21845)<<1;Ct=(Ct&52428)>>2|(Ct&13107)<<2,Ct=(Ct&61680)>>4|(Ct&3855)<<4,_i[be]=((Ct&65280)>>8|(Ct&255)<<8)>>1}var An=(function(i,e,t){for(var n=i.length,s=0,o=new rn(e);s<n;++s)i[s]&&++o[i[s]-1];var r=new rn(e);for(s=1;s<e;++s)r[s]=r[s-1]+o[s-1]<<1;var a;if(t){a=new rn(1<<e);var c=15-e;for(s=0;s<n;++s)if(i[s])for(var h=s<<4|i[s],d=e-i[s],u=r[i[s]-1]++<<d,f=u|(1<<d)-1;u<=f;++u)a[_i[u]>>c]=h}else for(a=new rn(n),s=0;s<n;++s)i[s]&&(a[s]=_i[r[i[s]-1]++]>>15-i[s]);return a}),In=new it(288);for(var be=0;be<144;++be)In[be]=8;for(var be=144;be<256;++be)In[be]=9;for(var be=256;be<280;++be)In[be]=7;for(var be=280;be<288;++be)In[be]=8;var ao=new it(32);for(var be=0;be<32;++be)ao[be]=5;var nh=An(In,9,1),sh=An(ao,5,1),Js=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},ht=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},ei=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},ih=function(i){return(i+7)/8|0},rh=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new it(i.subarray(e,t))},oh=["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"],dt=function(i,e,t){var n=new Error(e||oh[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,dt),!t)throw n;return n},ah=function(i,e,t,n){var s=i.length,o=0;if(!s||e.f&&!e.l)return t||new it(0);var r=!t,a=r||e.i!=2,c=e.i;r&&(t=new it(s*3));var h=function(Gt){var St=t.length;if(Gt>St){var Ln=new it(Math.max(St*2,Gt));Ln.set(t),t=Ln}},d=e.f||0,u=e.p||0,f=e.b||0,m=e.l,E=e.d,b=e.m,w=e.n,A=s*8;do{if(!m){d=ht(i,u,1);var S=ht(i,u+1,3);if(u+=3,S)if(S==1)m=nh,E=sh,b=9,w=5;else if(S==2){var L=ht(i,u,31)+257,I=ht(i,u+10,15)+4,C=L+ht(i,u+5,31)+1;u+=14;for(var D=new it(C),P=new it(19),F=0;F<I;++F)P[Ql[F]]=ht(i,u+F*3,7);u+=I*3;for(var k=Js(P),U=(1<<k)-1,z=An(P,k,1),F=0;F<C;){var Y=z[ht(i,u,U)];u+=Y&15;var _=Y>>4;if(_<16)D[F++]=_;else{var re=0,Ne=0;for(_==16?(Ne=3+ht(i,u,3),u+=2,re=D[F-1]):_==17?(Ne=3+ht(i,u,7),u+=3):_==18&&(Ne=11+ht(i,u,127),u+=7);Ne--;)D[F++]=re}}var at=D.subarray(0,L),Me=D.subarray(L);b=Js(at),w=Js(Me),m=An(at,b,1),E=An(Me,w,1)}else dt(1);else{var _=ih(u)+4,x=i[_-4]|i[_-3]<<8,v=_+x;if(v>s){c&&dt(0);break}a&&h(f+x),t.set(i.subarray(_,v),f),e.b=f+=x,e.p=u=v*8,e.f=d;continue}if(u>A){c&&dt(0);break}}a&&h(f+131072);for(var ze=(1<<b)-1,Ge=(1<<w)-1,ve=u;;ve=u){var re=m[ei(i,u)&ze],Ee=re>>4;if(u+=re&15,u>A){c&&dt(0);break}if(re||dt(2),Ee<256)t[f++]=Ee;else if(Ee==256){ve=u,m=null;break}else{var pt=Ee-254;if(Ee>264){var F=Ee-257,je=no[F];pt=ht(i,u,(1<<je)-1)+oo[F],u+=je}var At=E[ei(i,u)&Ge],ye=At>>4;At||dt(3),u+=At&15;var Me=th[ye];if(ye>3){var je=so[ye];Me+=ei(i,u)&(1<<je)-1,u+=je}if(u>A){c&&dt(0);break}a&&h(f+131072);var ct=f+pt;if(f<Me){var lt=o-Me,ln=Math.min(Me,ct);for(lt+f<0&&dt(3);f<ln;++f)t[f]=n[lt+f]}for(;f<ct;++f)t[f]=t[f-Me]}}e.l=m,e.p=ve,e.b=f,e.f=d,m&&(d=1,e.m=b,e.d=E,e.n=w)}while(!d);return f!=t.length&&r?rh(t,0,f):t.subarray(0,f)},ch=new it(0),lh=function(i,e){return((i[0]&15)!=8||i[0]>>4>7||(i[0]<<8|i[1])%31)&&dt(6,"invalid zlib data"),(i[1]>>5&1)==1&&dt(6,"invalid zlib data: "+(i[1]&32?"need":"unexpected")+" dictionary"),(i[1]>>3&4)+2};function Sn(i,e){return ah(i.subarray(lh(i),-4),{i:2},e,e)}var hh=typeof TextDecoder<"u"&&new TextDecoder,uh=0;try{hh.decode(ch,{stream:!0}),uh=1}catch{}class dh extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType,this.outputFormat=p.RGBAFormat,this.part=0}parse(e){const D=Math.pow(2.7182818,2.2);let P=null;function F(l,g){let T=0;for(let O=0;O<65536;++O)(O==0||l[O>>3]&1<<(O&7))&&(g[T++]=O);const M=T-1;for(;T<65536;)g[T++]=0;return M}function k(l){for(let g=0;g<16384;g++)l[g]={},l[g].len=0,l[g].lit=0,l[g].p=null}const U={l:0,c:0,lc:0};function z(l,g,T,M,O){for(;T<l;)g=g<<8|Hi(M,O),T+=8;T-=l,U.l=g>>T&(1<<l)-1,U.c=g,U.lc=T}const Y=new Array(59);function re(l){for(let T=0;T<=58;++T)Y[T]=0;for(let T=0;T<65537;++T)Y[l[T]]+=1;let g=0;for(let T=58;T>0;--T){const M=g+Y[T]>>1;Y[T]=g,g=M}for(let T=0;T<65537;++T){const M=l[T];M>0&&(l[T]=M|Y[M]++<<6)}}function Ne(l,g,T,M,O,H){const R=g;let G=0,B=0;for(;M<=O;M++){if(R.value-g.value>T)return!1;z(6,G,B,l,R);const V=U.l;if(G=U.c,B=U.lc,H[M]=V,V==63){if(R.value-g.value>T)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");z(8,G,B,l,R);let j=U.l+6;if(G=U.c,B=U.lc,M+j>O+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)H[M++]=0;M--}else if(V>=59){let j=V-59+2;if(M+j>O+1)throw new Error("THREE.EXRLoader: Something wrong with hufUnpackEncTable");for(;j--;)H[M++]=0;M--}}re(H)}function at(l){return l&63}function Me(l){return l>>6}function ze(l,g,T,M){for(;g<=T;g++){const O=Me(l[g]),H=at(l[g]);if(O>>H)throw new Error("THREE.EXRLoader: Invalid table entry");if(H>14){const R=M[O>>H-14];if(R.len)throw new Error("THREE.EXRLoader: Invalid table entry");if(R.lit++,R.p){const G=R.p;R.p=new Array(R.lit);for(let B=0;B<R.lit-1;++B)R.p[B]=G[B]}else R.p=new Array(1);R.p[R.lit-1]=g}else if(H){let R=0;for(let G=1<<14-H;G>0;G--){const B=M[(O<<14-H)+R];if(B.len||B.p)throw new Error("THREE.EXRLoader: Invalid table entry");B.len=H,B.lit=g,R++}}}return!0}const Ge={c:0,lc:0};function ve(l,g,T,M){l=l<<8|Hi(T,M),g+=8,Ge.c=l,Ge.lc=g}const Ee={c:0,lc:0};function pt(l,g,T,M,O,H,R,G,B){if(l==g){M<8&&(ve(T,M,O,H),T=Ge.c,M=Ge.lc),M-=8;let V=T>>M;if(V=new Uint8Array([V])[0],G.value+V>B)return!1;const j=R[G.value-1];for(;V-- >0;)R[G.value++]=j}else if(G.value<B)R[G.value++]=l;else return!1;Ee.c=T,Ee.lc=M}function je(l){return l&65535}function At(l){const g=je(l);return g>32767?g-65536:g}const ye={a:0,b:0};function ct(l,g){const T=At(l),O=At(g),H=T+(O&1)+(O>>1),R=H,G=H-O;ye.a=R,ye.b=G}function lt(l,g){const T=je(l),M=je(g),O=T-(M>>1)&65535,H=M+O-32768&65535;ye.a=H,ye.b=O}function ln(l,g,T,M,O,H,R){const G=R<16384,B=T>O?O:T;let V=1,j,X;for(;V<=B;)V<<=1;for(V>>=1,j=V,V>>=1;V>=1;){X=0;const W=X+H*(O-j),$=H*V,ee=H*j,q=M*V,Q=M*j;let oe,he,ae,de;for(;X<=W;X+=ee){let ne=X;const te=X+M*(T-j);for(;ne<=te;ne+=Q){const ie=ne+q,Te=ne+$,me=Te+q;G?(ct(l[ne+g],l[Te+g]),oe=ye.a,ae=ye.b,ct(l[ie+g],l[me+g]),he=ye.a,de=ye.b,ct(oe,he),l[ne+g]=ye.a,l[ie+g]=ye.b,ct(ae,de),l[Te+g]=ye.a,l[me+g]=ye.b):(lt(l[ne+g],l[Te+g]),oe=ye.a,ae=ye.b,lt(l[ie+g],l[me+g]),he=ye.a,de=ye.b,lt(oe,he),l[ne+g]=ye.a,l[ie+g]=ye.b,lt(ae,de),l[Te+g]=ye.a,l[me+g]=ye.b)}if(T&V){const ie=ne+$;G?ct(l[ne+g],l[ie+g]):lt(l[ne+g],l[ie+g]),oe=ye.a,l[ie+g]=ye.b,l[ne+g]=oe}}if(O&V){let ne=X;const te=X+M*(T-j);for(;ne<=te;ne+=Q){const ie=ne+q;G?ct(l[ne+g],l[ie+g]):lt(l[ne+g],l[ie+g]),oe=ye.a,l[ie+g]=ye.b,l[ne+g]=oe}}j=V,V>>=1}return X}function Gt(l,g,T,M,O,H,R,G,B){let V=0,j=0;const X=R,W=Math.trunc(M.value+(O+7)/8);for(;M.value<W;)for(ve(V,j,T,M),V=Ge.c,j=Ge.lc;j>=14;){const ee=V>>j-14&16383,q=g[ee];if(q.len)j-=q.len,pt(q.lit,H,V,j,T,M,G,B,X),V=Ee.c,j=Ee.lc;else{if(!q.p)throw new Error("THREE.EXRLoader: hufDecode issues");let Q;for(Q=0;Q<q.lit;Q++){const oe=at(l[q.p[Q]]);for(;j<oe&&M.value<W;)ve(V,j,T,M),V=Ge.c,j=Ge.lc;if(j>=oe&&Me(l[q.p[Q]])==(V>>j-oe&(1<<oe)-1)){j-=oe,pt(q.p[Q],H,V,j,T,M,G,B,X),V=Ee.c,j=Ee.lc;break}}if(Q==q.lit)throw new Error("THREE.EXRLoader: hufDecode issues")}}const $=8-O&7;for(V>>=$,j-=$;j>0;){const ee=g[V<<14-j&16383];if(ee.len)j-=ee.len,pt(ee.lit,H,V,j,T,M,G,B,X),V=Ee.c,j=Ee.lc;else throw new Error("THREE.EXRLoader: hufDecode issues")}return!0}function St(l,g,T,M,O,H){const R={value:0},G=T.value,B=Je(g,T),V=Je(g,T);T.value+=4;const j=Je(g,T);if(T.value+=4,B<0||B>=65537||V<0||V>=65537)throw new Error("THREE.EXRLoader: Something wrong with HUF_ENCSIZE");const X=new Array(65537),W=new Array(16384);k(W);const $=M-(T.value-G);if(Ne(l,T,$,B,V,X),j>8*(M-(T.value-G)))throw new Error("THREE.EXRLoader: Something wrong with hufUncompress");ze(X,B,V,W),Gt(X,W,l,T,j,V,H,O,R)}function Ln(l,g,T){for(let M=0;M<T;++M)g[M]=l[g[M]]}function On(l){for(let g=1;g<l.length;g++){const T=l[g-1]+l[g]-128;l[g]=T}}function Dn(l,g){let T=0,M=Math.floor((l.length+1)/2),O=0;const H=l.length-1;for(;!(O>H||(g[O++]=l[T++],O>H));)g[O++]=l[M++]}function Is(l){let g=l.byteLength;const T=new Array;let M=0;const O=new DataView(l);for(;g>0;){const H=O.getInt8(M++);if(H<0){const R=-H;g-=R+1;for(let G=0;G<R;G++)T.push(O.getUint8(M++))}else{const R=H;g-=2;const G=O.getUint8(M++);for(let B=0;B<R+1;B++)T.push(G)}}return T}function So(l,g,T,M,O,H){let R=new DataView(H.buffer);const G=T[l.idx[0]].width,B=T[l.idx[0]].height,V=3,j=Math.floor(G/8),X=Math.ceil(G/8),W=Math.ceil(B/8),$=G-(X-1)*8,ee=B-(W-1)*8,q={value:0},Q=new Array(V),oe=new Array(V),he=new Array(V),ae=new Array(V),de=new Array(V);for(let te=0;te<V;++te)de[te]=g[l.idx[te]],Q[te]=te<1?0:Q[te-1]+X*W,oe[te]=new Float32Array(64),he[te]=new Uint16Array(64),ae[te]=new Uint16Array(X*64);for(let te=0;te<W;++te){let ie=8;te==W-1&&(ie=ee);let Te=8;for(let ce=0;ce<X;++ce){ce==X-1&&(Te=$);for(let ue=0;ue<V;++ue)he[ue].fill(0),he[ue][0]=O[Q[ue]++],ki(q,M,he[ue]),Fi(he[ue],oe[ue]),Bi(oe[ue]);bo(oe);for(let ue=0;ue<V;++ue)zi(oe[ue],ae[ue],ce*64)}let me=0;for(let ce=0;ce<V;++ce){const ue=T[l.idx[ce]].type;for(let Ce=8*te;Ce<8*te+ie;++Ce){me=de[ce][Ce];for(let et=0;et<j;++et){const _e=et*64+(Ce&7)*8;R.setUint16(me+0*ue,ae[ce][_e+0],!0),R.setUint16(me+2*ue,ae[ce][_e+1],!0),R.setUint16(me+4*ue,ae[ce][_e+2],!0),R.setUint16(me+6*ue,ae[ce][_e+3],!0),R.setUint16(me+8*ue,ae[ce][_e+4],!0),R.setUint16(me+10*ue,ae[ce][_e+5],!0),R.setUint16(me+12*ue,ae[ce][_e+6],!0),R.setUint16(me+14*ue,ae[ce][_e+7],!0),me+=16*ue}}if(j!=X)for(let Ce=8*te;Ce<8*te+ie;++Ce){const et=de[ce][Ce]+8*j*2*ue,_e=j*64+(Ce&7)*8;for(let mt=0;mt<Te;++mt)R.setUint16(et+mt*2*ue,ae[ce][_e+mt],!0)}}}const ne=new Uint16Array(G);R=new DataView(H.buffer);for(let te=0;te<V;++te){T[l.idx[te]].decoded=!0;const ie=T[l.idx[te]].type;if(T[te].type==2)for(let Te=0;Te<B;++Te){const me=de[te][Te];for(let ce=0;ce<G;++ce)ne[ce]=R.getUint16(me+ce*2*ie,!0);for(let ce=0;ce<G;++ce)R.setFloat32(me+ce*2*ie,J(ne[ce]),!0)}}}function _o(l,g,T,M,O,H){const R=new DataView(H.buffer),G=T[l],B=G.width,V=G.height,j=Math.ceil(B/8),X=Math.ceil(V/8),W=Math.floor(B/8),$=B-(j-1)*8,ee=V-(X-1)*8,q={value:0};let Q=0;const oe=new Float32Array(64),he=new Uint16Array(64),ae=new Uint16Array(j*64);for(let de=0;de<X;++de){let ne=8;de==X-1&&(ne=ee);for(let te=0;te<j;++te)he.fill(0),he[0]=O[Q++],ki(q,M,he),Fi(he,oe),Bi(oe),zi(oe,ae,te*64);for(let te=8*de;te<8*de+ne;++te){let ie=g[l][te];for(let Te=0;Te<W;++Te){const me=Te*64+(te&7)*8;for(let ce=0;ce<8;++ce)R.setUint16(ie+ce*2*G.type,ae[me+ce],!0);ie+=16*G.type}if(j!=W){const Te=W*64+(te&7)*8;for(let me=0;me<$;++me)R.setUint16(ie+me*2*G.type,ae[Te+me],!0)}}}G.decoded=!0}function ki(l,g,T){let M,O=1;for(;O<64;)M=g[l.value],M==65280?O=64:M>>8==255?O+=M&255:(T[O]=M,O++),l.value++}function Fi(l,g){g[0]=J(l[0]),g[1]=J(l[1]),g[2]=J(l[5]),g[3]=J(l[6]),g[4]=J(l[14]),g[5]=J(l[15]),g[6]=J(l[27]),g[7]=J(l[28]),g[8]=J(l[2]),g[9]=J(l[4]),g[10]=J(l[7]),g[11]=J(l[13]),g[12]=J(l[16]),g[13]=J(l[26]),g[14]=J(l[29]),g[15]=J(l[42]),g[16]=J(l[3]),g[17]=J(l[8]),g[18]=J(l[12]),g[19]=J(l[17]),g[20]=J(l[25]),g[21]=J(l[30]),g[22]=J(l[41]),g[23]=J(l[43]),g[24]=J(l[9]),g[25]=J(l[11]),g[26]=J(l[18]),g[27]=J(l[24]),g[28]=J(l[31]),g[29]=J(l[40]),g[30]=J(l[44]),g[31]=J(l[53]),g[32]=J(l[10]),g[33]=J(l[19]),g[34]=J(l[23]),g[35]=J(l[32]),g[36]=J(l[39]),g[37]=J(l[45]),g[38]=J(l[52]),g[39]=J(l[54]),g[40]=J(l[20]),g[41]=J(l[22]),g[42]=J(l[33]),g[43]=J(l[38]),g[44]=J(l[46]),g[45]=J(l[51]),g[46]=J(l[55]),g[47]=J(l[60]),g[48]=J(l[21]),g[49]=J(l[34]),g[50]=J(l[37]),g[51]=J(l[47]),g[52]=J(l[50]),g[53]=J(l[56]),g[54]=J(l[59]),g[55]=J(l[61]),g[56]=J(l[35]),g[57]=J(l[36]),g[58]=J(l[48]),g[59]=J(l[49]),g[60]=J(l[57]),g[61]=J(l[58]),g[62]=J(l[62]),g[63]=J(l[63])}function Bi(l){const g=.5*Math.cos(.7853975),T=.5*Math.cos(3.14159/16),M=.5*Math.cos(3.14159/8),O=.5*Math.cos(3*3.14159/16),H=.5*Math.cos(5*3.14159/16),R=.5*Math.cos(3*3.14159/8),G=.5*Math.cos(7*3.14159/16),B=new Array(4),V=new Array(4),j=new Array(4),X=new Array(4);for(let W=0;W<8;++W){const $=W*8;B[0]=M*l[$+2],B[1]=R*l[$+2],B[2]=M*l[$+6],B[3]=R*l[$+6],V[0]=T*l[$+1]+O*l[$+3]+H*l[$+5]+G*l[$+7],V[1]=O*l[$+1]-G*l[$+3]-T*l[$+5]-H*l[$+7],V[2]=H*l[$+1]-T*l[$+3]+G*l[$+5]+O*l[$+7],V[3]=G*l[$+1]-H*l[$+3]+O*l[$+5]-T*l[$+7],j[0]=g*(l[$+0]+l[$+4]),j[3]=g*(l[$+0]-l[$+4]),j[1]=B[0]+B[3],j[2]=B[1]-B[2],X[0]=j[0]+j[1],X[1]=j[3]+j[2],X[2]=j[3]-j[2],X[3]=j[0]-j[1],l[$+0]=X[0]+V[0],l[$+1]=X[1]+V[1],l[$+2]=X[2]+V[2],l[$+3]=X[3]+V[3],l[$+4]=X[3]-V[3],l[$+5]=X[2]-V[2],l[$+6]=X[1]-V[1],l[$+7]=X[0]-V[0]}for(let W=0;W<8;++W)B[0]=M*l[16+W],B[1]=R*l[16+W],B[2]=M*l[48+W],B[3]=R*l[48+W],V[0]=T*l[8+W]+O*l[24+W]+H*l[40+W]+G*l[56+W],V[1]=O*l[8+W]-G*l[24+W]-T*l[40+W]-H*l[56+W],V[2]=H*l[8+W]-T*l[24+W]+G*l[40+W]+O*l[56+W],V[3]=G*l[8+W]-H*l[24+W]+O*l[40+W]-T*l[56+W],j[0]=g*(l[W]+l[32+W]),j[3]=g*(l[W]-l[32+W]),j[1]=B[0]+B[3],j[2]=B[1]-B[2],X[0]=j[0]+j[1],X[1]=j[3]+j[2],X[2]=j[3]-j[2],X[3]=j[0]-j[1],l[0+W]=X[0]+V[0],l[8+W]=X[1]+V[1],l[16+W]=X[2]+V[2],l[24+W]=X[3]+V[3],l[32+W]=X[3]-V[3],l[40+W]=X[2]-V[2],l[48+W]=X[1]-V[1],l[56+W]=X[0]-V[0]}function bo(l){for(let g=0;g<64;++g){const T=l[0][g],M=l[1][g],O=l[2][g];l[0][g]=T+1.5747*O,l[1][g]=T-.1873*M-.4682*O,l[2][g]=T+1.8556*M}}function zi(l,g,T){for(let M=0;M<64;++M)g[T+M]=p.DataUtils.toHalfFloat(xo(l[M]))}function xo(l){return l<=1?Math.sign(l)*Math.pow(Math.abs(l),2.2):Math.sign(l)*Math.pow(D,Math.abs(l)-1)}function Nn(l){return new DataView(l.array.buffer,l.offset.value,l.size)}function Ao(l){const g=l.viewer.buffer.slice(l.offset.value,l.offset.value+l.size),T=new Uint8Array(Is(g)),M=new Uint8Array(T.length);return On(T),Dn(T,M),new DataView(M.buffer)}function Ls(l){const g=l.array.slice(l.offset.value,l.offset.value+l.size),T=Sn(g),M=new Uint8Array(T.length);return On(T),Dn(T,M),new DataView(M.buffer)}function vo(l){const g=l.viewer,T={value:l.offset.value},M=new Uint16Array(l.columns*l.lines*(l.inputChannels.length*l.type)),O=new Uint8Array(8192);let H=0;const R=new Array(l.inputChannels.length);for(let ee=0,q=l.inputChannels.length;ee<q;ee++)R[ee]={},R[ee].start=H,R[ee].end=R[ee].start,R[ee].nx=l.columns,R[ee].ny=l.lines,R[ee].size=l.type,H+=R[ee].nx*R[ee].ny*R[ee].size;const G=hn(g,T),B=hn(g,T);if(B>=8192)throw new Error("THREE.EXRLoader: Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(G<=B)for(let ee=0;ee<B-G+1;ee++)O[ee+G]=vt(g,T);const V=new Uint16Array(65536),j=F(O,V),X=Je(g,T);St(l.array,g,T,X,M,H);for(let ee=0;ee<l.inputChannels.length;++ee){const q=R[ee];for(let Q=0;Q<R[ee].size;++Q)ln(M,q.start+Q,q.nx,q.size,q.ny,q.nx*q.size,j)}Ln(V,M,H);let W=0;const $=new Uint8Array(M.buffer.byteLength);for(let ee=0;ee<l.lines;ee++)for(let q=0;q<l.inputChannels.length;q++){const Q=R[q],oe=Q.nx*Q.size,he=new Uint8Array(M.buffer,Q.end*2,oe*2);$.set(he,W),W+=oe*2,Q.end+=oe}return new DataView($.buffer)}function Ro(l){const g=l.array.slice(l.offset.value,l.offset.value+l.size),T=Sn(g),M=l.inputChannels.length*l.lines*l.columns*l.totalBytes,O=new ArrayBuffer(M),H=new DataView(O);let R=0,G=0;const B=new Array(4);for(let V=0;V<l.lines;V++)for(let j=0;j<l.inputChannels.length;j++){let X=0;switch(l.inputChannels[j].pixelType){case 1:B[0]=R,B[1]=B[0]+l.columns,R=B[1]+l.columns;for(let $=0;$<l.columns;++$){const ee=T[B[0]++]<<8|T[B[1]++];X+=ee,H.setUint16(G,X,!0),G+=2}break;case 2:B[0]=R,B[1]=B[0]+l.columns,B[2]=B[1]+l.columns,R=B[2]+l.columns;for(let $=0;$<l.columns;++$){const ee=T[B[0]++]<<24|T[B[1]++]<<16|T[B[2]++]<<8;X+=ee,H.setUint32(G,X,!0),G+=4}break}}return H}function Mo(l){const g=l.array;let T=l.offset.value;const M=l.columns,O=l.lines,H=l.inputChannels,R=l.totalBytes,G=Ze.compression==="B44A_COMPRESSION",B=new Uint8Array(O*M*R),V=new Uint16Array(16);let j=0;for(let X=0;X<H.length;X++){const W=H[X],$=W.pixelType*2,ee=Math.ceil(M/W.xSampling),q=Math.ceil(O/W.ySampling),Q=W.xSampling===1&&W.ySampling===1;if(W.pixelType!==1){for(let ae=0;ae<q;ae++)if(Q){const de=ae*M*R+j*M;for(let ne=0;ne<ee*$;ne++)B[de+ne]=g[T++]}else T+=ee*$;j+=$;continue}const oe=Math.ceil(ee/4),he=Math.ceil(q/4);for(let ae=0;ae<he;ae++)for(let de=0;de<oe;de++){if(G&&g[T+2]>=52){const ne=g[T]<<8|g[T+1],te=ne&32768?ne&32767:~ne&65535;V.fill(te),T+=3}else{const ne=g[T]<<8|g[T+1],te=g[T+2]>>2,ie=32<<te,Te=ne+((g[T+2]<<4|g[T+3]>>4)&63)*(1<<te)-ie&65535,me=Te+((g[T+3]<<2|g[T+4]>>6)&63)*(1<<te)-ie&65535,ce=me+(g[T+4]&63)*(1<<te)-ie&65535,ue=ne+(g[T+5]>>2&63)*(1<<te)-ie&65535,Ce=Te+((g[T+5]<<4|g[T+6]>>4)&63)*(1<<te)-ie&65535,et=me+((g[T+6]<<2|g[T+7]>>6)&63)*(1<<te)-ie&65535,_e=ce+(g[T+7]&63)*(1<<te)-ie&65535,mt=ue+(g[T+8]>>2&63)*(1<<te)-ie&65535,jt=Ce+((g[T+8]<<4|g[T+9]>>4)&63)*(1<<te)-ie&65535,un=et+((g[T+9]<<2|g[T+10]>>6)&63)*(1<<te)-ie&65535,gt=_e+(g[T+10]&63)*(1<<te)-ie&65535,kt=mt+(g[T+11]>>2&63)*(1<<te)-ie&65535,Un=jt+((g[T+11]<<4|g[T+12]>>4)&63)*(1<<te)-ie&65535,Hn=un+((g[T+12]<<2|g[T+13]>>6)&63)*(1<<te)-ie&65535,Vn=gt+(g[T+13]&63)*(1<<te)-ie&65535,dn=[ne,ue,mt,kt,Te,Ce,jt,Un,me,et,un,Hn,ce,_e,gt,Vn];for(let Wt=0;Wt<16;Wt++)V[Wt]=dn[Wt]&32768?dn[Wt]&32767:~dn[Wt]&65535;T+=14}if(W.pLinear){if(P===null){P=new Uint16Array(65536);for(let ne=0;ne<65536;ne++)if((ne&31744)===31744||ne>32768)P[ne]=0;else{const te=J(ne);P[ne]=te<=0?0:p.DataUtils.toHalfFloat(8*Math.log(te))}}for(let ne=0;ne<16;ne++)V[ne]=P[V[ne]]}for(let ne=0;ne<4;ne++){const te=ae*4+ne;if(!(te>=q))for(let ie=0;ie<4;ie++){const Te=de*4+ie;if(Te>=ee)continue;const me=V[ne*4+ie];for(let ce=0;ce<W.ySampling;ce++){const ue=te*W.ySampling+ce;if(!(ue>=O))for(let Ce=0;Ce<W.xSampling;Ce++){const et=Te*W.xSampling+Ce;if(et>=M)continue;const _e=ue*M*R+j*M+et*2;B[_e]=me&255,B[_e+1]=me>>8&255}}}}}j+=2}return new DataView(B.buffer)}function Ui(l){const g=l.viewer,T={value:l.offset.value},M=new Uint8Array(l.columns*l.lines*(l.inputChannels.length*l.type*2)),O={version:ke(g,T),unknownUncompressedSize:ke(g,T),unknownCompressedSize:ke(g,T),acCompressedSize:ke(g,T),dcCompressedSize:ke(g,T),rleCompressedSize:ke(g,T),rleUncompressedSize:ke(g,T),rleRawSize:ke(g,T),totalAcUncompressedCount:ke(g,T),totalDcUncompressedCount:ke(g,T),acCompression:ke(g,T)};if(O.version<2)throw new Error("THREE.EXRLoader: "+Ze.compression+" version "+O.version+" is unsupported");const H=new Array;let R=hn(g,T)-2;for(;R>0;){const q=kn(g.buffer,T),Q=vt(g,T),oe=Q>>2&3,he=(Q>>4)-1,ae=new Int8Array([he])[0],de=vt(g,T);H.push({name:q,index:ae,type:de,compression:oe}),R-=q.length+3}const G=Ze.channels,B=new Array(l.inputChannels.length);for(let q=0;q<l.inputChannels.length;++q){const Q=B[q]={},oe=G[q];Q.name=oe.name,Q.compression=0,Q.decoded=!1,Q.type=oe.pixelType,Q.pLinear=oe.pLinear,Q.width=l.columns,Q.height=l.lines}const V={idx:new Array(3)};for(let q=0;q<l.inputChannels.length;++q){const Q=B[q],oe=Q.name.lastIndexOf("."),he=oe>=0?Q.name.substring(oe+1):Q.name;for(let ae=0;ae<H.length;++ae){const de=H[ae];he===de.name&&Q.type===de.type&&(Q.compression=de.compression,de.index>=0&&(V.idx[de.index]=q),Q.offset=q)}}let j,X,W;if(O.acCompressedSize>0)switch(O.acCompression){case 0:j=new Uint16Array(O.totalAcUncompressedCount),St(l.array,g,T,O.acCompressedSize,j,O.totalAcUncompressedCount);break;case 1:const q=l.array.slice(T.value,T.value+O.totalAcUncompressedCount),Q=Sn(q);j=new Uint16Array(Q.buffer),T.value+=O.totalAcUncompressedCount;break}if(O.dcCompressedSize>0){const q={array:l.array,offset:T,size:O.dcCompressedSize};X=new Uint16Array(Ls(q).buffer),T.value+=O.dcCompressedSize}if(O.rleRawSize>0){const q=l.array.slice(T.value,T.value+O.rleCompressedSize),Q=Sn(q);W=Is(Q.buffer),T.value+=O.rleCompressedSize}let $=0;const ee=new Array(B.length);for(let q=0;q<ee.length;++q)ee[q]=new Array;for(let q=0;q<l.lines;++q)for(let Q=0;Q<B.length;++Q)ee[Q].push($),$+=B[Q].width*l.type*2;V.idx[0]!==void 0&&B[V.idx[0]]&&So(V,ee,B,j,X,M);for(let q=0;q<B.length;++q){const Q=B[q];if(!Q.decoded)switch(Q.compression){case 2:let oe=0,he=0;for(let ae=0;ae<l.lines;++ae){let de=ee[q][oe];for(let ne=0;ne<Q.width;++ne){for(let te=0;te<2*Q.type;++te)M[de++]=W[he+te*Q.width*Q.height];he++}oe++}break;case 1:_o(q,ee,B,j,X,M);break;default:throw new Error("THREE.EXRLoader: unsupported channel compression")}}return new DataView(M.buffer)}function kn(l,g){const T=new Uint8Array(l);let M=0;for(;T[g.value+M]!=0;)M+=1;const O=new TextDecoder().decode(T.slice(g.value,g.value+M));return g.value=g.value+M+1,O}function Co(l,g,T){const M=new TextDecoder().decode(new Uint8Array(l).slice(g.value,g.value+T));return g.value=g.value+T,M}function Po(l,g){const T=qe(l,g),M=Je(l,g);return[T,M]}function Io(l,g){const T=Je(l,g),M=Je(l,g);return[T,M]}function qe(l,g){const T=l.getInt32(g.value,!0);return g.value=g.value+4,T}function Je(l,g){const T=l.getUint32(g.value,!0);return g.value=g.value+4,T}function Hi(l,g){const T=l[g.value];return g.value=g.value+1,T}function vt(l,g){const T=l.getUint8(g.value);return g.value=g.value+1,T}const ke=function(l,g){const T=Number(l.getBigInt64(g.value,!0));return g.value+=8,T};function We(l,g){const T=l.getFloat32(g.value,!0);return g.value+=4,T}function Lo(l,g){return p.DataUtils.toHalfFloat(We(l,g))}function J(l){const g=(l&31744)>>10,T=l&1023;return(l>>15?-1:1)*(g?g===31?T?NaN:1/0:Math.pow(2,g-15)*(1+T/1024):6103515625e-14*(T/1024))}function hn(l,g){const T=l.getUint16(g.value,!0);return g.value+=2,T}function Oo(l,g){return J(hn(l,g))}function Do(l,g,T,M){const O=T.value,H=[];for(;T.value<O+M-1;){const R=kn(g,T),G=qe(l,T),B=vt(l,T);T.value+=3;const V=qe(l,T),j=qe(l,T);H.push({name:R,pixelType:G,pLinear:B,xSampling:V,ySampling:j})}return T.value+=1,H}function No(l,g){const T=We(l,g),M=We(l,g),O=We(l,g),H=We(l,g),R=We(l,g),G=We(l,g),B=We(l,g),V=We(l,g);return{redX:T,redY:M,greenX:O,greenY:H,blueX:R,blueY:G,whiteX:B,whiteY:V}}function ko(l,g){const T=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],M=vt(l,g);return T[M]}function Fo(l,g){const T=qe(l,g),M=qe(l,g),O=qe(l,g),H=qe(l,g);return{xMin:T,yMin:M,xMax:O,yMax:H}}function Bo(l,g){const T=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],M=vt(l,g);return T[M]}function zo(l,g){const T=["ENVMAP_LATLONG","ENVMAP_CUBE"],M=vt(l,g);return T[M]}function Uo(l,g){const T=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],M=["ROUND_DOWN","ROUND_UP"],O=Je(l,g),H=Je(l,g),R=vt(l,g);return{xSize:O,ySize:H,levelMode:T[R&15],roundingMode:M[R>>4]}}function Ho(l,g){const T=We(l,g),M=We(l,g);return[T,M]}function Vo(l,g){const T=We(l,g),M=We(l,g),O=We(l,g);return[T,M,O]}function Go(l,g,T,M,O){if(M==="string"||M==="stringvector"||M==="iccProfile")return Co(g,T,O);if(M==="chlist")return Do(l,g,T,O);if(M==="chromaticities")return No(l,T);if(M==="compression")return ko(l,T);if(M==="box2i")return Fo(l,T);if(M==="envmap")return zo(l,T);if(M==="tiledesc")return Uo(l,T);if(M==="lineOrder")return Bo(l,T);if(M==="float")return We(l,T);if(M==="v2f")return Ho(l,T);if(M==="v3f")return Vo(l,T);if(M==="int")return qe(l,T);if(M==="rational")return Po(l,T);if(M==="timecode")return Io(l,T);if(M==="preview"||M==="deepImageState"||M==="idmanifest")return T.value+=O,"skipped";T.value+=O}function jo(l,g){const T=Math.log2(l);return g=="ROUND_DOWN"?Math.floor(T):Math.ceil(T)}function Wo(l,g,T){let M=0;switch(l.levelMode){case"ONE_LEVEL":M=1;break;case"MIPMAP_LEVELS":M=jo(Math.max(g,T),l.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return M}function Vi(l,g,T,M){const O=new Array(l);for(let H=0;H<l;H++){const R=1<<H;let G=g/R|0;M=="ROUND_UP"&&G*R<g&&(G+=1);const B=Math.max(G,1);O[H]=(B+T-1)/T|0}return O}function Zo(){const l=this,g=l.offset,T={value:0};for(let M=0;M<l.tileCount;M++){const O=qe(l.viewer,g),H=qe(l.viewer,g);g.value+=8,l.size=Je(l.viewer,g);const R=O*l.blockWidth,G=H*l.blockHeight;l.columns=R+l.blockWidth>l.width?l.width-R:l.blockWidth,l.lines=G+l.blockHeight>l.height?l.height-G:l.blockHeight;const B=l.columns*l.totalBytes,j=l.size<l.lines*B?l.uncompress(l):Nn(l);g.value+=l.size;for(let X=0;X<l.lines;X++){const W=X*l.columns*l.totalBytes;for(let $=0;$<l.inputChannels.length;$++){const ee=Ze.channels[$].name,q=l.channelByteOffsets[ee]*l.columns,Q=l.decodeChannels[ee];if(Q===void 0)continue;T.value=W+q;const oe=(l.height-(1+G+X))*l.outLineWidth;for(let he=0;he<l.columns;he++){const ae=oe+(he+R)*l.outputChannels+Q;l.byteArray[ae]=l.getter(j,T)}}}}}function Ko(){const l=this,g=l.offset,T={value:0};for(let M=0;M<l.height/l.blockHeight;M++){const O=qe(l.viewer,g)-Ze.dataWindow.yMin;l.size=Je(l.viewer,g),l.lines=O+l.blockHeight>l.height?l.height-O:l.blockHeight;const H=l.columns*l.totalBytes,G=l.size<l.lines*H?l.uncompress(l):Nn(l);g.value+=l.size;for(let B=0;B<l.lines;B++){const V=O+B,j=B*H,X=(l.height-1-V)*l.outLineWidth;for(let W=0;W<l.inputChannels.length;W++){const $=Ze.channels[W].name,ee=l.channelByteOffsets[$]*l.columns,q=l.decodeChannels[$];if(q!==void 0){T.value=j+ee;for(let Q=0;Q<l.columns;Q++){const oe=X+Q*l.outputChannels+q;l.byteArray[oe]=l.getter(G,T)}}}}}}function Xo(){const l=this,g=l.chunkOffsets,T={value:0};for(let M=0;M<g.length;M++){const O={value:g[M]};O.value+=4;const H=qe(l.viewer,O)-Ze.dataWindow.yMin;l.size=Je(l.viewer,O),l.lines=H+l.blockHeight>l.height?l.height-H:l.blockHeight;const R=l.columns*l.totalBytes,G=l.size<l.lines*R,B=l.offset;l.offset=O;const V=G?l.uncompress(l):Nn(l);l.offset=B;for(let j=0;j<l.lines;j++){const X=H+j,W=j*R,$=(l.height-1-X)*l.outLineWidth;for(let ee=0;ee<l.inputChannels.length;ee++){const q=Ze.channels[ee].name,Q=l.channelByteOffsets[q]*l.columns,oe=l.decodeChannels[q];if(oe!==void 0){T.value=W+Q;for(let he=0;he<l.columns;he++){const ae=$+he*l.outputChannels+oe;l.byteArray[ae]=l.getter(V,T)}}}}}}function Gi(l,g,T,M){if(T===0)return null;const O=l.slice(g,g+T);switch(M){case"NO_COMPRESSION":return new DataView(O.buffer,O.byteOffset,O.byteLength);case"RLE_COMPRESSION":{const H=new Uint8Array(Is(O.buffer.slice(O.byteOffset,O.byteOffset+O.byteLength))),R=new Uint8Array(H.length);return On(H),Dn(H,R),new DataView(R.buffer)}case"ZIPS_COMPRESSION":{const H=Sn(O),R=new Uint8Array(H.length);return On(H),Dn(H,R),new DataView(R.buffer)}default:throw new Error("THREE.EXRLoader: "+M+" is unsupported for deep data")}}function Yo(){const l=this,g=l.chunkOffsets,T=l.width,M=l.height,O=l.deepChannels,H=Ze.compression,R=l.multiPart,G=l.decodeChannels,B=l.outputChannels,V=l.byteArray instanceof Uint16Array;let j=-1;for(let X=0;X<O.length;X++)if(O[X].name==="A"){j=X;break}for(let X=0;X<g.length;X++){const W={value:g[X]};R&&(W.value+=4);const $=qe(l.viewer,W)-Ze.dataWindow.yMin,ee=ke(l.viewer,W),q=ke(l.viewer,W);ke(l.viewer,W);const Q=Gi(l.array,W.value,ee,H);if(W.value+=ee,Q===null)continue;const oe=new Uint32Array(T);for(let ie=0;ie<T;ie++)oe[ie]=Q.getUint32(ie*4,!0);const he=oe[T-1];if(he===0){W.value+=q;continue}const ae=Gi(l.array,W.value,q,H),de=[];let ne=0;for(let ie=0;ie<O.length;ie++)de.push(ne),ne+=he*O[ie].bytesPerSample;const te=(M-1-$)*l.outLineWidth;for(let ie=0;ie<T;ie++){const Te=ie===0?0:oe[ie-1],ce=oe[ie]-Te;if(ce===0)continue;const ue=new Float32Array(B);let Ce=0;for(let _e=0;_e<ce;_e++){const mt=Te+_e,jt=1-Ce;if(jt<=0)break;let un=1;if(j>=0){const gt=O[j].bytesPerSample,kt=de[j]+mt*gt;un=gt===2?J(ae.getUint16(kt,!0)):ae.getFloat32(kt,!0)}for(let gt=0;gt<O.length;gt++){const kt=O[gt],Un=G[kt.name];if(Un===void 0)continue;const Hn=kt.bytesPerSample,Vn=de[gt]+mt*Hn,dn=Hn===2?J(ae.getUint16(Vn,!0)):ae.getFloat32(Vn,!0);ue[Un]+=dn*jt}Ce+=un*jt}G.A!==void 0&&(ue[G.A]=Ce);const et=te+ie*B;for(let _e=0;_e<B;_e++)l.byteArray[et+_e]=V?p.DataUtils.toHalfFloat(ue[_e]):ue[_e]}}}function ji(l,g,T){const M={};let O=!1;for(;;){const H=kn(g,T);if(H==="")break;O=!0;const R=kn(g,T),G=Je(l,T),B=Go(l,g,T,R,G);B===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${R}'.`):M[H]=B}return O?M:null}function qo(l,g,T){if(l.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");const M=l.getUint8(4),O=l.getUint8(5),H={singleTile:!!(O&2),longName:!!(O&4),deepFormat:!!(O&8),multiPart:!!(O&16)};T.value=8;const R=[];if(H.multiPart){for(;;){const G=ji(l,g,T);if(G===null)break;G.version=M,G.spec=H,R.push(G)}if(R.length===0)throw new Error("THREE.EXRLoader: No valid part headers found.")}else{const G=ji(l,g,T);G.version=M,G.spec=H,R.push(G)}return R}function $o(l,g,T,M,O,H){const R={size:0,viewer:g,array:T,offset:M,width:l.dataWindow.xMax-l.dataWindow.xMin+1,height:l.dataWindow.yMax-l.dataWindow.yMin+1,inputChannels:l.channels,channelByteOffsets:{},shouldExpand:!1,yCbCr:!1,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:p.LinearSRGBColorSpace};switch(l.compression){case"NO_COMPRESSION":R.blockHeight=1,R.uncompress=Nn;break;case"RLE_COMPRESSION":R.blockHeight=1,R.uncompress=Ao;break;case"ZIPS_COMPRESSION":R.blockHeight=1,R.uncompress=Ls;break;case"ZIP_COMPRESSION":R.blockHeight=16,R.uncompress=Ls;break;case"PIZ_COMPRESSION":R.blockHeight=32,R.uncompress=vo;break;case"PXR24_COMPRESSION":R.blockHeight=16,R.uncompress=Ro;break;case"B44_COMPRESSION":case"B44A_COMPRESSION":R.blockHeight=32,R.uncompress=Mo;break;case"DWAA_COMPRESSION":R.blockHeight=32,R.uncompress=Ui;break;case"DWAB_COMPRESSION":R.blockHeight=256,R.uncompress=Ui;break;default:throw new Error("THREE.EXRLoader: "+l.compression+" is unsupported")}const G={};for(const W of l.channels)switch(W.name){case"BY":case"RY":case"Y":case"R":case"G":case"B":case"A":G[W.name]=!0,R.type=W.pixelType}let B=!1,V=!1;if(G.Y&&G.RY&&G.BY)R.outputChannels=4,R.yCbCr=!0;else if(G.R&&G.G&&G.B)R.outputChannels=4;else if(G.Y)R.outputChannels=1;else throw new Error("THREE.EXRLoader: file contains unsupported data channels.");switch(R.outputChannels){case 4:H==p.RGBAFormat?(B=!G.A,R.format=p.RGBAFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=4,R.decodeChannels={R:0,G:1,B:2,A:3}):H==p.RGFormat?(R.format=p.RGFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=2,R.decodeChannels={R:0,G:1}):H==p.RedFormat?(R.format=p.RedFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=1,R.decodeChannels={R:0}):V=!0;break;case 1:H==p.RGBAFormat?(B=!0,R.format=p.RGBAFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=4,R.shouldExpand=!0,R.decodeChannels={Y:0}):H==p.RGFormat?(R.format=p.RGFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=2,R.shouldExpand=!0,R.decodeChannels={Y:0}):H==p.RedFormat?(R.format=p.RedFormat,R.colorSpace=p.LinearSRGBColorSpace,R.outputChannels=1,R.decodeChannels={Y:0}):V=!0;break;default:V=!0}if(V)throw new Error("THREE.EXRLoader: invalid output format for specified file.");if(R.yCbCr&&(R.format=p.RGBAFormat,R.outputChannels=4,R.decodeChannels={Y:0,RY:1,BY:2},B=!0),R.type==1)switch(O){case p.FloatType:R.getter=Oo;break;case p.HalfFloatType:R.getter=hn;break}else if(R.type==2)switch(O){case p.FloatType:R.getter=We;break;case p.HalfFloatType:R.getter=Lo}else throw new Error("THREE.EXRLoader: unsupported pixelType "+R.type+" for "+l.compression+".");R.columns=R.width;const j=R.width*R.height*R.outputChannels;switch(O){case p.FloatType:R.byteArray=new Float32Array(j),B&&R.byteArray.fill(1,0,j);break;case p.HalfFloatType:R.byteArray=new Uint16Array(j),B&&R.byteArray.fill(15360,0,j);break;default:console.error("THREE.EXRLoader: unsupported type: ",O);break}let X=0;for(const W of l.channels)R.decodeChannels[W.name]!==void 0&&(R.channelByteOffsets[W.name]=X),X+=W.pixelType*2;if(R.totalBytes=X,R.outLineWidth=R.width*R.outputChannels,l.spec.deepFormat){R.deepChannels=[];let W=0;for(const $ of l.channels){const ee=$.pixelType===0?4:$.pixelType*2;R.deepChannels.push({name:$.name,pixelType:$.pixelType,bytesPerSample:ee}),W+=ee}R.deepBytesPerSample=W,R.chunkOffsets=l._chunkOffsets,R.multiPart=l.spec.multiPart,R.decode=Yo.bind(R)}else if(l.spec.singleTile){R.blockHeight=l.tiles.ySize,R.blockWidth=l.tiles.xSize;const W=Wo(l.tiles,R.width,R.height),$=Vi(W,R.width,l.tiles.xSize,l.tiles.roundingMode),ee=Vi(W,R.height,l.tiles.ySize,l.tiles.roundingMode);R.tileCount=$[0]*ee[0];for(let q=0;q<W;q++)for(let Q=0;Q<ee[q];Q++)for(let oe=0;oe<$[q];oe++)ke(g,M);R.decode=Zo.bind(R)}else if(l.spec.multiPart)R.blockWidth=R.width,R.chunkOffsets=l._chunkOffsets,R.decode=Xo.bind(R);else{R.blockWidth=R.width;const W=Math.ceil(R.height/R.blockHeight);for(let $=0;$<W;$++)ke(g,M);R.decode=Ko.bind(R)}return R}const Fn={value:0},Bn=new DataView(e),Qo=new Uint8Array(e),zn=qo(Bn,e,Fn),Wi=Math.max(0,Math.min(this.part,zn.length-1)),Ze=zn[Wi];if(Ze.spec.multiPart||Ze.spec.deepFormat)for(let l=0;l<zn.length;l++){const g=zn[l].chunkCount;if(l===Wi){Ze._chunkOffsets=[];for(let T=0;T<g;T++)Ze._chunkOffsets.push(ke(Bn,Fn))}else for(let T=0;T<g;T++)ke(Bn,Fn)}const tt=$o(Ze,Bn,Qo,Fn,this.type,this.outputFormat);if(tt.decode(),tt.shouldExpand){const l=tt.byteArray;if(this.outputFormat==p.RGBAFormat)for(let g=0;g<l.length;g+=4)l[g+2]=l[g+1]=l[g];else if(this.outputFormat==p.RGFormat)for(let g=0;g<l.length;g+=2)l[g+1]=l[g]}if(tt.yCbCr){const l=tt.byteArray,g=tt.width*tt.height;if(this.type===p.HalfFloatType)for(let T=0;T<g;T++){const M=T*4,O=J(l[M]),H=J(l[M+1]),R=J(l[M+2]),G=(1+H)*O,B=(1+R)*O,V=(O-G*.2126-B*.0722)/.7152;l[M]=p.DataUtils.toHalfFloat(Math.max(0,G)),l[M+1]=p.DataUtils.toHalfFloat(Math.max(0,V)),l[M+2]=p.DataUtils.toHalfFloat(Math.max(0,B))}else for(let T=0;T<g;T++){const M=T*4,O=l[M],H=l[M+1],R=l[M+2],G=(1+H)*O,B=(1+R)*O;l[M]=Math.max(0,G),l[M+1]=Math.max(0,(O-G*.2126-B*.0722)/.7152),l[M+2]=Math.max(0,B)}}return{header:Ze,width:tt.width,height:tt.height,data:tt.byteArray,format:tt.format,colorSpace:tt.colorSpace,type:this.type,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!1}}setDataType(e){return this.type=e,this}setOutputFormat(e){return this.outputFormat=e,this}setPart(e){return this.part=e,this}}class fh extends p.DataTextureLoader{constructor(e){super(e),this.type=p.HalfFloatType}parse(e){const r=function(C,D){switch(C){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(D||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(D||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(D||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(D||""))}},u=function(C,D,P){D=D||1024;let k=C.pos,U=-1,z=0,Y="",re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(k,k+128)));for(;0>(U=re.indexOf(`
|
|
26
|
-
`))&&z<D&&k<C.byteLength;)Y+=re,z+=re.length,k+=128,re=String.fromCharCode.apply(null,new Uint16Array(C.subarray(k,k+128)));return-1<U?(C.pos+=z+U+1,Y+re.slice(0,U)):!1},f=function(C){const D=/^#\?(\S+)/,P=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,F=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,k=/^\s*FORMAT=(\S+)\s*$/,U=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,z={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let Y,re;for((C.pos>=C.byteLength||!(Y=u(C)))&&r(1,"no header found"),(re=Y.match(D))||r(3,"bad initial token"),z.valid|=1,z.programtype=re[1],z.string+=Y+`
|
|
27
|
-
`;Y=u(C),Y!==!1;){if(z.string+=Y+`
|
|
28
|
-
`,Y.charAt(0)==="#"){z.comments+=Y+`
|
|
29
|
-
`;continue}if((re=Y.match(P))&&(z.gamma=parseFloat(re[1])),(re=Y.match(F))&&(z.exposure=parseFloat(re[1])),(re=Y.match(k))&&(z.valid|=2,z.format=re[1]),(re=Y.match(U))&&(z.valid|=4,z.height=parseInt(re[1],10),z.width=parseInt(re[2],10)),z.valid&2&&z.valid&4)break}return z.valid&2||r(3,"missing format specifier"),z.valid&4||r(3,"missing image size specifier"),z},m=function(C,D,P){const F=D;if(F<8||F>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);F!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const k=new Uint8Array(4*D*P);k.length||r(4,"unable to allocate buffer space");let U=0,z=0;const Y=4*F,re=new Uint8Array(4),Ne=new Uint8Array(Y);let at=P;for(;at>0&&z<C.byteLength;){z+4>C.byteLength&&r(1),re[0]=C[z++],re[1]=C[z++],re[2]=C[z++],re[3]=C[z++],(re[0]!=2||re[1]!=2||(re[2]<<8|re[3])!=F)&&r(3,"bad rgbe scanline format");let Me=0,ze;for(;Me<Y&&z<C.byteLength;){ze=C[z++];const ve=ze>128;if(ve&&(ze-=128),(ze===0||Me+ze>Y)&&r(3,"bad scanline data"),ve){const Ee=C[z++];for(let pt=0;pt<ze;pt++)Ne[Me++]=Ee}else Ne.set(C.subarray(z,z+ze),Me),Me+=ze,z+=ze}const Ge=F;for(let ve=0;ve<Ge;ve++){let Ee=0;k[U]=Ne[ve+Ee],Ee+=F,k[U+1]=Ne[ve+Ee],Ee+=F,k[U+2]=Ne[ve+Ee],Ee+=F,k[U+3]=Ne[ve+Ee],U+=4}at--}return k},E=function(C,D,P,F){const k=C[D+3],U=Math.pow(2,k-128)/255;P[F+0]=C[D+0]*U,P[F+1]=C[D+1]*U,P[F+2]=C[D+2]*U,P[F+3]=1},b=function(C,D,P,F){const k=C[D+3],U=Math.pow(2,k-128)/255;P[F+0]=p.DataUtils.toHalfFloat(Math.min(C[D+0]*U,65504)),P[F+1]=p.DataUtils.toHalfFloat(Math.min(C[D+1]*U,65504)),P[F+2]=p.DataUtils.toHalfFloat(Math.min(C[D+2]*U,65504)),P[F+3]=p.DataUtils.toHalfFloat(1)},w=new Uint8Array(e);w.pos=0;const A=f(w),S=A.width,_=A.height,x=m(w.subarray(w.pos),S,_);let v,L,I;switch(this.type){case p.FloatType:I=x.length/4;const C=new Float32Array(I*4);for(let P=0;P<I;P++)E(x,P*4,C,P*4);v=C,L=p.FloatType;break;case p.HalfFloatType:I=x.length/4;const D=new Uint16Array(I*4);for(let P=0;P<I;P++)b(x,P*4,D,P*4);v=D,L=p.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:S,height:_,data:v,header:A.string,gamma:A.gamma,exposure:A.exposure,type:L,colorSpace:p.LinearSRGBColorSpace,minFilter:p.LinearFilter,magFilter:p.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}class ph extends fh{constructor(e){console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."),super(e)}}class mh extends p.Scene{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;const e=new p.BoxGeometry;e.deleteAttribute("uv");const t=new p.MeshStandardMaterial({side:p.BackSide}),n=new p.MeshStandardMaterial,s=new p.PointLight(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const o=new p.Mesh(e,t);o.position.set(-.757,13.219,.717),o.scale.set(31.713,28.305,28.591),this.add(o);const r=new p.InstancedMesh(e,n,6),a=new p.Object3D;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),r.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(),r.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(),r.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(),r.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(),r.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(),r.setMatrixAt(5,a.matrix),this.add(r);const c=new p.Mesh(e,tn(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const h=new p.Mesh(e,tn(50));h.position.set(-16.109,18.021,-8.207),h.scale.set(.1,2.425,2.751),this.add(h);const d=new p.Mesh(e,tn(17));d.position.set(14.904,12.198,-1.832),d.scale.set(.15,4.265,6.331),this.add(d);const u=new p.Mesh(e,tn(43));u.position.set(-.462,8.89,14.52),u.scale.set(4.38,5.441,.088),this.add(u);const f=new p.Mesh(e,tn(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,.1),this.add(f);const m=new p.Mesh(e,tn(100));m.position.set(0,20,0),m.scale.set(1,.1,1),this.add(m)}dispose(){const e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function tn(i){return new p.MeshLambertMaterial({color:0,emissive:16777215,emissiveIntensity:i})}const gh=.42,yh=1.15,Eh=.7,Th=1;function wh(i){i.traverse(e=>{const t=e;if(t.isPointLight){t.intensity*=Eh;return}const n=e;if(!n.isMesh)return;const s=Array.isArray(n.material)?n.material:[n.material];for(const o of s){if(!o)continue;const r=o;(r.emissiveIntensity??0)>Th?r.emissiveIntensity*=yh:r.color&&r.color.multiplyScalar(gh)}})}class Sh{constructor(){this.pmremGenerator=null,this.threeRenderer=null,this.loadedTextures=new Map,this.renderTargets=[],this.studioPmremTexture=null,this.studioCubeTarget=null,this.disposed=!1}async initialize(e){var t;try{const n=e.renderer;let s=n.renderer||((t=n.getThreeRenderer)==null?void 0:t.call(n));if(!s&&n.getDomElement){const o=n.getDomElement();if(o&&"parentElement"in o&&o.parentElement){const r=o.parentElement.renderer;r instanceof y.WebGLRenderer&&(s=r)}}return s?(this.threeRenderer=s,this.pmremGenerator=new y.PMREMGenerator(s),this.pmremGenerator.compileEquirectangularShader(),N.ok(void 0)):N.err(new Z("Could not access Three.js renderer",K.INITIALIZATION_FAILED))}catch(n){return N.err(new Z("Failed to initialize environment service",K.INITIALIZATION_FAILED,{originalError:n}))}}async loadEnvironmentMap(e){var t;try{const n=this.loadedTextures.get(e);if(n)return N.ok(new _n(n));const s=(t=e.split(".").pop())==null?void 0:t.toLowerCase();let o;switch(s){case"hdr":o=new ph;break;case"exr":o=new dh;break;case"jpg":case"jpeg":case"png":o=new y.TextureLoader;break;default:return N.err(new Z(`Unsupported environment map format: ${s}`,K.UNSUPPORTED_FORMAT,{url:e,extension:s}))}const r=await new Promise((a,c)=>{o.load(e,h=>{a(h)},void 0,h=>c(h))});if(this.disposed)return r.dispose(),N.err(new Z("Environment service was disposed during the load",K.INVALID_STATE,{url:e}));if(this.pmremGenerator){r.mapping=y.EquirectangularReflectionMapping;const a=this.pmremGenerator.fromEquirectangular(r);this.renderTargets.push(a);const c=a.texture;return this.loadedTextures.set(e,c),this.loadedTextures.set(e+"_original",r),N.ok(new _n(c))}return this.loadedTextures.set(e,r),N.ok(new _n(r))}catch(n){return N.err(new Z("Failed to load environment map",K.TEXTURE_LOAD_FAILED,{url:e,originalError:n}))}}applyToScene(e,t,n){try{const s=ot(e);if(!s)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const o=Pl(t);if(!o)return N.err(new Z("Texture must be ThreeTextureAdapter",K.INVALID_PARAMETER));if(s.environment=o,n&&(n.backgroundBlurriness!==void 0&&(s.backgroundBlurriness=n.backgroundBlurriness),n.backgroundIntensity!==void 0&&(s.backgroundIntensity=n.backgroundIntensity),n.environmentIntensity!==void 0&&(s.environmentIntensity=n.environmentIntensity)),o.mapping===y.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,h])=>c.endsWith("_original")&&h.mapping===y.EquirectangularReflectionMapping);a?s.__originalEnvironmentTexture=a[1]:o===this.studioPmremTexture&&this.studioCubeTarget&&(s.__originalEnvironmentTexture=this.studioCubeTarget.texture)}else o.mapping===y.EquirectangularReflectionMapping&&(s.__originalEnvironmentTexture=o);if((n==null?void 0:n.setBackground)??!0)if(o.mapping===y.EquirectangularReflectionMapping)s.background=o;else if(o.mapping===y.CubeUVReflectionMapping){const a=Array.from(this.loadedTextures.entries()).find(([c,h])=>c.endsWith("_original")&&h.mapping===y.EquirectangularReflectionMapping);a?s.background=a[1]:s.background=o}else s.background=o;return N.ok(void 0)}catch(s){return N.err(new Z("Failed to apply environment to scene",K.SCENE_OPERATION_FAILED,{originalError:s}))}}getOriginalEnvironmentTexture(e){const t=this.loadedTextures.get(e+"_original");return t?new _n(t):null}async setBackgroundImage(e,t){try{const n=ot(e);if(!n)return N.err(new Z("Scene must be ThreeSceneAdapter",K.INVALID_PARAMETER));const s=await this.loadBackgroundTexture(t);s.colorSpace=y.SRGBColorSpace,s.needsUpdate=!0;const o=n.background;return n.background=s,o instanceof y.Texture&&o!==n.environment&&o.dispose(),N.ok(void 0)}catch(n){return N.err(new Z("Failed to set background image",K.TEXTURE_LOAD_FAILED,{originalError:n}))}}loadBackgroundTexture(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement){const s=new y.Texture(e);return s.needsUpdate=!0,Promise.resolve(s)}const t=typeof File<"u"&&e instanceof File?URL.createObjectURL(e):null,n=t??e;return new Promise((s,o)=>{new y.TextureLoader().load(n,r=>{t&&URL.revokeObjectURL(t),s(r)},void 0,r=>{t&&URL.revokeObjectURL(t),o(r)})})}createStudioEnvironment(e={}){try{if(!this.pmremGenerator)return N.err(new Z("Environment service not initialized",K.INITIALIZATION_FAILED));const t=new mh;wh(t);const n=this.pmremGenerator.fromScene(t);this.renderTargets.push(n);const s=n.texture;return this.captureStudioCubeOriginal(t,s),t.dispose(),N.ok(new _n(s))}catch(t){return N.err(new Z("Failed to create studio environment",K.TEXTURE_LOAD_FAILED,{originalError:t}))}}captureStudioCubeOriginal(e,t){var n;if(this.threeRenderer)try{const s=new y.WebGLCubeRenderTarget(256,{type:y.HalfFloatType}),o=new y.CubeCamera(.1,100,s),r=this.threeRenderer.toneMapping;this.threeRenderer.toneMapping=y.NoToneMapping;try{o.update(this.threeRenderer,e)}finally{this.threeRenderer.toneMapping=r}(n=this.studioCubeTarget)==null||n.dispose(),this.studioCubeTarget=s,this.studioPmremTexture=t}catch(s){console.warn("Failed to capture the studio environment for path tracing:",s)}}dispose(){var e;this.disposed=!0,this.loadedTextures.forEach(t=>t.dispose()),this.loadedTextures.clear(),this.renderTargets.forEach(t=>t.dispose()),this.renderTargets=[],(e=this.studioCubeTarget)==null||e.dispose(),this.studioCubeTarget=null,this.studioPmremTexture=null,this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null),this.threeRenderer=null}}class _n{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 _h{constructor(e){this.object=e,this.boundingBox=new y.Box3().setFromObject(this.object)}alignToFloor(){const e=this.calculateFloorOffset();this.applyOffset(e)}calculateFloorOffset(){const e=this.boundingBox.min.y,t=this.boundingBox.max.y-e,n=new y.Vector3;return t>0?n.y=-e:n.y=0,n}applyOffset(e){this.object.position.add(e)}}class bh{alignToFloor(e){try{let t=null;return"getThreeObject"in e&&typeof e.getThreeObject=="function"?t=e.getThreeObject():e instanceof y.Object3D&&(t=e),t?(new _h(t).alignToFloor(),N.ok(void 0)):N.err(new Z("Could not get Three.js object for floor alignment",K.INVALID_PARAMETER))}catch(t){return N.err(new Z("Failed to align object to floor",K.OPERATION_FAILED,{originalError:t}))}}}const Rr={touch:10,default:5};class xh{constructor(){this.raycaster=new y.Raycaster,this.activePointers=new Set,this.options=null,this.pending=null,this.detach=null}initialize(e){this.dispose(),this.options=e;const{canvas:t}=e,n=r=>{this.activePointers.add(r.pointerId);try{t.setPointerCapture(r.pointerId)}catch{}if(this.activePointers.size>1||r.button!==0){this.pending=null;return}this.pending={pointerId:r.pointerId,x:r.clientX,y:r.clientY,threshold:r.pointerType==="touch"?Rr.touch:Rr.default}},s=r=>{this.activePointers.delete(r.pointerId);const a=this.pending;!a||a.pointerId!==r.pointerId||(this.pending=null,Math.hypot(r.clientX-a.x,r.clientY-a.y)>a.threshold)||this.pick(r.clientX,r.clientY)},o=r=>{this.activePointers.delete(r.pointerId),this.pending=null};t.addEventListener("pointerdown",n),t.addEventListener("pointerup",s),t.addEventListener("pointercancel",o),this.detach=()=>{t.removeEventListener("pointerdown",n),t.removeEventListener("pointerup",s),t.removeEventListener("pointercancel",o)}}pick(e,t){if(!this.options)return;const{canvas:n,camera:s,getPickRoot:o,onPick:r}=this.options,a=o(),c=wt(a),h=Pn(s);if(!c||!h){r(null);return}const d=n.getBoundingClientRect();if(d.width===0||d.height===0){r(null);return}const u=new y.Vector2((e-d.left)/d.width*2-1,-((t-d.top)/d.height)*2+1);(this.options.bvh??!0)&&jr(c),this.raycaster.setFromCamera(u,h),this.raycaster.firstHitOnly=!0;const f=this.raycaster.intersectObject(c,!0)[0];if(!f){r(null);return}r({object:new Ke(f.object),point:{x:f.point.x,y:f.point.y,z:f.point.z}})}dispose(){var e;(e=this.detach)==null||e.call(this),this.detach=null,this.options=null,this.pending=null,this.activePointers.clear()}}const Ah=.001,Mr={visible:!1};class vh{constructor(e){this.sources=e,this.anchor=new y.Vector3,this.projected=new y.Vector3,this.cameraPosition=new y.Vector3,this.toAnchor=new y.Vector3,this.raycaster=new y.Raycaster,this.lastCameraMatrix=new y.Matrix4,this.lastWidth=-1,this.lastHeight=-1,this.hasProjected=!1}invalidate(){this.hasProjected=!1}project(e,t){const n=Pn(this.sources.camera),s=this.sources.getCanvas();if(!n||!s)return null;const o=s.clientWidth||s.width,r=s.clientHeight||s.height;return this.hasProjected&&o===this.lastWidth&&r===this.lastHeight&&this.lastCameraMatrix.equals(n.matrixWorld)?null:(this.lastCameraMatrix.copy(n.matrixWorld),this.lastWidth=o,this.lastHeight=r,this.hasProjected=!0,this.anchor.set(e.x,e.y,e.z),n.getWorldPosition(this.cameraPosition),this.projected.copy(this.anchor).applyMatrix4(n.matrixWorldInverse),this.projected.z>=0||t&&this.isOccluded(n)?Mr:(this.projected.copy(this.anchor).project(n),{visible:!0,left:(this.projected.x+1)/2*o,top:(1-this.projected.y)/2*r}))}isOccluded(e){const t=wt(this.sources.getModel());if(!t)return!1;this.toAnchor.copy(this.anchor).sub(this.cameraPosition);const n=this.toAnchor.length();this.raycaster.set(this.cameraPosition,this.toAnchor.normalize()),this.raycaster.camera=e,this.raycaster.firstHitOnly=!0;const s=this.raycaster.intersectObject(t,!0)[0];return!!(s&&s.distance<n-Ah)}}class Rh{createProjector(e){return new vh(e)}}class Mh{constructor(){this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1,this.speed=1}attach(e){this.detach();const t=wt(e);if(!t)return;const n=Ch(t);n&&(this.clips=n.animations,this.mixer=new y.AnimationMixer(n),this.mixer.timeScale=this.speed)}getClipNames(){return this.clips.map(e=>e.name)}play(e){if(e!==void 0){if(this.clips.length===0)return N.err(new Z(`Cannot play animation clip '${e}': no animation clips are attached`,K.INVALID_STATE));if(!this.clips.some(s=>s.name===e)){const s=this.clips.map(o=>o.name);return N.err(new Z(`Unknown animation clip '${e}'. Available clips: ${s.join(", ")}`,K.INVALID_PARAMETER))}}if(!this.mixer)return N.ok(void 0);if(!this.playing&&this.activeActions.length>0&&e===void 0)return this.playing=!0,N.ok(void 0);const t=e?this.clips.filter(s=>s.name===e):this.clips;if(t.length===0)return N.ok(void 0);const n=this.mixer;return n.stopAllAction(),this.activeActions=t.map(s=>{const o=n.clipAction(s);return o.play(),o}),this.playing=!0,N.ok(void 0)}pause(){this.playing=!1}isPlaying(){return this.playing}setSpeed(e){this.speed=e,this.mixer&&(this.mixer.timeScale=e)}update(e){this.playing&&this.mixer&&this.mixer.update(e)}detach(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot())),this.mixer=null,this.clips=[],this.activeActions=[],this.playing=!1}}function Ch(i){let e=null;return i.traverse(t=>{var n;!e&&(((n=t.animations)==null?void 0:n.length)??0)>0&&(e=t)}),e}var Mn=(i=>(i.MapControls="MapControls",i.OrbitControls="OrbitControls",i))(Mn||{});class Ph{static createViewer(e,t){var A;Dr(t.units);const n=new Mc(e),s=new gi,o=this.createCamera(t),r=this.createControls(o.getThreeCamera(),e,t),a=new Ih().createDefaultLoader({renderer:n.getThreeRenderer()??void 0,bvh:(A=t.selection)==null?void 0:A.bvh,...t.loaders}),c=new Yl,h=new Sh,d=new ql,u=new bh,f=new xh,m=new Rh,E=new Mh,b=Es.convertRendererOptions(t.renderer||{});b.preserveDrawingBuffer=!0;const w={renderer:n,scene:s,camera:o,controls:r,modelLoader:a,options:t,rendererOptions:b,sceneSetupService:c,environmentService:h,pathTracingService:d,floorAlignmentService:u,selectionService:f,anchorProjectionService:m,animationService:E};return new gs(w)}static createCamera(e){const n=e.camera||{},s=n.fov||n.cameraFov||30,o=n.near||n.cameraNear||.1,r=n.far||n.cameraFar||1e5,a=n.position||n.cameraPosition,c=n.target||n.cameraTarget,h=Ci.create(s,1,o,r);return a&&h.position.set(a[0],a[1],a[2]),c&&h.lookAt({x:c[0],y:c[1],z:c[2],set:()=>{},copy:()=>{},add:()=>{},multiply:()=>{},normalize:()=>{},length:()=>0}),h}static createControls(e,t,n){const s=n.controls||{},o=s.type||Mn.OrbitControls;let r;o===Mn.MapControls?r=new Cl(e,t):r=new Ml(e,t),r.enabled=s.enabled??!0,r.enableDamping=s.enableDamping??!0,r.dampingFactor=s.dampingFactor??.25,r.enableZoom=s.enableZoom??!0,r.enableRotate=s.enableRotate??!0,r.enablePan=s.enablePan??!0,r.autoRotate=s.autoRotate??!1,s.autoRotateSpeed!==void 0&&(r.autoRotateSpeed=s.autoRotateSpeed),s.minDistance!==void 0&&(r.minDistance=s.minDistance),s.maxDistance!==void 0&&(r.maxDistance=s.maxDistance),s.minPolarAngle!==void 0&&(r.minPolarAngle=s.minPolarAngle),s.maxPolarAngle!==void 0&&(r.maxPolarAngle=s.maxPolarAngle);const c=n.camera||{},h=c.target||c.cameraTarget;return h&&r.target&&(r.target.set(h[0],h[1],h[2]),r.update()),r}}class Ih extends br{createDefaultLoader(e={}){return br.createLoader("model.glb",e)}}const Lh=["toneMappingExposure","bloom","vignette","filmGrain","colorGrade"],Oh=["environmentIntensity"],Dh=["autoRotate","autoRotateSpeed"],Nh=["enabled"];function co(i){var t,n,s,o,r,a,c,h,d,u,f,m,E,b,w;const e={backgroundColor:i.backgroundColor,backgroundColorEdge:i.backgroundColorEdge};return e.renderer={bloom:((t=i.renderer)==null?void 0:t.bloom)??!1,vignette:((n=i.renderer)==null?void 0:n.vignette)??!1,filmGrain:((s=i.renderer)==null?void 0:s.filmGrain)??!1,colorGrade:((o=i.renderer)==null?void 0:o.colorGrade)??!1},((r=i.renderer)==null?void 0:r.toneMappingExposure)!==void 0&&(e.renderer.toneMappingExposure=i.renderer.toneMappingExposure),((a=i.environment)==null?void 0:a.environmentIntensity)!==void 0&&(e.environment={environmentIntensity:i.environment.environmentIntensity}),(((c=i.controls)==null?void 0:c.autoRotate)!==void 0||((h=i.controls)==null?void 0:h.autoRotateSpeed)!==void 0)&&(e.controls={autoRotate:(d=i.controls)==null?void 0:d.autoRotate,autoRotateSpeed:(u=i.controls)==null?void 0:u.autoRotateSpeed}),(((f=i.animations)==null?void 0:f.autoplay)!==void 0||((m=i.animations)==null?void 0:m.speed)!==void 0)&&(e.animations={autoplay:(E=i.animations)==null?void 0:E.autoplay,speed:(b=i.animations)==null?void 0:b.speed}),((w=i.pathTracing)==null?void 0:w.enabled)!==void 0&&(e.pathTracing={enabled:i.pathTracing.enabled}),e}const ws={staticScene:!1,backgroundColor:"#f0f0f7",replaceWithScreenshotOnComplete:!1,units:"meters",floorAlignment:!0,pathTracing:{enabled:!1,maxSamples:1024,bounces:16,transmissiveBounces:4,renderScale:.8,lowResScale:.25,dynamicLowRes:!0},camera:{position:[60,60,60],target:[0,0,0],fov:30,near:.1,far:1e5,autoFitToObject:!0},environment:{backgroundIntensity:1,environmentIntensity:.5},lighting:{ambientLight:{color:"#4a4a4a",intensity:.32},hemisphereLight:{skyColor:"#fff6ec",groundColor:"#3c3630",intensity:.3},directionalLight:{color:"#fff8f2",intensity:2.4,position:[40,90,40],castShadow:!0,shadow:{mapSize:{width:4096,height:4096},camera:{near:.5,far:200,left:-50,right:50,top:50,bottom:-50},bias:-1e-4,radius:14}},fillLight:{color:"#eef2ff",intensity:.6,position:[-55,28,34]},rimLight:{color:"#f2f6ff",intensity:2.6,position:[18,52,-72]}},renderer:{antialias:!0,alpha:!1,shadowMapEnabled:!0,pixelRatio:typeof window<"u"?window.devicePixelRatio:1,shadowMapType:1,toneMapping:7,toneMappingExposure:1.15},controls:{type:Mn.OrbitControls,enabled:!0,enableDamping:!0,dampingFactor:.25,enableZoom:!0,enableRotate:!0,enablePan:!0,maxPolarAngle:Math.PI/2},helpers:{grid:{type:"shadow_floor",size:20,divisions:20,colorGrid:"#a8a8a2",opacity:.5,styleOptions:{tileSize:.1173,metalness:0,roughness:.9,transmission:0}},axes:!1,stats:!1,gizmo:!1,studioEnvironment:!0,darkStudioMode:!1}},Oi={studio:{backgroundColor:"#f0f0f7",renderer:{toneMappingExposure:1.15},environment:{environmentIntensity:.5}},product:{backgroundColor:"#ffffff",renderer:{toneMappingExposure:1.2},environment:{environmentIntensity:.55}},neutral:{backgroundColor:"#d9d9de",renderer:{toneMappingExposure:1.1},environment:{environmentIntensity:.45}},dark:{backgroundColor:"#242430",backgroundColorEdge:"#050507",renderer:{toneMappingExposure:1.3},environment:{environmentIntensity:.42}},outdoor:{backgroundColor:"#bcd4e6",renderer:{toneMappingExposure:1.2},environment:{environmentIntensity:.6}}};function lo(i){return i?Oi[i]:{}}function bi(i,e){return on(on(i,lo(e.preset)),e)}const ls=(i,...e)=>{if(!i)return;const t={...i};for(const n of e)delete t[n];return Object.keys(t).length>0?t:void 0};function kh(i){const e=se.useMemo(()=>{var s;return JSON.stringify({pathTracing:ls(i.pathTracing,...Nh),staticScene:i.staticScene,renderer:ls(i.renderer,...Lh),camera:i.camera,controls:ls(i.controls,...Dh),environment:ls(i.environment,...Oh),lighting:i.lighting,helpers:i.helpers,rendering:i.rendering,replaceWithScreenshotOnComplete:i.replaceWithScreenshotOnComplete,loaders:i.loaders,units:i.units??"meters",selectionBvh:((s=i.selection)==null?void 0:s.bvh)!==!1})},[i.pathTracing,i.staticScene,i.renderer,i.camera,i.controls,i.environment,i.lighting,i.helpers,i.rendering,i.replaceWithScreenshotOnComplete,i.loaders,i.units,i.selection]),t=se.useMemo(()=>{const s=bi(ws,i);return JSON.stringify(co(s))},[i.preset,i.backgroundColor,i.backgroundColorEdge,i.renderer,i.environment,i.controls,i.animations,i.pathTracing]);return{options:se.useMemo(()=>i,[e,t]),structuralKey:e,runtimeKey:t}}const Fh="200px";function Bh(i,e){const[t,n]=se.useState(!e);return se.useEffect(()=>{if(t)return;if(!e){n(!0);return}const s=i.current;if(!s||typeof IntersectionObserver>"u"){n(!0);return}const o=new IntersectionObserver(r=>{r.some(a=>a.isIntersecting)&&n(!0)},{rootMargin:Fh});return o.observe(s),()=>o.disconnect()},[i,e,t]),t}function zh(i,e){const t=se.useRef(null),n=se.useRef({width:0,height:0}),[s,o]=se.useState(!1),[r,a]=se.useState(null),{options:c,structuralKey:h,runtimeKey:d}=kh(e),u=Bh(i,(e.loading??"eager")==="lazy");return se.useEffect(()=>{if(!u||!i.current||t.current)return;a(null);const f=bi(ws,c);let m;try{m=Ph.createViewer(i.current,f)}catch(b){console.error("Failed to create viewer:",b),a(b instanceof Error?b:new Error(String(b)));return}t.current=m,n.current={width:0,height:0};let E=!1;return m.initialize().then(b=>{E||(b.ok?o(!0):(console.error("Failed to initialize viewer:",b.error),a(b.error)))}),()=>{E=!0,m.dispose(),t.current=null,o(!1)}},[i,h,u]),se.useEffect(()=>{if(!t.current||!s)return;const f=bi(ws,c);t.current.updateOptions(co(f))},[d,s]),se.useEffect(()=>{if(!t.current||!i.current)return;let f=null;const m=w=>{if(i.current&&t.current){const A=i.current.parentElement||i.current;let{clientWidth:S,clientHeight:_}=A;if(w&&w[0]){const{width:x,height:v}=w[0].contentRect;S=Math.floor(x),_=Math.floor(v)}if(n.current.width===S&&n.current.height===_)return;f!==null&&cancelAnimationFrame(f),f=requestAnimationFrame(()=>{t.current&&i.current&&(t.current.resize(S,_),n.current={width:S,height:_})})}};m();const E=()=>m();window.addEventListener("resize",E);let b=null;return typeof ResizeObserver<"u"&&i.current.parentElement&&(b=new ResizeObserver(m),b.observe(i.current.parentElement)),()=>{window.removeEventListener("resize",E),b==null||b.disconnect(),f!==null&&cancelAnimationFrame(f)}},[s,i,h]),{viewer:t.current,isInitialized:s,initError:r}}function ho(i,e){const t=se.useRef(e);t.current=e,se.useEffect(()=>{if(!i)return;const n=i.getEvents(),s=[],o=r=>{const a=c=>{var h,d;(d=(h=t.current)[r])==null||d.call(h,c)};return n.on(r,a),()=>n.off(r,a)};return Object.keys(e).forEach(r=>{e[r]&&s.push(o(r))}),()=>{s.forEach(r=>r())}},[i])}function Uh(i,e){const[t,n]=se.useState(null),s=se.useRef(new Set);se.useEffect(()=>{if(i!==void 0&&s.current.has(i)){s.current.delete(i),n(c=>c===i?null:c);return}s.current.clear(),n(null)},[i]);const o=!!(e!=null&&e.presets);se.useEffect(()=>{o||(s.current.clear(),n(null))},[o]);const r=e==null?void 0:e.onPresetChange,a=se.useCallback(c=>{n(c),r&&(s.current.add(c),r(c))},[r]);return{activePreset:t??i,pickerEnabled:o,selectPreset:a}}function Hh(i,e,t,n,s){return se.useMemo(()=>{var h,d,u;const o=i.preset!==e,r=t===!0&&((h=i.pathTracing)==null?void 0:h.enabled)===void 0,a=n!==void 0&&((d=i.controls)==null?void 0:d.autoRotate)===void 0,c=s!==void 0&&((u=i.animations)==null?void 0:u.autoplay)===void 0;return!o&&!r&&!a&&!c?i:{...i,...o?{preset:e}:{},...r?{pathTracing:{...i.pathTracing,enabled:!0}}:{},...a?{controls:{...i.controls,autoRotate:n}}:{},...c?{animations:{...i.animations,autoplay:s}}:{}}},[i,e,t,n,s])}function Vh(i,e,t){const n=se.useMemo(()=>{if(typeof t=="string")return t;if(t)return`object-${t.uuid||"no-uuid"}`},[t]),[s,o]=se.useState(()=>({status:t?"loading":"idle"}));return se.useEffect(()=>{o({status:t?"loading":"idle"})},[n]),se.useEffect(()=>{if(!i||!e||!t||i.isDisposed())return;let r=!0;const a=typeof t=="string"?t:new Ke(t);return i.loadModel(a).then(c=>{!r||i.isDisposed()||(c.ok?o({status:"loaded"}):(o({status:"error",error:c.error.message}),console.error("Failed to load model:",c.error)))}),()=>{r=!1}},[i,e,n]),s}class ti{static toThreeObject(e){const t=wt(e);if(t)return t;const n=new y.Object3D;return n.position.set(e.position.x,e.position.y,e.position.z),n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),n.scale.set(e.scale.x,e.scale.y,e.scale.z),n}static toThreeCamera(e){return Pn(e)??new y.PerspectiveCamera}static toThreeControls(e){return Li(e)??e}static convertModelLoaded(e){return{model:this.toThreeObject(e.model),loadTime:e.loadTime}}static convertControlsChange(e){return{type:e.type,camera:e.camera?this.toThreeCamera(e.camera):void 0,controls:e.controls?this.toThreeControls(e.controls):void 0}}static convertObjectSelected(e){return{object:this.toThreeObject(e.object),point:e.point}}static convertInitialized(e,t){return{viewer:t}}static convertDisposed(e,t){return{viewer:t}}}function Gh(i){const e=se.useRef(new bs),t=se.useMemo(()=>({"model:loading":n=>e.current.emit("model:loading",n),"model:progress":n=>e.current.emit("model:progress",n),"model:loaded":n=>e.current.emit("model:loaded",ti.convertModelLoaded(n)),"model:error":n=>e.current.emit("model:error",n),"render:complete":n=>e.current.emit("render:complete",n),"controls:change":n=>e.current.emit("controls:change",ti.convertControlsChange(n)),"object:selected":n=>e.current.emit("object:selected",ti.convertObjectSelected(n)),error:n=>e.current.emit("error",n)}),[]);return ho(i,t),e.current}function jh(i,e,t){const n=se.useRef(t);n.current=t;const s=se.useMemo(()=>({"model:loaded":()=>{var r,a;return(a=(r=n.current).onLoad)==null?void 0:a.call(r)},"model:progress":r=>{var a,c;return(c=(a=n.current).onProgress)==null?void 0:c.call(a,Math.min(1,r.loaded/r.total))},"model:error":r=>{var a,c;return(c=(a=n.current).onError)==null?void 0:c.call(a,r.error)}}),[]);ho(i,s);const o=se.useRef(null);se.useEffect(()=>{if(!e){o.current=null;return}const r=n.current.onError;r&&o.current!==e&&(o.current=e,r(e))})}const uo=se.createContext(null);function Wh({viewer:i,canvasRef:e,children:t}){const n=se.useMemo(()=>({viewer:i,canvasRef:e}),[i,e]);return ge.jsx(uo.Provider,{value:n,children:t})}function fo(){const i=se.useContext(uo);if(!i)throw new Error("useViewerContext must be used within ViewerProvider");return i}function Zh(){const{canvasRef:i}=fo();return ge.jsx("canvas",{ref:i,style:{width:"100%",height:"100%",display:"block",imageRendering:"auto",background:"transparent"}})}(function(){try{if(typeof document<"u"){var i=document.createElement("style");i.appendChild(document.createTextNode(".gizmo-default{width:100px;height:100px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.custom-gizmo-style{width:360px;height:360px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.map-gizmo-style,.cad-gizmo-style{width:96px;height:96px;position:absolute;top:0;right:0;z-index:2;cursor:pointer}.example-container{position:relative;width:640px;height:360px;background-color:#3d5361;border-radius:6px;overflow:hidden}body{background-color:#f0f0f0;margin:0;padding:0}.content{display:flex;justify-content:center;align-items:center;flex-direction:column;height:100vh}.example-select{margin-bottom:24px}")),document.head.appendChild(i)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();const Kh=(i,e,t,n,s,o)=>{const r=performance.now(),a=()=>{const c=performance.now()-r,h=Math.min(c/s,1);i.position.lerpVectors(t,n,h),e==null||e.update(),o(),h<1&&requestAnimationFrame(a)};requestAnimationFrame(a)},Cr={type:"change"},Di={type:"start"},po={type:"end"},hs=new p.Ray,Pr=new p.Plane,Xh=Math.cos(70*p.MathUtils.DEG2RAD),Oe=new p.Vector3,Qe=2*Math.PI,Se={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ni=1e-6;class mo extends p.Controls{constructor(e,t=null){super(e,t),this.state=Se.NONE,this.target=new p.Vector3,this.cursor=new p.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:p.MOUSE.ROTATE,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.PAN},this.touches={ONE:p.TOUCH.ROTATE,TWO:p.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new p.Vector3,this._lastQuaternion=new p.Quaternion,this._lastTargetPosition=new p.Vector3,this._quat=new p.Quaternion().setFromUnitVectors(e.up,new p.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new p.Spherical,this._sphericalDelta=new p.Spherical,this._scale=1,this._panOffset=new p.Vector3,this._rotateStart=new p.Vector2,this._rotateEnd=new p.Vector2,this._rotateDelta=new p.Vector2,this._panStart=new p.Vector2,this._panEnd=new p.Vector2,this._panDelta=new p.Vector2,this._dollyStart=new p.Vector2,this._dollyEnd=new p.Vector2,this._dollyDelta=new p.Vector2,this._dollyDirection=new p.Vector3,this._mouse=new p.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=qh.bind(this),this._onPointerDown=Yh.bind(this),this._onPointerUp=$h.bind(this),this._onContextMenu=iu.bind(this),this._onMouseWheel=eu.bind(this),this._onKeyDown=tu.bind(this),this._onTouchStart=nu.bind(this),this._onTouchMove=su.bind(this),this._onMouseDown=Qh.bind(this),this._onMouseMove=Jh.bind(this),this._interceptControlDown=ru.bind(this),this._interceptControlUp=ou.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(Cr),this.update(),this.state=Se.NONE}update(e=null){const t=this.object.position;Oe.copy(t).sub(this.target),Oe.applyQuaternion(this._quat),this._spherical.setFromVector3(Oe),this.autoRotate&&this.state===Se.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=Qe:n>Math.PI&&(n-=Qe),s<-Math.PI?s+=Qe:s>Math.PI&&(s-=Qe),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=r!=this._spherical.radius}if(Oe.setFromSpherical(this._spherical),Oe.applyQuaternion(this._quatInverse),t.copy(this.target).add(Oe),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const a=Oe.length();r=this._clampDistance(a*this._scale);const c=a-r;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),o=!!c}else if(this.object.isOrthographicCamera){const a=new p.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=c!==this.object.zoom;const h=new p.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),r=Oe.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(hs.origin.copy(this.object.position),hs.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(hs.direction))<Xh?this.object.lookAt(this.target):(Pr.setFromNormalAndCoplanarPoint(this.object.up,this.target),hs.intersectPlane(Pr,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>ni||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ni||this._lastTargetPosition.distanceToSquared(this.target)>ni?(this.dispatchEvent(Cr),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Qe/60*this.autoRotateSpeed*e:Qe/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Oe.setFromMatrixColumn(t,0),Oe.multiplyScalar(-e),this._panOffset.add(Oe)}_panUp(e,t){this.screenSpacePanning===!0?Oe.setFromMatrixColumn(t,1):(Oe.setFromMatrixColumn(t,0),Oe.crossVectors(this.object.up,Oe)),Oe.multiplyScalar(e),this._panOffset.add(Oe)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;Oe.copy(s).sub(this.target);let o=Oe.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(),s=e-n.left,o=t-n.top,r=n.width,a=n.height;this._mouse.x=s/r*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),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,o=Math.sqrt(n*n+s*s);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),s=.5*(e.pageX+n.x),o=.5*(e.pageY+n.y);this._rotateEnd.set(s,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),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,o=Math.sqrt(n*n+s*s);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 r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new p.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function Yh(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i)))}function qh(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function $h(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(po),this.state=Se.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 Qh(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case p.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Se.DOLLY;break;case p.MOUSE.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Se.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Se.ROTATE}break;case p.MOUSE.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Se.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Se.PAN}break;default:this.state=Se.NONE}this.state!==Se.NONE&&this.dispatchEvent(Di)}function Jh(i){switch(this.state){case Se.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Se.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Se.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function eu(i){this.enabled===!1||this.enableZoom===!1||this.state!==Se.NONE||(i.preventDefault(),this.dispatchEvent(Di),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(po))}function tu(i){this.enabled!==!1&&this._handleKeyDown(i)}function nu(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case p.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Se.TOUCH_ROTATE;break;case p.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Se.TOUCH_PAN;break;default:this.state=Se.NONE}break;case 2:switch(this.touches.TWO){case p.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Se.TOUCH_DOLLY_PAN;break;case p.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Se.TOUCH_DOLLY_ROTATE;break;default:this.state=Se.NONE}break;default:this.state=Se.NONE}this.state!==Se.NONE&&this.dispatchEvent(Di)}function su(i){switch(this._trackPointer(i),this.state){case Se.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Se.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Se.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Se.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Se.NONE}}function iu(i){this.enabled!==!1&&i.preventDefault()}function ru(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function ou(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class au extends mo{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:p.MOUSE.PAN,MIDDLE:p.MOUSE.DOLLY,RIGHT:p.MOUSE.ROTATE},this.touches={ONE:p.TOUCH.PAN,TWO:p.TOUCH.DOLLY_ROTATE}}}const fe={CUBE_SIZE:1.8,EDGE_SECTION_SIZE:.35,FACE_THICKNESS:.35,CANVAS_SIZE:256,FONT_SIZE:"62px",TEXT_COLOR:"#000000",TEXT_ALIGN:"center",TEXT_BASELINE:"middle",FACE_COLOR:"#EFF3F2",EDGE_COLOR:"#EFF3F2",CORNER_COLOR:"#EFF3F2",LINE_COLOR:0};var Lt=(i=>(i.FRONT="FRONT",i.BACK="BACK",i.RIGHT="RIGHT",i.LEFT="LEFT",i.TOP="TOP",i.BOTTOM="BOTTOM",i))(Lt||{});new y.Vector3(0,1,0);const Cn="rotation-arrows-name",xi="left-rotation-arrow-name",Ss="right-rotation-arrow-name",cu="gizmo-group-name",lu=[Ss,xi],ms={GIZMO_DISTANCE:8,DEFAULT_UP:new y.Vector3(0,1,0),FORWARD:new y.Vector3(0,0,-1)},si=i=>ms.FORWARD.clone().applyQuaternion(i),Ir=(i,e,t=new y.Vector3)=>t.clone().add(i.multiplyScalar(-e));class hu{constructor(e,t=Cn){this.gizmoScene=e,this.gizmoArrowsName=t}syncGizmoWithMain(e,t){e.quaternion.copy(t.quaternion),e.up.copy(t.up);const n=si(e.quaternion).normalize();e.position.copy(Ir(n,ms.GIZMO_DISTANCE)),e.camera.updateMatrixWorld(!0);const s=this.gizmoScene.getObjectByName(this.gizmoArrowsName);s&&s.rotation.copy(e.camera.rotation)}syncMainWithGizmo(e,t,n){const s=n.target.clone(),o=e.position.distanceTo(s),r=e.camera instanceof y.PerspectiveCamera;n instanceof au&&!r?this.syncMapControls(e,t,s,o):this.syncOrbitControls(e,t,s,o),e.camera.updateMatrix(),e.camera.updateMatrixWorld(!0),n.update()}syncMapControls(e,t,n,s){const o=e.position.y-n.y,r=si(t.quaternion);r.y=0,r.normalize();const a=n.clone();a.y+=o,a.add(r.multiplyScalar(-s)),e.position.copy(a),e.up.copy(ms.DEFAULT_UP),e.camera.lookAt(n)}syncOrbitControls(e,t,n,s){const o=si(t.quaternion),r=ms.DEFAULT_UP.clone().applyQuaternion(t.quaternion),a=Ir(o,s,n);e.position.copy(a),e.up.copy(r),e.camera.lookAt(n)}}const go=i=>new hu(i),Lr=(i,e,t)=>{go(t).syncGizmoWithMain({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up})},uu=(i,e,t)=>{go(e.userData.scene).syncMainWithGizmo({camera:i,position:i.position,quaternion:i.quaternion,up:i.up},{camera:e,position:e.position,quaternion:e.quaternion,up:e.up},t)},du=()=>{try{const i=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(i.getContext("webgl")||i.getContext("experimental-webgl")))}catch{return!1}},fu=()=>du()?new y.WebGLRenderer({alpha:!0,antialias:!1}):(console.error("WebGL is not supported in this environment."),null),pu=i=>{const e=new y.AmbientLight(16777215,1);i.add(e);const t=new y.DirectionalLight(16777215,1);t.position.set(5,10,5),i.add(t);const n=new y.DirectionalLight(16777215,1);n.position.set(-5,-10,5),i.add(n);const s=new y.PointLight(16777215,1,100);s.position.set(0,0,5),i.add(s),t.castShadow=!1,n.castShadow=!1,s.castShadow=!1};class mu{static createTextTexture(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=fe.CANVAS_SIZE,t.height=fe.CANVAS_SIZE,n&&(n.clearRect(0,0,t.width,t.height),n.font=`${fe.FONT_SIZE} Arial`,n.fillStyle=fe.TEXT_COLOR,n.textAlign=fe.TEXT_ALIGN,n.textBaseline=fe.TEXT_BASELINE,n.fillText(e,t.width/2,t.height/2));const s=new y.CanvasTexture(t);return s.needsUpdate=!0,s}}class us{static createWireframe([e,t,n]){const s=new y.BoxGeometry(e,t,n),o=new y.EdgesGeometry(s),r=new y.LineBasicMaterial({color:fe.LINE_COLOR}),a=new y.LineSegments(o,r);return a.name="Wireframe",a}static createEdgeBox(e,t,n){const s=fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,o={x:fe.EDGE_SECTION_SIZE,y:fe.EDGE_SECTION_SIZE,z:fe.EDGE_SECTION_SIZE};o[t]=s;const r=new y.BoxGeometry(o.x,o.y,o.z),a=new y.MeshStandardMaterial({color:fe.EDGE_COLOR}),c=new y.Mesh(r,a);return c.position.copy(e),c.name=`Edge Box ${n}`,c}static createCornerCube(e,t){const n=new y.BoxGeometry(fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE,fe.EDGE_SECTION_SIZE),s=new y.MeshStandardMaterial({color:fe.CORNER_COLOR}),o=new y.Mesh(n,s);return o.position.copy(e),o.name=`Corner Cube ${t}`,o}static createFace(e,t,n){const s=new y.Group,o=new y.BoxGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.FACE_THICKNESS),r=new y.MeshStandardMaterial({color:fe.FACE_COLOR}),a=new y.Mesh(o,r);a.name=`Face Box ${n}`,s.add(a);const c=new y.PlaneGeometry(fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE,fe.CUBE_SIZE-fe.EDGE_SECTION_SIZE),h=new y.MeshStandardMaterial({map:mu.createTextTexture(n),transparent:!0,depthWrite:!1}),d=new y.Mesh(c,h);return d.position.set(0,0,fe.FACE_THICKNESS/2+.01),s.add(d),s.position.copy(e),s.rotation.copy(t),s}}const gu=(i,e)=>{const t=document.createElement("canvas");t.width=64,t.height=64;const n=t.getContext("2d");n.fillStyle="rgba(0, 0, 0, 0)",n.fillRect(0,0,t.width,t.height),n.font="Bold 48px Arial",n.fillStyle=`#${e.toString(16).padStart(6,"0")}`,n.textAlign="center",n.textBaseline="middle",n.fillText(i,t.width/2,t.height/2);const s=new y.CanvasTexture(t),o=new y.SpriteMaterial({map:s}),r=new y.Sprite(o);return r.scale.set(.5,.5,.5),r};class yu{constructor(e){this.hoveredObject=null,this.originalColor=null,this.config=e}get vectorToCube(){var e;return(e=this.hoveredObject)==null?void 0:e.userData.vectorToCube}getInitialRotation(){switch(this.config.initialFace){case Lt.BACK:return new y.Euler(0,Math.PI,0);case Lt.RIGHT:return new y.Euler(0,-Math.PI/2,0);case Lt.LEFT:return new y.Euler(0,Math.PI/2,0);case Lt.TOP:return new y.Euler(Math.PI/2,0,0);case Lt.BOTTOM:return new y.Euler(-Math.PI/2,0,0);case Lt.FRONT:default:return new y.Euler(0,0,0)}}createWireframe(){const e=fe.CUBE_SIZE+fe.EDGE_SECTION_SIZE,t=us.createWireframe([e,e,e]);return t.userData.gizmoCube=this,t}createEdgeBox(e,t,n){const s=us.createEdgeBox(e,t,n);return s.userData.gizmoCube=this,s}createCornerCube(e,t){const n=us.createCornerCube(e,t);return n.userData.gizmoCube=this,n}createFace(e,t,n){const s=us.createFace(e,t,n),o=s.getObjectByName(`Face Box ${n}`);return o.userData.gizmoCube=this,s}createEdges(e){const t=fe.CUBE_SIZE/2;[{axis:"x",pos:new y.Vector3(0,t,-t)},{axis:"x",pos:new y.Vector3(0,t,t)},{axis:"x",pos:new y.Vector3(0,-t,-t)},{axis:"x",pos:new y.Vector3(0,-t,t)},{axis:"y",pos:new y.Vector3(t,0,-t)},{axis:"y",pos:new y.Vector3(t,0,t)},{axis:"y",pos:new y.Vector3(-t,0,-t)},{axis:"y",pos:new y.Vector3(-t,0,t)},{axis:"z",pos:new y.Vector3(t,t,0)},{axis:"z",pos:new y.Vector3(t,-t,0)},{axis:"z",pos:new y.Vector3(-t,t,0)},{axis:"z",pos:new y.Vector3(-t,-t,0)}].forEach(({axis:n,pos:s},o)=>{const r=this.createEdgeBox(s,n,o+1);e.add(r)})}createCorners(e){const t=fe.CUBE_SIZE/2;[new y.Vector3(-t,-t,-t),new y.Vector3(-t,-t,t),new y.Vector3(-t,t,-t),new y.Vector3(-t,t,t),new y.Vector3(t,-t,-t),new y.Vector3(t,-t,t),new y.Vector3(t,t,-t),new y.Vector3(t,t,t)].forEach((n,s)=>{const o=this.createCornerCube(n,s+1);e.add(o)})}createFaces(e){const t=fe.CUBE_SIZE/2;[{pos:new y.Vector3(0,0,t),rotation:new y.Euler(0,0,0),label:"FRONT"},{pos:new y.Vector3(0,0,-t),rotation:new y.Euler(0,Math.PI,0),label:"BACK"},{pos:new y.Vector3(t,0,0),rotation:new y.Euler(0,Math.PI/2,0),label:"RIGHT"},{pos:new y.Vector3(-t,0,0),rotation:new y.Euler(0,-Math.PI/2,0),label:"LEFT"},{pos:new y.Vector3(0,t,0),rotation:new y.Euler(-Math.PI/2,0,0),label:"TOP"},{pos:new y.Vector3(0,-t,0),rotation:new y.Euler(Math.PI/2,0,0),label:"BOTTOM"}].forEach(({pos:n,rotation:s,label:o})=>{const r=this.createFace(n,s,o);e.add(r)})}createAxis(e){const{color:t,direction:n,length:s,origin:o,lineWidth:r,label:a}=e,c=new y.Group,h=r/2,d=new y.CylinderGeometry(h,h,s,32),u=new y.MeshBasicMaterial({color:t}),f=new y.Mesh(d,u);if(f.position.copy(o).add(n.clone().multiplyScalar(s/2)),!n.equals(new y.Vector3(0,1,0))){const E=new y.Vector3(0,1,0).cross(n).normalize(),b=Math.acos(new y.Vector3(0,1,0).dot(n));f.setRotationFromAxisAngle(E,b)}c.add(f);const m=gu(a,t);return m.position.copy(o).add(n.clone().multiplyScalar(s+.1)),c.add(m),c}createCoordinateAxes(){const e=new y.Group,t=fe.CUBE_SIZE,n=fe.EDGE_SECTION_SIZE,s=-1.075,o=a=>{const c=new y.Vector3(1,1,1);return new y.Vector3(a,a,a).add(c.clone().normalize().negate().multiplyScalar(.04))},r=t+1.25*n;return[{color:16711680,direction:new y.Vector3(1,0,0),length:r,origin:o(s),lineWidth:.04,label:"X"},{color:65280,direction:new y.Vector3(0,1,0),length:r,origin:o(s),lineWidth:.04,label:"Y"},{color:255,direction:new y.Vector3(0,0,1),length:r,origin:o(s),lineWidth:.04,label:"Z"}].forEach(a=>{const c=this.createAxis(a);e.add(c)}),e}create(){const e=new y.Group;e.name=cu;const t=this.createWireframe();e.add(t),this.createEdges(e),this.createCorners(e),this.createFaces(e);const n=this.createCoordinateAxes();e.add(n);const s=this.getInitialRotation();return e.setRotationFromEuler(s),e}highlightObject(e){if(this.hoveredObject!==e)if(this.hoveredObject&&this.originalColor&&this.hoveredObject.material.color.set(this.originalColor),e&&e instanceof y.Mesh){const t=e.material;this.hoveredObject=e,this.originalColor=t.color.clone(),t.color.set(11519973)}else this.hoveredObject=null,this.originalColor=null}handleClick(){if(this.hoveredObject){let e=new y.Vector3;e=this.hoveredObject.getWorldPosition(e).clone();const t=new y.Vector3(0,0,0),n=e.sub(t).normalize();this.hoveredObject.userData.vectorToCube=n}}}class Eu{constructor(e){this.onChangeMainControlsListener=()=>{},this.onChangeGizmoControlsListener=()=>{},this.animationId=0;const{gizmoParams:t,mainParams:n,syncFunctions:s,options: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=s,this.options=o,this.gizmoControls=new mo(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 yu({initialFace:((e=this.options)==null?void 0:e.initialFace)??Lt.FRONT}).create();this.gizmoScene.add(t),pu(this.gizmoScene)}initializeControls(){this.onChangeMainControlsListener=()=>this.syncFunctions.syncGizmoCameraWithMain(this.gizmoCamera,this.mainCamera,this.gizmoScene),this.mainControls.addEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.enableZoom=!1,this.gizmoControls.enablePan=!1,this.gizmoControls.rotateSpeed=.5,this.gizmoControls.update(),this.onChangeGizmoControlsListener=()=>{const e=this.gizmoScene.getObjectByName(Cn);e==null||e.rotation.copy(this.gizmoCamera.rotation),this.syncFunctions.syncMainCameraWithGizmo(this.mainCamera,this.gizmoCamera,this.mainControls),this.renderGizmo()},this.gizmoControls.addEventListener("change",this.onChangeGizmoControlsListener)}startAnimationLoop(){const e=()=>{this.gizmoRenderer.render(this.gizmoScene,this.gizmoCamera)},t=()=>{this.animationId=requestAnimationFrame(t),e()};t()}dispose(){this.mainControls.removeEventListener("change",this.onChangeMainControlsListener),this.gizmoControls.removeEventListener("change",this.onChangeGizmoControlsListener),this.gizmoScene.clear(),cancelAnimationFrame(this.animationId)}}const Tu=(i,e)=>{let t;return function(...n){t||(i.apply(this,n),t=!0,setTimeout(()=>t=!1,e))}};function Or(i,e,t){if(!e)return;const n=e.domElement.getBoundingClientRect();t.x=(i.clientX-n.left)/n.width*2-1,t.y=-((i.clientY-n.top)/n.height)*2+1}const yo=(i,e,t,n)=>(n.setFromCamera(i,e),n.intersectObjects(t.children,!0)),Eo=i=>{var e;const t=["Wireframe",""];return((e=i.find(n=>!t.includes(n.object.name)))==null?void 0:e.object)||null};function wu(i,e,t,n){if(!e||!t)return null;const s=yo(i,e,t,n);return Eo(s)}function Su(i,e){const t=i==null?void 0:i.userData.gizmoCube;if(i&&t){t.handleClick();const n=t.vectorToCube;n&&e(n)}}const _u={radius:2.1,color:12369854,tubeRadius:.1,tubeSegments:8,numPoints:64,tubeOffset:1.5},bu={size:.2,depth:.1,heightRatio:1.4,segments:1};class xu{constructor(e={}){this.config={..._u,...e},this.material=new y.MeshBasicMaterial({color:this.config.color})}create(){const e=new y.Group,t=this.createQuarterCircleCurves();return e.add(...this.createTubes(t),...this.createArrowHeads(t)),e.name=Cn,e}createQuarterCircleCurves(){const e=this.generateQuarterCirclePoints(),t=Math.floor(e.length/2);return[new y.CatmullRomCurve3(e.slice(0,t-this.config.tubeOffset)),new y.CatmullRomCurve3(e.slice(t+this.config.tubeOffset))]}generateQuarterCirclePoints(){const e=Math.PI/2,t=e/2,n=e/4;return Array.from({length:this.config.numPoints+1},(s,o)=>{const r=o/this.config.numPoints,a=n+t*r,c=this.config.radius*Math.sin(a),h=this.config.radius*Math.cos(a);return new y.Vector3(c,h,0)})}createTubes([e,t]){const n=(s,o)=>{const r=new y.TubeGeometry(s,this.config.numPoints,this.config.tubeRadius,this.config.tubeSegments,!1),a=new y.Mesh(r,this.material);return a.name=o,a};return[n(e,xi),n(t,Ss)]}createArrowHeads([e,t]){const{size:n,depth:s,heightRatio:o,segments:r}=bu,a=this.createArrowShape(n,o),c=new y.ExtrudeGeometry(a,{steps:r,depth:s,bevelEnabled:!1}).center(),h=(d,u,f)=>{const m=new y.Mesh(c,this.material);return m.position.copy(d),m.rotation.z=u,m.name=f,m};return[h(e.getPoint(0),this.calculateArrowRotation(e.getTangent(0))+Math.PI/2,xi),h(t.getPoint(1),this.calculateArrowRotation(t.getTangent(1))-Math.PI/2,Ss)]}createArrowShape(e,t){return new y.Shape().moveTo(0,0).lineTo(e,-e*t).lineTo(-e,-e*t).lineTo(0,0)}calculateArrowRotation(e){return Math.atan2(e.y,e.x)}}const Au=i=>{const e=i.rotation,t=.01,n=Math.PI,s=(Math.abs(e.x)%(2*n)+2*n)%(2*n),o=(Math.abs(e.y)%(2*n)+2*n)%(2*n),r=Math.abs(s-n/2)<t||Math.abs(s-3*n/2)<t||Math.abs(o-n/2)<t||Math.abs(o-3*n/2)<t,a=(Math.abs(s)<t||Math.abs(s-n)<t)&&(Math.abs(o)<t||Math.abs(o-n)<t);return!(r||a)},vu=25,Ru=200;function Mu({gizmoRenderer:i,gizmoScene:e,gizmoCamera:t,alignCameraWithVector:n,gizmoControlRef:s}){const o=se.useRef(null),r=se.useRef(null),a=se.useRef(new y.Raycaster).current,c=se.useRef(new y.Vector2).current,h=se.useCallback(()=>{const b=e.getObjectByName(Cn),w=Au(t);if(b&&w){e.remove(b);return}if(b||w)return;const A=new xu().create();A.rotation.copy(t.rotation),e.add(A)},[e,t]),d=se.useCallback(()=>{const b=e.getObjectByName(Cn);b&&e.remove(b)},[e]),u=se.useCallback(Tu(b=>{if(!s.current||!i)return;Or(b,i,c);const w=yo(c,t,e,a),A=Eo(w);A!=null&&A.userData.gizmoCube?A.userData.gizmoCube.highlightObject(A):e.traverse(S=>{S.userData.gizmoCube&&S.userData.gizmoCube.highlightObject(null)}),w.length>0?h():d()},1e3/vu),[s,i,t,e,a,c,h,d]),f=se.useCallback(b=>{o.current=Date.now(),r.current={x:b.clientX,y:b.clientY}},[]),m=se.useCallback(b=>{var w;const A=b.name===Ss?1:-1,S=90*Math.PI/180,_=new y.Vector3(0,0,0),x=A*S,v=new y.Matrix4;v.makeRotationZ(x),t.up.applyMatrix4(v),t.lookAt(_),(w=s.current)==null||w.gizmoControls.update()},[t,s]),E=se.useCallback(b=>{if((o.current?Date.now()-o.current:0)<Ru){Or(b,i,c);const w=wu(c,t,e,a);w!=null&&w.name&&lu.includes(w.name)?m(w):Su(w,n)}o.current=null,r.current=null},[m,n,i,t,e,a,c]);return{onMouseDown:f,onMouseMove:u,onMouseUp:E,onMouseLeave:d}}const Cu=({camera:i,controls:e,className:t,render:n,options:s})=>{const o=se.useRef(null),r=se.useRef(new y.Scene).current,[a]=se.useState(()=>fu()),c=30,h=1,d=.1,u=10,f=new y.PerspectiveCamera(c,h,d,u),m=se.useRef(f).current,E=se.useRef(null),b=se.useCallback(()=>{a&&(n(),a.render(r,m))},[n,a,r,m]),w=se.useCallback(v=>{if(!i||!e)return;const L=i.position.length(),I=v.clone().multiplyScalar(L),C=400,D=new y.Matrix4;D.lookAt(I,new y.Vector3(0,0,0),new y.Vector3(0,1,0));const P=new y.Quaternion;P.setFromRotationMatrix(D),i.quaternion.copy(P),Kh(i,e,i.position.clone(),I,C,b),i.up.set(0,1,0),i.lookAt(new y.Vector3(0,0,0)),e.target.set(0,0,0),e.update()},[i,e,b,r]),{onMouseDown:A,onMouseMove:S,onMouseUp:_,onMouseLeave:x}=Mu({gizmoRenderer:a,gizmoScene:r,gizmoCamera:m,alignCameraWithVector:w,gizmoControlRef:E});return se.useEffect(()=>{const v=o.current;if(!v||!i||!e||!a)return;E.current&&E.current.dispose();const L={gizmoDiv:v,gizmoScene:r,gizmoRenderer:a,gizmoCamera:m},I={mainCamera:i,mainControls:e,renderGizmo:b},C={syncGizmoCameraWithMain:Lr,syncMainCameraWithGizmo:uu};return E.current=new Eu({gizmoParams:L,mainParams:I,syncFunctions:C,options:s}),v.addEventListener("mousedown",A),v.addEventListener("mousemove",S),v.addEventListener("mouseup",_),v.addEventListener("mouseleave",x),()=>{E.current&&(E.current.dispose(),E.current=null),v.removeEventListener("mousedown",A),v.removeEventListener("mousemove",S),v.removeEventListener("mouseup",_),v.removeEventListener("mouseleave",x)}},[i,e,b,S,A,_]),se.useEffect(()=>{i&&(Lr(m,i,r),b())},[i,b]),ge.jsx("div",{className:t?`${t}`:"gizmo-default",ref:o})},ds=10,Pu=i=>({top:i.startsWith("top")?ds:"auto",bottom:i.startsWith("bottom")?ds:"auto",left:i.endsWith("left")?ds:"auto",right:i.endsWith("right")?ds:"auto"}),Iu=({camera:i,controls:e,render:t,placement:n="top-right",size:s=128})=>{if(!i||!e)return null;const o=e;return ge.jsx("div",{className:"viewer-gizmo-container",style:{position:"absolute",width:s,height:s,zIndex:1e3,...Pu(n)},children:ge.jsx(Cu,{camera:i,controls:o,render:t})})};class Lu extends se.Component{constructor(e){super(e),this.reset=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ViewerErrorBoundary caught error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:ge.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:ge.jsxs("div",{children:[ge.jsx("h3",{children:"Error Loading 3D Viewer"}),ge.jsx("p",{children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),ge.jsx("button",{type:"button",onClick:this.reset,children:"Try again"})]})}):this.props.children}}function Ou({status:i,label:e,color:t,backdrop:n}){const s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;return ge.jsxs("div",{"data-testid":"viewer-loading-overlay",role:"status","aria-live":"polite","aria-busy":i==="loading",style:{position:"absolute",inset:0,zIndex:20,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,background:n,color:t,pointerEvents:"none",userSelect:"none",fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, sans-serif",fontSize:14},children:[i==="loading"?ge.jsxs("svg",{width:"44",height:"44",viewBox:"0 0 44 44","aria-hidden":"true",children:[ge.jsx("circle",{cx:"22",cy:"22",r:"18",fill:"none",stroke:t,strokeOpacity:"0.25",strokeWidth:"4"}),ge.jsx("path",{d:"M22 4 a18 18 0 0 1 18 18",fill:"none",stroke:t,strokeWidth:"4",strokeLinecap:"round",children:!s&&ge.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 22 22",to:"360 22 22",dur:"0.9s",repeatCount:"indefinite"})})]}):ge.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[ge.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),ge.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),ge.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),e&&ge.jsx("div",{style:{opacity:.92,maxWidth:"80%",textAlign:"center"},children:e})]})}const Du='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',Nu={background:"rgba(255,255,255,0.78)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(0,0,0,0.06)",boxShadow:"0 8px 30px rgba(0,0,0,0.10)"},ku=Object.keys(Oi);function Fu({active:i,onSelect:e}){return ge.jsx("div",{"data-testid":"viewer-preset-picker",role:"group","aria-label":"Visual preset",style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:10,display:"flex",gap:2,padding:4,borderRadius:999,maxWidth:"calc(100% - 16px)",overflowX:"auto",...Nu},children:ku.map(t=>ge.jsx("button",{type:"button","aria-pressed":t===i,onClick:()=>e(t),style:{padding:"6px 14px",borderRadius:999,border:t===i?"1px solid #111318":"1px solid transparent",background:t===i?"#111318":"transparent",color:t===i?"#fff":"#3f3f4a",fontFamily:Du,fontSize:13,fontWeight:500,lineHeight:1,whiteSpace:"nowrap",flexShrink:0,cursor:"pointer",textTransform:"capitalize",transition:"background 120ms ease, color 120ms ease"},children:t},t))})}const bn={enabled:!0,label:"Loading…",color:"#ffffff",backdrop:"rgba(15,16,20,0.6)"};function Bu(i){return i===void 0||i===!0?bn:i===!1?{...bn,enabled:!1}:{enabled:i.enabled??!0,label:i.label??bn.label,errorLabel:i.errorLabel,color:i.color??bn.color,backdrop:i.backdrop??bn.backdrop}}const Pt=()=>new Z("Viewer is not ready yet",K.COMPONENT_NOT_MOUNTED),To=se.forwardRef(({object:i,options:e={},preset:t,pathTraced:n,turntable:s,animations:o,children:r},a)=>{var k,U;const c=se.useRef(null),h=e.preset??t,{activePreset:d,pickerEnabled:u,selectPreset:f}=Uh(h,e.ui),m=Hh(e,d,n,s,o),{viewer:E,isInitialized:b,initError:w}=zh(c,m),A=Vh(E,b,i),S=Gh(E);jh(E,w,e);const _=E?Pn(E.getCamera()):null,x=E?Li(E.getControls()):null,v=E?eo(E.getRenderer()):null,L=se.useCallback(()=>{E==null||E.requestRender()},[E]),I=((k=e.helpers)==null?void 0:k.gizmo)!==void 0&&e.helpers.gizmo!==!1,C=typeof((U=e.helpers)==null?void 0:U.gizmo)=="object"?e.helpers.gizmo:{},D=se.useMemo(()=>Bu(e.loadingIndicator),[e.loadingIndicator]),P=A.status==="error"||!!w,F=D.enabled&&(A.status==="loading"||P);return se.useImperativeHandle(a,()=>({scene:E?ot(E.getScene()):null,camera:_,renderer:v,controls:x,events:S,loadModel:async z=>{if(!E)throw Pt();const Y=typeof z=="string"?z:new Ke(z),re=await E.loadModel(Y);if(!re.ok)throw re.error},captureStill:async z=>{if(!E)throw Pt();const Y=await E.captureStill(z);if(!Y.ok)throw Y.error;return Y.value},captureVideo:async z=>{if(!E)throw Pt();const Y=await E.captureVideo(z);if(!Y.ok)throw Y.error;return Y.value},getAnimationNames:()=>(E==null?void 0:E.getAnimationNames())??[],playAnimations:z=>{if(!E)throw Pt();const Y=E.playAnimations(z);if(!Y.ok)throw Y.error},pauseAnimations:()=>{E==null||E.pauseAnimations()},setEnvironmentMap:async z=>{if(!E)throw Pt();const Y=await E.setEnvironmentMap(z);if(!Y.ok)throw Y.error},resetEnvironment:()=>{if(!E)throw Pt();const z=E.resetEnvironment();if(!z.ok)throw z.error},setBackgroundImage:async z=>{if(!E)throw Pt();const Y=await E.setBackgroundImage(z);if(!Y.ok)throw Y.error},setBackgroundColor:z=>{if(!E)throw Pt();const Y=E.setBackgroundColor(z);if(!Y.ok)throw Y.error},dispose:()=>{E==null||E.dispose()}}),[E,_,v,x,S]),ge.jsx(Lu,{children:ge.jsx(Wh,{viewer:E,canvasRef:c,children:ge.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[ge.jsx(Zh,{}),I&&b&&_&&x&&ge.jsx(Iu,{camera:_,controls:x,render:L,placement:C.placement,size:C.size}),F&&ge.jsx(Ou,{status:P?"error":"loading",label:P?D.errorLabel??(w==null?void 0:w.message)??A.error??"Failed to load model":D.label,color:D.color,backdrop:D.backdrop}),u&&ge.jsx(Fu,{active:d??"studio",onSelect:f}),r]})})})});To.displayName="SimpleViewer";const wo=se.forwardRef((i,e)=>ge.jsx(To,{ref:e,...i}));wo.displayName="SimpleViewer";const zu=()=>ge.jsx("span",{"aria-hidden":"true",style:{display:"block",width:14,height:14,borderRadius:"50%",background:"rgba(17,19,24,0.9)",border:"2px solid rgba(255,255,255,0.95)",boxShadow:"0 2px 8px rgba(0,0,0,0.35)"}});function Uu({position:i,occlude:e=!1,children:t}){const{viewer:n}=fo(),s=se.useRef(null),[o,r,a]=i;se.useEffect(()=>{if(!n)return;const h=s.current;if(!h)return;const d=n.createAnchorProjector();if(!d)return;const u={x:o,y:r,z:a},f=()=>{const w=d.project(u,e);if(w){if(!w.visible){h.style.visibility="hidden";return}h.style.visibility="visible",h.style.left=`${w.left}px`,h.style.top=`${w.top}px`}},m=()=>{d.invalidate(),f()};f();const E=n.getEvents(),b=[E.on("render:complete",f),E.on("controls:change",f),E.on("model:loaded",m)];return window.addEventListener("resize",m),()=>{b.forEach(w=>w()),window.removeEventListener("resize",m)}},[n,o,r,a,e]);const c=t!=null&&t!==!1;return ge.jsx("div",{ref:s,"data-testid":"viewer-hotspot",style:{position:"absolute",left:0,top:0,transform:"translate(-50%, -50%)",visibility:"hidden",zIndex:5,pointerEvents:c?"auto":"none"},children:c?t:ge.jsx(zu,{})})}exports.BOUNDING_DATA_INDEX=Ta;exports.BYTES_PER_NODE=He;exports.CONTACT_SHADOW_HELPER_FLAG=Cs;exports.COUNT=Xe;exports.ControlType=Mn;exports.DEFAULT_PATH_TRACING_SAMPLES=ii;exports.ErrorCode=K;exports.Hotspot=Uu;exports.IS_LEAF=Pe;exports.LEAFNODE_MASK_32=Ea;exports.MeshBVH=Rn;exports.OFFSET=Ve;exports.PATH_TRACING_FLOOR_FLAG=Ps;exports.Result=N;exports.SAH=zr;exports.SPLIT_AXIS=xs;exports.SimpleViewerWrapper=wo;exports.ThreeViewerError=Z;exports.TypedEventEmitter=bs;exports.VIEWER_PRESETS=Oi;exports.defaultOptions=ws;exports.getIndexArray=Gr;exports.getVertexCount=As;exports.resolvePreset=lo;
|