@ridp/threejs 1.5.1 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +0,0 @@
1
- "use strict";const u=require("three"),Ge=require("dexie");function Be(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const x=Be(u),be={type:"change"},_e={type:"start"},Oe={type:"end"},te=new u.Ray,Ee=new u.Plane,ze=Math.cos(70*u.MathUtils.DEG2RAD),L=new u.Vector3,O=2*Math.PI,R={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ce=1e-6;class Ie extends u.Controls{constructor(e,t=null){super(e,t),this.state=R.NONE,this.target=new u.Vector3,this.cursor=new u.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:u.MOUSE.ROTATE,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.PAN},this.touches={ONE:u.TOUCH.ROTATE,TWO:u.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 u.Vector3,this._lastQuaternion=new u.Quaternion,this._lastTargetPosition=new u.Vector3,this._quat=new u.Quaternion().setFromUnitVectors(e.up,new u.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new u.Spherical,this._sphericalDelta=new u.Spherical,this._scale=1,this._panOffset=new u.Vector3,this._rotateStart=new u.Vector2,this._rotateEnd=new u.Vector2,this._rotateDelta=new u.Vector2,this._panStart=new u.Vector2,this._panEnd=new u.Vector2,this._panDelta=new u.Vector2,this._dollyStart=new u.Vector2,this._dollyEnd=new u.Vector2,this._dollyDelta=new u.Vector2,this._dollyDirection=new u.Vector3,this._mouse=new u.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Ve.bind(this),this._onPointerDown=Ke.bind(this),this._onPointerUp=We.bind(this),this._onContextMenu=Je.bind(this),this._onMouseWheel=$e.bind(this),this._onKeyDown=qe.bind(this),this._onTouchStart=Ze.bind(this),this._onTouchMove=Qe.bind(this),this._onMouseDown=Xe.bind(this),this._onMouseMove=Ye.bind(this),this._interceptControlDown=et.bind(this),this._interceptControlUp=tt.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(be),this.update(),this.state=R.NONE}update(e=null){const t=this.object.position;L.copy(t).sub(this.target),L.applyQuaternion(this._quat),this._spherical.setFromVector3(L),this.autoRotate&&this.state===R.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+=O:n>Math.PI&&(n-=O),s<-Math.PI?s+=O:s>Math.PI&&(s-=O),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const i=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=i!=this._spherical.radius}if(L.setFromSpherical(this._spherical),L.applyQuaternion(this._quatInverse),t.copy(this.target).add(L),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let i=null;if(this.object.isPerspectiveCamera){const c=L.length();i=this._clampDistance(c*this._scale);const a=c-i;this.object.position.addScaledVector(this._dollyDirection,a),this.object.updateMatrixWorld(),r=!!a}else if(this.object.isOrthographicCamera){const c=new u.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object);const a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=a!==this.object.zoom;const l=new u.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(c),this.object.updateMatrixWorld(),i=L.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;i!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(i).add(this.object.position):(te.origin.copy(this.object.position),te.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(te.direction))<ze?this.object.lookAt(this.target):(Ee.setFromNormalAndCoplanarPoint(this.object.up,this.target),te.intersectPlane(Ee,this.target))))}else if(this.object.isOrthographicCamera){const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),i!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>ce||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ce||this._lastTargetPosition.distanceToSquared(this.target)>ce?(this.dispatchEvent(be),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?O/60*this.autoRotateSpeed*e:O/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){L.setFromMatrixColumn(t,0),L.multiplyScalar(-e),this._panOffset.add(L)}_panUp(e,t){this.screenSpacePanning===!0?L.setFromMatrixColumn(t,1):(L.setFromMatrixColumn(t,0),L.crossVectors(this.object.up,L)),L.multiplyScalar(e),this._panOffset.add(L)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;L.copy(s).sub(this.target);let r=L.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,i=n.width,c=n.height;this._mouse.x=s/i*2-1,this._mouse.y=-(r/c)*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(O*this._rotateDelta.x/t.clientHeight),this._rotateUp(O*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(O*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(-O*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(O*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(-O*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(O*this._rotateDelta.x/t.clientHeight),this._rotateUp(O*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const i=(e.pageX+t.x)*.5,c=(e.pageY+t.y)*.5;this._updateZoomParameters(i,c)}_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 u.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 Ke(o){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(o)&&(this._addPointer(o),o.pointerType==="touch"?this._onTouchStart(o):this._onMouseDown(o)))}function Ve(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function We(o){switch(this._removePointer(o),this._pointers.length){case 0:this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Oe),this.state=R.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 Xe(o){let e;switch(o.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 u.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=R.DOLLY;break;case u.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=R.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=R.ROTATE}break;case u.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=R.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=R.PAN}break;default:this.state=R.NONE}this.state!==R.NONE&&this.dispatchEvent(_e)}function Ye(o){switch(this.state){case R.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case R.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case R.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function $e(o){this.enabled===!1||this.enableZoom===!1||this.state!==R.NONE||(o.preventDefault(),this.dispatchEvent(_e),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(Oe))}function qe(o){this.enabled!==!1&&this._handleKeyDown(o)}function Ze(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case u.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=R.TOUCH_ROTATE;break;case u.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=R.TOUCH_PAN;break;default:this.state=R.NONE}break;case 2:switch(this.touches.TWO){case u.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=R.TOUCH_DOLLY_PAN;break;case u.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=R.TOUCH_DOLLY_ROTATE;break;default:this.state=R.NONE}break;default:this.state=R.NONE}this.state!==R.NONE&&this.dispatchEvent(_e)}function Qe(o){switch(this._trackPointer(o),this.state){case R.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case R.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case R.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case R.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=R.NONE}}function Je(o){this.enabled!==!1&&o.preventDefault()}function et(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function tt(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class st extends Ie{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:u.MOUSE.PAN,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.ROTATE},this.touches={ONE:u.TOUCH.PAN,TWO:u.TOUCH.DOLLY_ROTATE}}}function Se(o,e){if(e===u.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),o;if(e===u.TriangleFanDrawMode||e===u.TriangleStripDrawMode){let t=o.getIndex();if(t===null){const i=[],c=o.getAttribute("position");if(c!==void 0){for(let a=0;a<c.count;a++)i.push(a);o.setIndex(i),t=o.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),o}const n=t.count-2,s=[];if(e===u.TriangleFanDrawMode)for(let i=1;i<=n;i++)s.push(t.getX(0)),s.push(t.getX(i)),s.push(t.getX(i+1));else for(let i=0;i<n;i++)i%2===0?(s.push(t.getX(i)),s.push(t.getX(i+1)),s.push(t.getX(i+2))):(s.push(t.getX(i+2)),s.push(t.getX(i+1)),s.push(t.getX(i)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=o.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),o}const le=new WeakMap;class nt extends u.Loader{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,s){const r=new u.FileLoader(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,i=>{this.parse(i,t,s)},n,s)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,u.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,s,r=u.LinearSRGBColorSpace,i=()=>{}){const c={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:r};return this.decodeGeometry(e,c).then(t).catch(i)}decodeGeometry(e,t){const n=JSON.stringify(t);if(le.has(e)){const a=le.get(e);if(a.key===n)return a.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const r=this.workerNextTaskID++,i=e.byteLength,c=this._getWorker(r,i).then(a=>(s=a,new Promise((l,d)=>{s._callbacks[r]={resolve:l,reject:d},s.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(a=>this._createGeometry(a.geometry));return c.catch(()=>!0).then(()=>{s&&r&&this._releaseTask(s,r)}),le.set(e,{key:n,promise:c}),c}_createGeometry(e){const t=new u.BufferGeometry;e.index&&t.setIndex(new u.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n],r=s.name,i=s.array,c=s.itemSize,a=new u.BufferAttribute(i,c);r==="color"&&(this._assignVertexColorSpace(a,s.vertexColorSpace),a.normalized=!(i instanceof Float32Array)),t.setAttribute(r,a)}return t}_assignVertexColorSpace(e,t){if(t!==u.SRGBColorSpace)return;const n=new u.Color;for(let s=0,r=e.count;s<r;s++)n.fromBufferAttribute(e,s),u.ColorManagement.colorSpaceToWorking(n,u.SRGBColorSpace),e.setXYZ(s,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new u.FileLoader(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((s,r)=>{n.load(e,s,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const s=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const r=it.toString(),i=["/* draco decoder */",s,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
2
- `);this.workerSourceURL=URL.createObjectURL(new Blob([i]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(r){const i=r.data;switch(i.type){case"decode":s._callbacks[i.id].resolve(i);break;case"error":s._callbacks[i.id].reject(i);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+i.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,r){return s._taskLoad>r._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function it(){let o,e;onmessage=function(i){const c=i.data;switch(c.type){case"init":o=c.decoderConfig,e=new Promise(function(d){o.onModuleLoaded=function(h){d({draco:h})},DracoDecoderModule(o)});break;case"decode":const a=c.buffer,l=c.taskConfig;e.then(d=>{const h=d.draco,m=new h.Decoder;try{const g=t(h,m,new Int8Array(a),l),T=g.attributes.map(b=>b.array.buffer);g.index&&T.push(g.index.array.buffer),self.postMessage({type:"decode",id:c.id,geometry:g},T)}catch(g){console.error(g),self.postMessage({type:"error",id:c.id,error:g.message})}finally{h.destroy(m)}});break}};function t(i,c,a,l){const d=l.attributeIDs,h=l.attributeTypes;let m,g;const T=c.GetEncodedGeometryType(a);if(T===i.TRIANGULAR_MESH)m=new i.Mesh,g=c.DecodeArrayToMesh(a,a.byteLength,m);else if(T===i.POINT_CLOUD)m=new i.PointCloud,g=c.DecodeArrayToPointCloud(a,a.byteLength,m);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!g.ok()||m.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+g.error_msg());const b={index:null,attributes:[]};for(const f in d){const p=self[h[f]];let y,w;if(l.useUniqueIDs)w=d[f],y=c.GetAttributeByUniqueId(m,w);else{if(w=c.GetAttributeId(m,i[d[f]]),w===-1)continue;y=c.GetAttribute(m,w)}const _=s(i,c,m,f,p,y);f==="color"&&(_.vertexColorSpace=l.vertexColorSpace),b.attributes.push(_)}return T===i.TRIANGULAR_MESH&&(b.index=n(i,c,m)),i.destroy(m),b}function n(i,c,a){const d=a.num_faces()*3,h=d*4,m=i._malloc(h);c.GetTrianglesUInt32Array(a,h,m);const g=new Uint32Array(i.HEAPF32.buffer,m,d).slice();return i._free(m),{array:g,itemSize:1}}function s(i,c,a,l,d,h){const m=h.num_components(),T=a.num_points()*m,b=T*d.BYTES_PER_ELEMENT,f=r(i,d),p=i._malloc(b);c.GetAttributeDataArrayForAllPoints(a,h,f,b,p);const y=new d(i.HEAPF32.buffer,p,T).slice();return i._free(p),{name:l,array:y,itemSize:m}}function r(i,c){switch(c){case Float32Array:return i.DT_FLOAT32;case Int8Array:return i.DT_INT8;case Int16Array:return i.DT_INT16;case Int32Array:return i.DT_INT32;case Uint8Array:return i.DT_UINT8;case Uint16Array:return i.DT_UINT16;case Uint32Array:return i.DT_UINT32}}}class rt extends u.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ht(t)}),this.register(function(t){return new ut(t)}),this.register(function(t){return new wt(t)}),this.register(function(t){return new bt(t)}),this.register(function(t){return new Et(t)}),this.register(function(t){return new ft(t)}),this.register(function(t){return new pt(t)}),this.register(function(t){return new mt(t)}),this.register(function(t){return new gt(t)}),this.register(function(t){return new lt(t)}),this.register(function(t){return new yt(t)}),this.register(function(t){return new dt(t)}),this.register(function(t){return new Tt(t)}),this.register(function(t){return new _t(t)}),this.register(function(t){return new at(t)}),this.register(function(t){return new St(t)}),this.register(function(t){return new Mt(t)})}load(e,t,n,s){const r=this;let i;if(this.resourcePath!=="")i=this.resourcePath;else if(this.path!==""){const l=u.LoaderUtils.extractUrlBase(e);i=u.LoaderUtils.resolveURL(l,this.path)}else i=u.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const c=function(l){s?s(l):console.error(l),r.manager.itemError(e),r.manager.itemEnd(e)},a=new u.FileLoader(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(l){try{r.parse(l,i,function(d){t(d),r.manager.itemEnd(e)},c)}catch(d){c(d)}},n,c)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const i={},c={},a=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(a.decode(new Uint8Array(e,0,4))===ke){try{i[E.KHR_BINARY_GLTF]=new xt(e)}catch(h){s&&s(h);return}r=JSON.parse(i[E.KHR_BINARY_GLTF].content)}else r=JSON.parse(a.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new Ft(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](l);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),c[h.name]=h,i[h.name]=!0}if(r.extensionsUsed)for(let d=0;d<r.extensionsUsed.length;++d){const h=r.extensionsUsed[d],m=r.extensionsRequired||[];switch(h){case E.KHR_MATERIALS_UNLIT:i[h]=new ct;break;case E.KHR_DRACO_MESH_COMPRESSION:i[h]=new Rt(r,this.dracoLoader);break;case E.KHR_TEXTURE_TRANSFORM:i[h]=new At;break;case E.KHR_MESH_QUANTIZATION:i[h]=new Lt;break;default:m.indexOf(h)>=0&&c[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}l.setExtensions(i),l.setPlugins(c),l.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function ot(){let o={};return{get:function(e){return o[e]},add:function(e,t){o[e]=t},remove:function(e){delete o[e]},removeAll:function(){o={}}}}const E={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class at{constructor(e){this.parser=e,this.name=E.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,a=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let l;const d=new u.Color(16777215);a.color!==void 0&&d.setRGB(a.color[0],a.color[1],a.color[2],u.LinearSRGBColorSpace);const h=a.range!==void 0?a.range:0;switch(a.type){case"directional":l=new u.DirectionalLight(d),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new u.PointLight(d),l.distance=h;break;case"spot":l=new u.SpotLight(d),l.distance=h,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,l.angle=a.spot.outerConeAngle,l.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return l.position.set(0,0,0),j(l,a),a.intensity!==void 0&&(l.intensity=a.intensity),l.name=t.createUniqueName(a.name||"light_"+e),s=Promise.resolve(l),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],c=(r.extensions&&r.extensions[this.name]||{}).light;return c===void 0?null:this._loadLight(c).then(function(a){return n._getNodeRef(t.cache,c,a)})}}class ct{constructor(){this.name=E.KHR_MATERIALS_UNLIT}getMaterialType(){return u.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new u.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const i=r.baseColorFactor;e.color.setRGB(i[0],i[1],i[2],u.LinearSRGBColorSpace),e.opacity=i[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,u.SRGBColorSpace))}return Promise.all(s)}}class lt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}}class ht{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(r.push(n.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){const c=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new u.Vector2(c,c)}return Promise.all(r)}}class ut{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name];return t.dispersion=r.dispersion!==void 0?r.dispersion:0,Promise.resolve()}}class dt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(r)}}class ft{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[];t.sheenColor=new u.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const i=s.extensions[this.name];if(i.sheenColorFactor!==void 0){const c=i.sheenColorFactor;t.sheenColor.setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&r.push(n.assignTexture(t,"sheenColorMap",i.sheenColorTexture,u.SRGBColorSpace)),i.sheenRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(r)}}class pt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&r.push(n.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(r)}}class mt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&r.push(n.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const c=i.attenuationColor||[1,1,1];return t.attenuationColor=new u.Color().setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace),Promise.all(r)}}class gt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name];return t.ior=r.ior!==void 0?r.ior:1.5,Promise.resolve()}}class yt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&r.push(n.assignTexture(t,"specularIntensityMap",i.specularTexture));const c=i.specularColorFactor||[1,1,1];return t.specularColor=new u.Color().setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace),i.specularColorTexture!==void 0&&r.push(n.assignTexture(t,"specularColorMap",i.specularColorTexture,u.SRGBColorSpace)),Promise.all(r)}}class _t{constructor(e){this.parser=e,this.name=E.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&r.push(n.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(r)}}class Tt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],i=s.extensions[this.name];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&r.push(n.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(r)}}class wt{constructor(e){this.parser=e,this.name=E.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],i=t.options.ktx2Loader;if(!i){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,i)}}class bt{constructor(e){this.parser=e,this.name=E.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const i=r.extensions[t],c=s.images[i.source];let a=n.textureLoader;if(c.uri){const l=n.options.manager.getHandler(c.uri);l!==null&&(a=l)}return n.loadTextureImage(e,i.source,a)}}class Et{constructor(e){this.parser=e,this.name=E.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const i=r.extensions[t],c=s.images[i.source];let a=n.textureLoader;if(c.uri){const l=n.options.manager.getHandler(c.uri);l!==null&&(a=l)}return n.loadTextureImage(e,i.source,a)}}class St{constructor(e){this.name=E.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(c){const a=s.byteOffset||0,l=s.byteLength||0,d=s.count,h=s.byteStride,m=new Uint8Array(c,a,l);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(d,h,m,s.mode,s.filter).then(function(g){return g.buffer}):i.ready.then(function(){const g=new ArrayBuffer(d*h);return i.decodeGltfBuffer(new Uint8Array(g),d,h,m,s.mode,s.filter),g})})}else return null}}class Mt{constructor(e){this.name=E.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 l of s.primitives)if(l.mode!==I.TRIANGLES&&l.mode!==I.TRIANGLE_STRIP&&l.mode!==I.TRIANGLE_FAN&&l.mode!==void 0)return null;const i=n.extensions[this.name].attributes,c=[],a={};for(const l in i)c.push(this.parser.getDependency("accessor",i[l]).then(d=>(a[l]=d,a[l])));return c.length<1?null:(c.push(this.parser.createNodeMesh(e)),Promise.all(c).then(l=>{const d=l.pop(),h=d.isGroup?d.children:[d],m=l[0].count,g=[];for(const T of h){const b=new u.Matrix4,f=new u.Vector3,p=new u.Quaternion,y=new u.Vector3(1,1,1),w=new u.InstancedMesh(T.geometry,T.material,m);for(let _=0;_<m;_++)a.TRANSLATION&&f.fromBufferAttribute(a.TRANSLATION,_),a.ROTATION&&p.fromBufferAttribute(a.ROTATION,_),a.SCALE&&y.fromBufferAttribute(a.SCALE,_),w.setMatrixAt(_,b.compose(f,p,y));for(const _ in a)if(_==="_COLOR_0"){const S=a[_];w.instanceColor=new u.InstancedBufferAttribute(S.array,S.itemSize,S.normalized)}else _!=="TRANSLATION"&&_!=="ROTATION"&&_!=="SCALE"&&T.geometry.setAttribute(_,a[_]);u.Object3D.prototype.copy.call(w,T),this.parser.assignFinalMaterial(w),g.push(w)}return d.isGroup?(d.clear(),d.add(...g),d):g[0]}))}}const ke="glTF",Z=12,Me={JSON:1313821514,BIN:5130562};class xt{constructor(e){this.name=E.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Z),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!==ke)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-Z,r=new DataView(e,Z);let i=0;for(;i<s;){const c=r.getUint32(i,!0);i+=4;const a=r.getUint32(i,!0);if(i+=4,a===Me.JSON){const l=new Uint8Array(e,Z+i,c);this.content=n.decode(l)}else if(a===Me.BIN){const l=Z+i;this.body=e.slice(l,l+c)}i+=c}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Rt{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=E.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,i=e.extensions[this.name].attributes,c={},a={},l={};for(const d in i){const h=me[d]||d.toLowerCase();c[h]=i[d]}for(const d in e.attributes){const h=me[d]||d.toLowerCase();if(i[d]!==void 0){const m=n.accessors[e.attributes[d]],g=Y[m.componentType];l[h]=g.name,a[h]=m.normalized===!0}}return t.getDependency("bufferView",r).then(function(d){return new Promise(function(h,m){s.decodeDracoFile(d,function(g){for(const T in g.attributes){const b=g.attributes[T],f=a[T];f!==void 0&&(b.normalized=f)}h(g)},c,l,u.LinearSRGBColorSpace,m)})})}}class At{constructor(){this.name=E.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 Lt{constructor(){this.name=E.KHR_MESH_QUANTIZATION}}class Ne extends u.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let i=0;i!==s;i++)t[i]=n[r+i];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,i=this.sampleValues,c=this.valueSize,a=c*2,l=c*3,d=s-t,h=(n-t)/d,m=h*h,g=m*h,T=e*l,b=T-l,f=-2*g+3*m,p=g-m,y=1-f,w=p-m+h;for(let _=0;_!==c;_++){const S=i[b+_+c],M=i[b+_+a]*d,A=i[T+_+c],D=i[T+_]*d;r[_]=y*S+w*M+f*A+p*D}return r}}const Ct=new u.Quaternion;class Dt extends Ne{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return Ct.fromArray(r).normalize().toArray(r),r}}const I={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Y={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},xe={9728:u.NearestFilter,9729:u.LinearFilter,9984:u.NearestMipmapNearestFilter,9985:u.LinearMipmapNearestFilter,9986:u.NearestMipmapLinearFilter,9987:u.LinearMipmapLinearFilter},Re={33071:u.ClampToEdgeWrapping,33648:u.MirroredRepeatWrapping,10497:u.RepeatWrapping},he={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},me={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"},B={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Pt={CUBICSPLINE:void 0,LINEAR:u.InterpolateLinear,STEP:u.InterpolateDiscrete},ue={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Ot(o){return o.DefaultMaterial===void 0&&(o.DefaultMaterial=new u.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:u.FrontSide})),o.DefaultMaterial}function V(o,e,t){for(const n in t.extensions)o[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function j(o,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(o.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function It(o,e,t){let n=!1,s=!1,r=!1;for(let l=0,d=e.length;l<d;l++){const h=e[l];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(o);const i=[],c=[],a=[];for(let l=0,d=e.length;l<d;l++){const h=e[l];if(n){const m=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):o.attributes.position;i.push(m)}if(s){const m=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):o.attributes.normal;c.push(m)}if(r){const m=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):o.attributes.color;a.push(m)}}return Promise.all([Promise.all(i),Promise.all(c),Promise.all(a)]).then(function(l){const d=l[0],h=l[1],m=l[2];return n&&(o.morphAttributes.position=d),s&&(o.morphAttributes.normal=h),r&&(o.morphAttributes.color=m),o.morphTargetsRelative=!0,o})}function kt(o,e){if(o.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)o.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(o.morphTargetInfluences.length===t.length){o.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)o.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Nt(o){let e;const t=o.extensions&&o.extensions[E.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+de(t.attributes):e=o.indices+":"+de(o.attributes)+":"+o.mode,o.targets!==void 0)for(let n=0,s=o.targets.length;n<s;n++)e+=":"+de(o.targets[n]);return e}function de(o){let e="";const t=Object.keys(o).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+o[t[n]]+";";return e}function ge(o){switch(o){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 vt(o){return o.search(/\.jpe?g($|\?)/i)>0||o.search(/^data\:image\/jpeg/)===0?"image/jpeg":o.search(/\.webp($|\?)/i)>0||o.search(/^data\:image\/webp/)===0?"image/webp":o.search(/\.ktx2($|\?)/i)>0||o.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Ht=new u.Matrix4;class Ft{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new ot,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,i=-1;if(typeof navigator<"u"){const c=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(c)===!0;const a=c.match(/Version\/(\d+)/);s=n&&a?parseInt(a[1],10):-1,r=c.indexOf("Firefox")>-1,i=r?c.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&i<98?this.textureLoader=new u.TextureLoader(this.options.manager):this.textureLoader=new u.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new u.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(i){return i._markDefs&&i._markDefs()}),Promise.all(this._invokeAll(function(i){return i.beforeRoot&&i.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(i){const c={scene:i[0][s.scene||0],scenes:i[0],animations:i[1],cameras:i[2],asset:s.asset,parser:n,userData:{}};return V(r,c,s),j(c,s),Promise.all(n._invokeAll(function(a){return a.afterRoot&&a.afterRoot(c)})).then(function(){for(const a of c.scenes)a.updateMatrixWorld();e(c)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const i=t[s].joints;for(let c=0,a=i.length;c<a;c++)e[i[c]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const i=e[s];i.mesh!==void 0&&(this._addNodeRef(this.meshCache,i.mesh),i.skin!==void 0&&(n[i.mesh].isSkinnedMesh=!0)),i.camera!==void 0&&this._addNodeRef(this.cameraCache,i.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(i,c)=>{const a=this.associations.get(i);a!=null&&this.associations.set(c,a);for(const[l,d]of i.children.entries())r(d,c.children[l])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,i){return n.getDependency(e,i)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[E.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,i){n.load(u.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){i(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const i=he[s.type],c=Y[s.componentType],a=s.normalized===!0,l=new c(s.count*i);return Promise.resolve(new u.BufferAttribute(l,i,a))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(i){const c=i[0],a=he[s.type],l=Y[s.componentType],d=l.BYTES_PER_ELEMENT,h=d*a,m=s.byteOffset||0,g=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,T=s.normalized===!0;let b,f;if(g&&g!==h){const p=Math.floor(m/g),y="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+p+":"+s.count;let w=t.cache.get(y);w||(b=new l(c,p*g,s.count*g/d),w=new u.InterleavedBuffer(b,g/d),t.cache.add(y,w)),f=new u.InterleavedBufferAttribute(w,a,m%g/d,T)}else c===null?b=new l(s.count*a):b=new l(c,m,s.count*a),f=new u.BufferAttribute(b,a,T);if(s.sparse!==void 0){const p=he.SCALAR,y=Y[s.sparse.indices.componentType],w=s.sparse.indices.byteOffset||0,_=s.sparse.values.byteOffset||0,S=new y(i[1],w,s.sparse.count*p),M=new l(i[2],_,s.sparse.count*a);c!==null&&(f=new u.BufferAttribute(f.array.slice(),f.itemSize,f.normalized)),f.normalized=!1;for(let A=0,D=S.length;A<D;A++){const P=S[A];if(f.setX(P,M[A*a]),a>=2&&f.setY(P,M[A*a+1]),a>=3&&f.setZ(P,M[A*a+2]),a>=4&&f.setW(P,M[A*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}f.normalized=T}return f})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r];let c=this.textureLoader;if(i.uri){const a=n.manager.getHandler(i.uri);a!==null&&(c=a)}return this.loadTextureImage(e,r,c)}loadTextureImage(e,t,n){const s=this,r=this.json,i=r.textures[e],c=r.images[t],a=(c.uri||c.bufferView)+":"+i.sampler;if(this.textureCache[a])return this.textureCache[a];const l=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=i.name||c.name||"",d.name===""&&typeof c.uri=="string"&&c.uri.startsWith("data:image/")===!1&&(d.name=c.uri);const m=(r.samplers||{})[i.sampler]||{};return d.magFilter=xe[m.magFilter]||u.LinearFilter,d.minFilter=xe[m.minFilter]||u.LinearMipmapLinearFilter,d.wrapS=Re[m.wrapS]||u.RepeatWrapping,d.wrapT=Re[m.wrapT]||u.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==u.NearestFilter&&d.minFilter!==u.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[a]=l,l}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const i=s.images[e],c=self.URL||self.webkitURL;let a=i.uri||"",l=!1;if(i.bufferView!==void 0)a=n.getDependency("bufferView",i.bufferView).then(function(h){l=!0;const m=new Blob([h],{type:i.mimeType});return a=c.createObjectURL(m),a});else if(i.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(a).then(function(h){return new Promise(function(m,g){let T=m;t.isImageBitmapLoader===!0&&(T=function(b){const f=new u.Texture(b);f.needsUpdate=!0,m(f)}),t.load(u.LoaderUtils.resolveURL(h,r.path),T,void 0,g)})}).then(function(h){return l===!0&&c.revokeObjectURL(a),j(h,i),h.userData.mimeType=i.mimeType||vt(i.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(i){if(!i)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(i=i.clone(),i.channel=n.texCoord),r.extensions[E.KHR_TEXTURE_TRANSFORM]){const c=n.extensions!==void 0?n.extensions[E.KHR_TEXTURE_TRANSFORM]:void 0;if(c){const a=r.associations.get(i);i=r.extensions[E.KHR_TEXTURE_TRANSFORM].extendTexture(i,c),r.associations.set(i,a)}}return s!==void 0&&(i.colorSpace=s),e[t]=i,i})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,i=t.attributes.normal===void 0;if(e.isPoints){const c="PointsMaterial:"+n.uuid;let a=this.cache.get(c);a||(a=new u.PointsMaterial,u.Material.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,a.sizeAttenuation=!1,this.cache.add(c,a)),n=a}else if(e.isLine){const c="LineBasicMaterial:"+n.uuid;let a=this.cache.get(c);a||(a=new u.LineBasicMaterial,u.Material.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,this.cache.add(c,a)),n=a}if(s||r||i){let c="ClonedMaterial:"+n.uuid+":";s&&(c+="derivative-tangents:"),r&&(c+="vertex-colors:"),i&&(c+="flat-shading:");let a=this.cache.get(c);a||(a=n.clone(),r&&(a.vertexColors=!0),i&&(a.flatShading=!0),s&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(c,a),this.associations.set(a,this.associations.get(n))),n=a}e.material=n}getMaterialType(){return u.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let i;const c={},a=r.extensions||{},l=[];if(a[E.KHR_MATERIALS_UNLIT]){const h=s[E.KHR_MATERIALS_UNLIT];i=h.getMaterialType(),l.push(h.extendParams(c,r,t))}else{const h=r.pbrMetallicRoughness||{};if(c.color=new u.Color(1,1,1),c.opacity=1,Array.isArray(h.baseColorFactor)){const m=h.baseColorFactor;c.color.setRGB(m[0],m[1],m[2],u.LinearSRGBColorSpace),c.opacity=m[3]}h.baseColorTexture!==void 0&&l.push(t.assignTexture(c,"map",h.baseColorTexture,u.SRGBColorSpace)),c.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,c.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(c,"metalnessMap",h.metallicRoughnessTexture)),l.push(t.assignTexture(c,"roughnessMap",h.metallicRoughnessTexture))),i=this._invokeOne(function(m){return m.getMaterialType&&m.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(m){return m.extendMaterialParams&&m.extendMaterialParams(e,c)})))}r.doubleSided===!0&&(c.side=u.DoubleSide);const d=r.alphaMode||ue.OPAQUE;if(d===ue.BLEND?(c.transparent=!0,c.depthWrite=!1):(c.transparent=!1,d===ue.MASK&&(c.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&i!==u.MeshBasicMaterial&&(l.push(t.assignTexture(c,"normalMap",r.normalTexture)),c.normalScale=new u.Vector2(1,1),r.normalTexture.scale!==void 0)){const h=r.normalTexture.scale;c.normalScale.set(h,h)}if(r.occlusionTexture!==void 0&&i!==u.MeshBasicMaterial&&(l.push(t.assignTexture(c,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(c.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&i!==u.MeshBasicMaterial){const h=r.emissiveFactor;c.emissive=new u.Color().setRGB(h[0],h[1],h[2],u.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&i!==u.MeshBasicMaterial&&l.push(t.assignTexture(c,"emissiveMap",r.emissiveTexture,u.SRGBColorSpace)),Promise.all(l).then(function(){const h=new i(c);return r.name&&(h.name=r.name),j(h,r),t.associations.set(h,{materials:e}),r.extensions&&V(s,h,r),h})}createUniqueName(e){const t=u.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(c){return n[E.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(c,t).then(function(a){return Ae(a,c,t)})}const i=[];for(let c=0,a=e.length;c<a;c++){const l=e[c],d=Nt(l),h=s[d];if(h)i.push(h.promise);else{let m;l.extensions&&l.extensions[E.KHR_DRACO_MESH_COMPRESSION]?m=r(l):m=Ae(new u.BufferGeometry,l,t),s[d]={primitive:l,promise:m},i.push(m)}}return Promise.all(i)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],i=r.primitives,c=[];for(let a=0,l=i.length;a<l;a++){const d=i[a].material===void 0?Ot(this.cache):this.getDependency("material",i[a].material);c.push(d)}return c.push(t.loadGeometries(i)),Promise.all(c).then(function(a){const l=a.slice(0,a.length-1),d=a[a.length-1],h=[];for(let g=0,T=d.length;g<T;g++){const b=d[g],f=i[g];let p;const y=l[g];if(f.mode===I.TRIANGLES||f.mode===I.TRIANGLE_STRIP||f.mode===I.TRIANGLE_FAN||f.mode===void 0)p=r.isSkinnedMesh===!0?new u.SkinnedMesh(b,y):new u.Mesh(b,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),f.mode===I.TRIANGLE_STRIP?p.geometry=Se(p.geometry,u.TriangleStripDrawMode):f.mode===I.TRIANGLE_FAN&&(p.geometry=Se(p.geometry,u.TriangleFanDrawMode));else if(f.mode===I.LINES)p=new u.LineSegments(b,y);else if(f.mode===I.LINE_STRIP)p=new u.Line(b,y);else if(f.mode===I.LINE_LOOP)p=new u.LineLoop(b,y);else if(f.mode===I.POINTS)p=new u.Points(b,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+f.mode);Object.keys(p.geometry.morphAttributes).length>0&&kt(p,r),p.name=t.createUniqueName(r.name||"mesh_"+e),j(p,r),f.extensions&&V(s,p,f),t.assignFinalMaterial(p),h.push(p)}for(let g=0,T=h.length;g<T;g++)t.associations.set(h[g],{meshes:e,primitives:g});if(h.length===1)return r.extensions&&V(s,h[0],r),h[0];const m=new u.Group;r.extensions&&V(s,m,r),t.associations.set(m,{meshes:e});for(let g=0,T=h.length;g<T;g++)m.add(h[g]);return m})}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 u.PerspectiveCamera(u.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new u.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),j(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),i=s,c=[],a=[];for(let l=0,d=i.length;l<d;l++){const h=i[l];if(h){c.push(h);const m=new u.Matrix4;r!==null&&m.fromArray(r.array,l*16),a.push(m)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new u.Skeleton(c,a)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,i=[],c=[],a=[],l=[],d=[];for(let h=0,m=s.channels.length;h<m;h++){const g=s.channels[h],T=s.samplers[g.sampler],b=g.target,f=b.node,p=s.parameters!==void 0?s.parameters[T.input]:T.input,y=s.parameters!==void 0?s.parameters[T.output]:T.output;b.node!==void 0&&(i.push(this.getDependency("node",f)),c.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",y)),l.push(T),d.push(b))}return Promise.all([Promise.all(i),Promise.all(c),Promise.all(a),Promise.all(l),Promise.all(d)]).then(function(h){const m=h[0],g=h[1],T=h[2],b=h[3],f=h[4],p=[];for(let y=0,w=m.length;y<w;y++){const _=m[y],S=g[y],M=T[y],A=b[y],D=f[y];if(_===void 0)continue;_.updateMatrix&&_.updateMatrix();const P=n._createAnimationTracks(_,S,M,A,D);if(P)for(let G=0;G<P.length;G++)p.push(P[G])}return new u.AnimationClip(r,void 0,p)})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const i=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&i.traverse(function(c){if(c.isMesh)for(let a=0,l=s.weights.length;a<l;a++)c.morphTargetInfluences[a]=s.weights[a]}),i})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),i=[],c=s.children||[];for(let l=0,d=c.length;l<d;l++)i.push(n.getDependency("node",c[l]));const a=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(i),a]).then(function(l){const d=l[0],h=l[1],m=l[2];m!==null&&d.traverse(function(g){g.isSkinnedMesh&&g.bind(m,Ht)});for(let g=0,T=h.length;g<T;g++)d.add(h[g]);return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],i=r.name?s.createUniqueName(r.name):"",c=[],a=s._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return a&&c.push(a),r.camera!==void 0&&c.push(s.getDependency("camera",r.camera).then(function(l){return s._getNodeRef(s.cameraCache,r.camera,l)})),s._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){c.push(l)}),this.nodeCache[e]=Promise.all(c).then(function(l){let d;if(r.isBone===!0?d=new u.Bone:l.length>1?d=new u.Group:l.length===1?d=l[0]:d=new u.Object3D,d!==l[0])for(let h=0,m=l.length;h<m;h++)d.add(l[h]);if(r.name&&(d.userData.name=r.name,d.name=i),j(d,r),r.extensions&&V(n,d,r),r.matrix!==void 0){const h=new u.Matrix4;h.fromArray(r.matrix),d.applyMatrix4(h)}else r.translation!==void 0&&d.position.fromArray(r.translation),r.rotation!==void 0&&d.quaternion.fromArray(r.rotation),r.scale!==void 0&&d.scale.fromArray(r.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const h=s.associations.get(d);s.associations.set(d,{...h})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new u.Group;n.name&&(r.name=s.createUniqueName(n.name)),j(r,n),n.extensions&&V(t,r,n);const i=n.nodes||[],c=[];for(let a=0,l=i.length;a<l;a++)c.push(s.getDependency("node",i[a]));return Promise.all(c).then(function(a){for(let d=0,h=a.length;d<h;d++)r.add(a[d]);const l=d=>{const h=new Map;for(const[m,g]of s.associations)(m instanceof u.Material||m instanceof u.Texture)&&h.set(m,g);return d.traverse(m=>{const g=s.associations.get(m);g!=null&&h.set(m,g)}),h};return s.associations=l(r),r})}_createAnimationTracks(e,t,n,s,r){const i=[],c=e.name?e.name:e.uuid,a=[];B[r.path]===B.weights?e.traverse(function(m){m.morphTargetInfluences&&a.push(m.name?m.name:m.uuid)}):a.push(c);let l;switch(B[r.path]){case B.weights:l=u.NumberKeyframeTrack;break;case B.rotation:l=u.QuaternionKeyframeTrack;break;case B.translation:case B.scale:l=u.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:l=u.NumberKeyframeTrack;break;case 2:case 3:default:l=u.VectorKeyframeTrack;break}break}const d=s.interpolation!==void 0?Pt[s.interpolation]:u.InterpolateLinear,h=this._getArrayFromAccessor(n);for(let m=0,g=a.length;m<g;m++){const T=new l(a[m]+"."+B[r.path],t.array,h,d);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(T),i.push(T)}return i}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=ge(t.constructor),s=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof u.QuaternionKeyframeTrack?Dt:Ne;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Ut(o,e,t){const n=e.attributes,s=new u.Box3;if(n.POSITION!==void 0){const c=t.json.accessors[n.POSITION],a=c.min,l=c.max;if(a!==void 0&&l!==void 0){if(s.set(new u.Vector3(a[0],a[1],a[2]),new u.Vector3(l[0],l[1],l[2])),c.normalized){const d=ge(Y[c.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const c=new u.Vector3,a=new u.Vector3;for(let l=0,d=r.length;l<d;l++){const h=r[l];if(h.POSITION!==void 0){const m=t.json.accessors[h.POSITION],g=m.min,T=m.max;if(g!==void 0&&T!==void 0){if(a.setX(Math.max(Math.abs(g[0]),Math.abs(T[0]))),a.setY(Math.max(Math.abs(g[1]),Math.abs(T[1]))),a.setZ(Math.max(Math.abs(g[2]),Math.abs(T[2]))),m.normalized){const b=ge(Y[m.componentType]);a.multiplyScalar(b)}c.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(c)}o.boundingBox=s;const i=new u.Sphere;s.getCenter(i.center),i.radius=s.min.distanceTo(s.max)/2,o.boundingSphere=i}function Ae(o,e,t){const n=e.attributes,s=[];function r(i,c){return t.getDependency("accessor",i).then(function(a){o.setAttribute(c,a)})}for(const i in n){const c=me[i]||i.toLowerCase();c in o.attributes||s.push(r(n[i],c))}if(e.indices!==void 0&&!o.index){const i=t.getDependency("accessor",e.indices).then(function(c){o.setIndex(c)});s.push(i)}return u.ColorManagement.workingColorSpace!==u.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${u.ColorManagement.workingColorSpace}" not supported.`),j(o,e),Ut(o,e,t),Promise.all(s).then(function(){return e.targets!==void 0?It(o,e.targets,t):o})}const Le=new u.Vector3,jt=new u.Quaternion,Ce=new u.Vector3;class Gt extends u.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS3DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.addEventListener("removed",function(){this.traverse(function(t){t.element instanceof t.element.ownerDocument.defaultView.Element&&t.element.parentNode!==null&&t.element.remove()})})}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this}}class Bt extends Gt{constructor(e){super(e),this.isCSS3DSprite=!0,this.rotation2D=0}copy(e,t){return super.copy(e,t),this.rotation2D=e.rotation2D,this}}const H=new u.Matrix4,zt=new u.Matrix4;class Kt{constructor(e={}){const t=this;let n,s,r,i;const c={camera:{style:""},objects:new WeakMap},a=e.element!==void 0?e.element:document.createElement("div");a.style.overflow="hidden",this.domElement=a;const l=document.createElement("div");l.style.transformOrigin="0 0",l.style.pointerEvents="none",a.appendChild(l);const d=document.createElement("div");d.style.transformStyle="preserve-3d",l.appendChild(d),this.getSize=function(){return{width:n,height:s}},this.render=function(f,p){const y=p.projectionMatrix.elements[5]*i;p.view&&p.view.enabled?(l.style.transform=`translate( ${-p.view.offsetX*(n/p.view.width)}px, ${-p.view.offsetY*(s/p.view.height)}px )`,l.style.transform+=`scale( ${p.view.fullWidth/p.view.width}, ${p.view.fullHeight/p.view.height} )`):l.style.transform="",f.matrixWorldAutoUpdate===!0&&f.updateMatrixWorld(),p.parent===null&&p.matrixWorldAutoUpdate===!0&&p.updateMatrixWorld();let w,_;p.isOrthographicCamera&&(w=-(p.right+p.left)/2,_=(p.top+p.bottom)/2);const S=p.view&&p.view.enabled?p.view.height/p.view.fullHeight:1,M=p.isOrthographicCamera?`scale( ${S} )scale(`+y+")translate("+h(w)+"px,"+h(_)+"px)"+m(p.matrixWorldInverse):`scale( ${S} )translateZ(`+y+"px)"+m(p.matrixWorldInverse),D=(p.isPerspectiveCamera?"perspective("+y+"px) ":"")+M+"translate("+r+"px,"+i+"px)";c.camera.style!==D&&(d.style.transform=D,c.camera.style=D),b(f,f,p)},this.setSize=function(f,p){n=f,s=p,r=n/2,i=s/2,a.style.width=f+"px",a.style.height=p+"px",l.style.width=f+"px",l.style.height=p+"px",d.style.width=f+"px",d.style.height=p+"px"};function h(f){return Math.abs(f)<1e-10?0:f}function m(f){const p=f.elements;return"matrix3d("+h(p[0])+","+h(-p[1])+","+h(p[2])+","+h(p[3])+","+h(p[4])+","+h(-p[5])+","+h(p[6])+","+h(p[7])+","+h(p[8])+","+h(-p[9])+","+h(p[10])+","+h(p[11])+","+h(p[12])+","+h(-p[13])+","+h(p[14])+","+h(p[15])+")"}function g(f){const p=f.elements;return"translate(-50%,-50%)"+("matrix3d("+h(p[0])+","+h(p[1])+","+h(p[2])+","+h(p[3])+","+h(-p[4])+","+h(-p[5])+","+h(-p[6])+","+h(-p[7])+","+h(p[8])+","+h(p[9])+","+h(p[10])+","+h(p[11])+","+h(p[12])+","+h(p[13])+","+h(p[14])+","+h(p[15])+")")}function T(f){f.isCSS3DObject&&(f.element.style.display="none");for(let p=0,y=f.children.length;p<y;p++)T(f.children[p])}function b(f,p,y,w){if(f.visible===!1){T(f);return}if(f.isCSS3DObject){const _=f.layers.test(y.layers)===!0,S=f.element;if(S.style.display=_===!0?"":"none",_===!0){f.onBeforeRender(t,p,y);let M;f.isCSS3DSprite?(H.copy(y.matrixWorldInverse),H.transpose(),f.rotation2D!==0&&H.multiply(zt.makeRotationZ(f.rotation2D)),f.matrixWorld.decompose(Le,jt,Ce),H.setPosition(Le),H.scale(Ce),H.elements[3]=0,H.elements[7]=0,H.elements[11]=0,H.elements[15]=1,M=g(H)):M=g(f.matrixWorld);const A=c.objects.get(f);if(A===void 0||A.style!==M){S.style.transform=M;const D={style:M};c.objects.set(f,D)}S.parentNode!==d&&d.appendChild(S),f.onAfterRender(t,p,y)}}for(let _=0,S=f.children.length;_<S;_++)b(f.children[_],p,y)}}}var $=function(){var o=0,e=document.createElement("div");e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",function(d){d.preventDefault(),n(++o%e.children.length)},!1);function t(d){return e.appendChild(d.dom),d}function n(d){for(var h=0;h<e.children.length;h++)e.children[h].style.display=h===d?"block":"none";o=d}var s=(performance||Date).now(),r=s,i=0,c=t(new $.Panel("FPS","#0ff","#002")),a=t(new $.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var l=t(new $.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:e,addPanel:t,showPanel:n,begin:function(){s=(performance||Date).now()},end:function(){i++;var d=(performance||Date).now();if(a.update(d-s,200),d>=r+1e3&&(c.update(i*1e3/(d-r),100),r=d,i=0,l)){var h=performance.memory;l.update(h.usedJSHeapSize/1048576,h.jsHeapSizeLimit/1048576)}return d},update:function(){s=this.end()},domElement:e,setMode:n}};$.Panel=function(o,e,t){var n=1/0,s=0,r=Math.round,i=r(window.devicePixelRatio||1),c=80*i,a=48*i,l=3*i,d=2*i,h=3*i,m=15*i,g=74*i,T=30*i,b=document.createElement("canvas");b.width=c,b.height=a,b.style.cssText="width:80px;height:48px";var f=b.getContext("2d");return f.font="bold "+9*i+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=t,f.fillRect(0,0,c,a),f.fillStyle=e,f.fillText(o,l,d),f.fillRect(h,m,g,T),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(h,m,g,T),{dom:b,update:function(p,y){n=Math.min(n,p),s=Math.max(s,p),f.fillStyle=t,f.globalAlpha=1,f.fillRect(0,0,c,m),f.fillStyle=e,f.fillText(r(p)+" "+o+" ("+r(n)+"-"+r(s)+")",l,d),f.drawImage(b,h+i,m,g-i,T,h,m,g-i,T),f.fillRect(h+g-i,m,i,T),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(h+g-i,m,i,r((1-p/y)*T))}}};function Vt(o){return new u.CameraHelper(o)}function Wt(o=150,...e){return new u.GridHelper(o,o/10,...e)}function Xt(o){return new u.BoxHelper(o,16776960)}function Yt(o,e){return new Ie(o,e)}function $t(o,e){return new st(o,e)}function qt(){const o=new u.Raycaster,e=new u.Vector2(0,0);return{raycaster:o,pointer:e}}function Zt(o=10){return new u.AxesHelper(o)}function Qt(o=new u.Vector3(1,1,1),e=new u.Vector3(10,10,10),t=5,n=16776960){return o.normalize(),new u.ArrowHelper(o,e,t,n)}function Jt(){const o=new $;return o.dom.style.cssText="position:absolute;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",o}const ve=o=>{o.geometry&&o.geometry.dispose(),o.material&&(Array.isArray(o.material)?o.material.forEach(e=>{De(e)}):De(o.material)),o.children&&o.children.forEach(e=>ve(e))};function De(o){for(const e in o)o[e]&&o[e].isTexture&&o[e].dispose();o.dispose()}const fe={};async function es(o,e=50){const t={type:o.type,name:o.name,position:o.position.toArray(),rotation:o.rotation.toArray(),scale:o.scale.toArray(),visible:o.visible,children:[],geometry:null,material:null,userData:o.userData};o.isMesh&&(t.geometry=ne(o.geometry),t.material=re(o.material));const n=[{object:o,parentData:t}];let s=0;for(;n.length>0;){const{object:r,parentData:i}=n.pop();for(const c of r.children){const a={type:c.type,name:c.name,position:c.position.toArray(),rotation:c.rotation.toArray(),scale:c.scale.toArray(),visible:c.visible,children:[],geometry:null,material:null,userData:c.userData};c.isMesh&&(a.geometry=ne(c.geometry),a.material=re(c.material)),i.children.push(a),n.push({object:c,parentData:a}),s++,s%e===0&&await new Promise(l=>requestAnimationFrame(l))}}return t}function ts(o){const e={type:o.type,name:o.name,position:o.position.toArray(),rotation:o.rotation.toArray(),scale:o.scale.toArray(),visible:o.visible,children:[],geometry:null,material:null,userData:o.userData};o.isMesh&&(e.geometry=ne(o.geometry),e.material=re(o.material));const t=[{object:o,parentData:e}];for(;t.length>0;){const{object:n,parentData:s}=t.pop();for(const r of n.children){const i={type:r.type,name:r.name,position:r.position.toArray(),rotation:r.rotation.toArray(),scale:r.scale.toArray(),visible:r.visible,children:[],geometry:null,material:null,userData:r.userData};r.isMesh&&(i.geometry=ne(r.geometry),i.material=re(r.material)),s.children.push(i),t.push({object:r,parentData:i})}}return e}async function He(o,e=50){const t=[];let n;switch(o.type){case"Mesh":const r=ie(o.geometry),i=oe(o.material);n=new x.Mesh(r,i);break;case"Group":n=new x.Group;break;case"Object3D":n=new x.Object3D;break;default:return console.warn(`Unsupported object type: ${o.type}`),null}n.name=o.name,n.position.fromArray(o.position),n.rotation.fromArray(o.rotation),n.scale.fromArray(o.scale),n.visible=o.visible,n.userData=o.userData,t.push({data:o,object:n});let s=0;for(;t.length>0;){const{data:r,object:i}=t.pop();for(const c of[...r.children].reverse()){let a;switch(c.type){case"Mesh":const l=ie(c.geometry),d=oe(c.material);a=new x.Mesh(l,d);break;case"Group":a=new x.Group;break;case"Object3D":a=new x.Object3D;break;default:console.warn(`Unsupported object type: ${c.type}`);continue}a&&(a.name=c.name,a.position.fromArray(c.position),a.rotation.fromArray(c.rotation),a.scale.fromArray(c.scale),a.visible=c.visible,a.userData=c.userData,i.add(a),t.push({data:c,object:a}),s++,s%e===0&&await new Promise(l=>requestAnimationFrame(l)))}}return n}function ss(o){const e=[];let t;switch(o.type){case"Mesh":const n=ie(o.geometry),s=oe(o.material);t=new x.Mesh(n,s);break;case"Group":t=new x.Group;break;case"Object3D":t=new x.Object3D;break;default:return console.warn(`Unsupported object type: ${o.type}`),null}for(t.name=o.name,t.position.fromArray(o.position),t.rotation.fromArray(o.rotation),t.scale.fromArray(o.scale),t.visible=o.visible,t.userData=o.userData,e.push({data:o,object:t});e.length>0;){const{data:n,object:s}=e.pop();for(const r of[...n.children].reverse()){let i;switch(r.type){case"Mesh":const c=ie(r.geometry),a=oe(r.material);i=new x.Mesh(c,a);break;case"Group":i=new x.Group;break;case"Object3D":i=new x.Object3D;break;default:console.warn(`Unsupported object type: ${r.type}`);continue}i&&(i.name=r.name,i.position.fromArray(r.position),i.rotation.fromArray(r.rotation),i.scale.fromArray(r.scale),i.visible=r.visible,i.userData=r.userData,s.add(i),e.push({data:r,object:i}))}}return t}function ne(o){const e={},{attributes:t,index:n,type:s}=o;t.position&&(e.position={type:"Float32Array",array:Array.from(t.position.array),itemSize:3}),t.normal&&(e.normal={type:"Float32Array",array:Array.from(t.normal.array),itemSize:3}),t.uv&&(e.uv={type:"Float32Array",array:Array.from(t.uv.array),itemSize:2});const r={type:s,attributes:e};return n&&n.array&&(r.index={type:"Uint32Array",array:Array.from(n.array),itemSize:1}),r}function ie(o){const{type:e,attributes:t,index:n}=o,s=new x.BufferGeometry;for(const r in t)if(t.hasOwnProperty(r)){const{type:i,array:c,itemSize:a}=t[r];s.setAttribute(r,new x.BufferAttribute(new Float32Array(c),a))}return n&&s.setIndex(n.array),s}function re(o){return{type:o.type,color:o.color.getHex(),map:o.map?o.map.image.src:null,opacity:o.opacity,name:o.name,depthTest:o.depthTest,depthWrite:o.depthWrite,transparent:o.transparent,side:o.side,roughness:o.roughness,metalness:o.metalness,emissive:o.emissive.getHex()}}function oe(o){if(fe[o.name])return fe[o.name];const{type:e,...t}=o,n=e||"MeshStandardMaterial",s=new x[n]({...t});if(o.map){const r=new x.TextureLoader().load(o.map);s.map=r}return s.needsUpdate=!0,fe[o.name]=s,s}class Fe{constructor(){this.stats={hits:0,misses:0,totalLoadTime:0,cacheSaveTime:0,errors:0},this.loadHistory=[]}recordHit(e){this.stats.hits++,this.stats.totalLoadTime+=e,this._recordHistory("hit",e)}recordMiss(e){this.stats.misses++,this.stats.totalLoadTime+=e,this._recordHistory("miss",e)}recordCacheSave(e){this.stats.cacheSaveTime+=e}recordError(e,t){this.stats.errors++,this._recordHistory("error",0,{path:e,error:t.message})}getHitRate(){const e=this.stats.hits+this.stats.misses;return e>0?(this.stats.hits/e*100).toFixed(2)+"%":"0%"}getAvgLoadTime(){const e=this.stats.hits+this.stats.misses;return e>0?(this.stats.totalLoadTime/e).toFixed(2)+"ms":"0ms"}getStats(){const e=this.stats.hits+this.stats.misses;return{命中率:this.getHitRate(),平均加载时间:this.getAvgLoadTime(),缓存命中数:this.stats.hits,缓存未命中数:this.stats.misses,总加载次数:e,总加载时间:this.stats.totalLoadTime.toFixed(2)+"ms",缓存保存时间:this.stats.cacheSaveTime.toFixed(2)+"ms",错误次数:this.stats.errors}}getHistory(e=10){return this.loadHistory.slice(-e)}reset(){this.stats={hits:0,misses:0,totalLoadTime:0,cacheSaveTime:0,errors:0},this.loadHistory=[]}_recordHistory(e,t,n={}){this.loadHistory.push({type:e,duration:t,timestamp:Date.now(),...n}),this.loadHistory.length>100&&this.loadHistory.shift()}logReport(){console.group("📊 缓存性能报告");const e=this.getStats();Object.entries(e).forEach(([t,n])=>{console.log(`${t}: ${n}`)}),console.groupEnd()}}const U=new Fe;class J{static async retry(e,t={}){const{maxRetries:n=3,initialDelay:s=1e3,maxDelay:r=1e4,backoffFactor:i=2,shouldRetry:c=J.defaultShouldRetry}=t;let a,l=s;for(let d=0;d<=n;d++)try{return await e()}catch(h){if(a=h,d===n||!c(h,d))throw h;console.warn(`[ RetryHelper ] 操作失败,第 ${d+1} 次尝试失败,${l}ms 后进行第 ${d+2} 次尝试...`,h),await J.delay(l),l=Math.min(l*i,r)}throw a}static defaultShouldRetry(e,t){if(e.name==="TypeError"&&e.message.includes("fetch"))return!0;if(e.message.includes("HTTP error")){const n=e.message.match(/status:\s*(\d+)/);if(n){const s=parseInt(n[1],10);return s>=500||s===429||s===408}}return!1}static delay(e){return new Promise(t=>setTimeout(t,e))}}const se={NETWORK:"NETWORK",PARSE:"PARSE",VERSION_MISMATCH:"VERSION",UNKNOWN:"UNKNOWN"};class q extends Error{constructor(e,t,n,s){super(e),this.name="ModelLoadError",this.type=t,this.path=n,this.originalError=s,this.timestamp=Date.now()}static networkError(e,t){return new q(`网络加载失败: ${e}`,se.NETWORK,e,t)}static parseError(e,t){return new q(`模型解析失败: ${e}`,se.PARSE,e,t)}static versionMismatchError(e,t,n){return new q(`版本不匹配: ${e} (期望: ${t}, 实际: ${n})`,se.VERSION_MISMATCH,e)}}const ns=5;class Q{constructor(e="threeJsIDBCache",t={}){this.version=ns,this.dbName=e,this.options={maxSize:t.maxSize||500*1024*1024,maxEntries:t.maxEntries||50,evictRatio:t.evictRatio||.2},this.dbInit()}dbInit(){this.db=new Ge(this.dbName),this.db.version(this.version).stores({models:"&path, version, timestamp, accessCount, size, format"}).upgrade(async e=>{console.log("[ IDBCache 版本更新 ] ====> 从旧版本升级到 v5");const t=e.table("models"),n=await t.toArray();console.log(`[ IDBCache ] 发现 ${n.length} 条旧缓存记录,开始验证...`);let s=0,r=0;for(const i of n)i.data instanceof ArrayBuffer?(await t.update(i.path,{format:"arraybuffer"}),s++):i.data&&typeof i.data=="object"?i.data.metadata||i.data.type==="Object3D"||i.data.uuid?(console.warn(`[ IDBCache ] 检测到旧版本序列化格式: ${i.path},标记为待删除`),await t.delete(i.path),r++):(console.warn(`[ IDBCache ] 检测到无法识别的数据格式: ${i.path},删除`),await t.delete(i.path),r++):(console.warn(`[ IDBCache ] 检测到无效数据: ${i.path},删除`),await t.delete(i.path),r++);console.log(`[ IDBCache ] 升级完成: 保留 ${s} 条,删除 ${r} 条旧格式记录`)})}getDatabase(){return this.db}async saveModel(e,t,n){if(!n||!(n instanceof ArrayBuffer))throw new Error(`[ IDBCache ] 无效的 ArrayBuffer: ${e}`);if(n.byteLength===0)throw new Error(`[ IDBCache ] ArrayBuffer 为空: ${e}`);await this.ensureCapacity(n.byteLength),await this.db.table("models").put({path:e,version:t,data:n,size:n.byteLength,timestamp:Date.now(),accessCount:0,format:"arraybuffer"})}async ensureCapacity(e){const t=await this.db.table("models").toArray(),n=t.reduce((c,a)=>c+(a.size||0),0),s=t.length,r=n+e>this.options.maxSize,i=s>=this.options.maxEntries;(r||i)&&(console.log(`[ IDBCache ] ====> 容量不足,开始 LRU 淘汰. 总大小: ${(n/1024/1024).toFixed(2)}MB, 条目数: ${s}`),await this.evictLRU(t))}async evictLRU(e){const t=e.sort((c,a)=>(c.accessCount||0)!==(a.accessCount||0)?(c.accessCount||0)-(a.accessCount||0):(c.timestamp||0)-(a.timestamp||0)),n=Math.max(1,Math.floor(t.length*this.options.evictRatio)),s=t.slice(0,n),r=s.map(c=>c.path);await this.db.table("models").bulkDelete(r);const i=s.reduce((c,a)=>c+(a.size||0),0);console.log(`[ IDBCache ] ====> LRU 淘汰完成. 删除 ${n} 个条目,释放 ${(i/1024/1024).toFixed(2)}MB`)}async getModel(e,t){const n=await this.db.table("models").get(e);return n?n.version!==t?(console.log(`[ IDBCache ] 模型版本不一致,清除当前记录 (缓存: ${n.version}, 请求: ${t})`),await this.db.table("models").delete(e),null):n.data?n.data instanceof ArrayBuffer?n.data.byteLength===0?(console.warn(`[ IDBCache ] ArrayBuffer 为空,删除记录: ${e}`),await this.db.table("models").delete(e),null):(await this.db.table("models").update(e,{accessCount:(n.accessCount||0)+1,timestamp:Date.now(),format:"arraybuffer"}),n.data):(console.warn(`[ IDBCache ] 检测到旧版本序列化格式,删除记录: ${e}`),await this.db.table("models").delete(e),null):(console.warn(`[ IDBCache ] 数据为空,删除记录: ${e}`),await this.db.table("models").delete(e),null):(console.warn(`Model "${e}" not found in table models`),null)}async cacheModel(e,t,n){console.log("[ ] ====> path, modelData, version",e,t,n);try{this.db.table("models").put({version:n,path:e,data:t}).then(()=>{console.log(`Model "${e}" cached successfully in table models`)})}catch{console.log(" 缓存模型失败 =====> ")}return t}async loadCachedModel(e,t){let n=null;try{if(n=await this.db.table("models").get(e),!n)return console.warn(`Model "${t}" not found in table models`),null;if(n.version!==t)return console.log(" =====> 模型版本不一致, 清除当前记录"),await this.db.table("models").delete(e),null}catch{return console.log(" =====> 查询表中模型失败"),this.db.delete().then(()=>{this.init()}),null}return n.data}async getStats(){const e=await this.db.table("models").toArray(),t=e.reduce((s,r)=>s+(r.size||0),0),n=e.reduce((s,r)=>s+(r.accessCount||0),0);return{count:e.length,totalSize:t,totalSizeMB:(t/1024/1024).toFixed(2),maxEntries:this.options.maxEntries,maxSizeMB:(this.options.maxSize/1024/1024).toFixed(2),usagePercentage:(t/this.options.maxSize*100).toFixed(2),totalAccessCount:n,avgAccessCount:e.length>0?(n/e.length).toFixed(2):0}}async clear(){await this.db.table("models").clear(),console.log("[ IDBCache ] ====> 缓存已清空")}async deleteModel(e){await this.db.table("models").delete(e)}async cleanLegacyFormats(){console.log("[ IDBCache ] 开始清理旧版本格式的缓存...");const e=await this.db.table("models").toArray();let t=0,n=0;const s=[];for(const i of e){let c=!1;i.data?i.data instanceof ArrayBuffer?i.data.byteLength===0&&(c=!0,console.warn(`[ IDBCache ] 清理空 ArrayBuffer: ${i.path}`)):(c=!0,console.warn(`[ IDBCache ] 清理非 ArrayBuffer 格式: ${i.path}`)):(c=!0,console.warn(`[ IDBCache ] 清理空数据: ${i.path}`)),c?(await this.db.table("models").delete(i.path),t++,s.push(i.path)):(n++,i.format||await this.db.table("models").update(i.path,{format:"arraybuffer"}))}const r={total:e.length,deleted:t,kept:n,deletedPaths:s};return console.log("[ IDBCache ] 清理完成:",r),r}async validateAndRepair(){console.log("[ IDBCache ] 开始验证缓存完整性...");const e=await this.db.table("models").toArray();let t=0,n=0;const s=[];for(const i of e){let c=!0;const a=[];i.data||(c=!1,a.push("missing_data")),i.data&&!(i.data instanceof ArrayBuffer)&&(c=!1,a.push("invalid_format")),i.data&&i.data.byteLength===0&&(c=!1,a.push("empty_buffer")),i.version||(c=!1,a.push("missing_version")),i.format||(s.push({path:i.path,action:"add_format_field"}),await this.db.table("models").update(i.path,{format:"arraybuffer"})),c?t++:(console.warn(`[ IDBCache ] 发现无效记录: ${i.path}`,a),await this.db.table("models").delete(i.path),n++)}const r={total:e.length,valid:t,invalid:n,repairs:s.length};return console.log("[ IDBCache ] 验证完成:",r),r}}function Te(o){const{geometries:e,materials:t,hierarchy:n}=o,s=new Map;e.forEach((a,l)=>{const d=is(a);s.set(l,d)});const r=new Map;t.forEach((a,l)=>{const d=rs(a);r.set(l,d)});const i=new x.Group;i.name="Scene";const c=new Map;return n.forEach(a=>{let l;if(a.type==="Mesh"){const d=a.geometryIndex>=0?s.get(a.geometryIndex):null,h=a.materialIndex>=0?r.get(a.materialIndex):null;l=new x.Mesh(d,h)}else a.type==="Group"?l=new x.Group:a.type==="Object3D"?l=new x.Object3D:l=new x.Object3D;l.name=a.name,l.position.fromArray(a.position),l.rotation.fromArray(a.rotation),l.scale.fromArray(a.scale),l.visible=a.visible,l.userData=a.userData||{},c.set(a.id,l)}),n.forEach(a=>{const l=c.get(a.id);if(a.parentId!==null){const d=c.get(a.parentId);d&&d.add(l)}else i.add(l)}),i}function is(o){const e=new x.BufferGeometry;for(const t in o.attributes){const n=o.attributes[t],s=n.array;let r;if(s.byteLength===0){console.warn(`[ sceneRebuilder ] 属性 ${t} 的数组为空`);continue}if(s.buffer&&s.buffer.byteLength===0){console.warn(`[ sceneRebuilder ] 属性 ${t} 的 buffer 已被转移,尝试重建`);continue}r=s;const i=new x.BufferAttribute(r,n.itemSize);i.normalized=n.normalized,e.setAttribute(t,i)}if(o.index){const t=o.index,n=t.array;if(n&&n.byteLength>0){const s=new x.BufferAttribute(n,t.itemSize);e.setIndex(s)}}return e}function rs(o){let e;const t={name:o.name,color:o.color!==void 0?o.color:16777215,opacity:o.opacity!==void 0?o.opacity:1,transparent:o.transparent!==void 0?o.transparent:!1,alphaTest:o.alphaTest!==void 0?o.alphaTest:0,side:o.side!==void 0?o.side:x.FrontSide,depthTest:o.depthTest!==void 0?o.depthTest:!0,depthWrite:o.depthWrite!==void 0?o.depthWrite:!0,wireframe:o.wireframe!==void 0?o.wireframe:!1,vertexColors:o.vertexColors!==void 0?o.vertexColors:!1};switch(o.type){case"MeshStandardMaterial":e=new x.MeshStandardMaterial({...t,roughness:o.roughness!==void 0?o.roughness:.5,metalness:o.metalness!==void 0?o.metalness:.5,emissive:o.emissive!==void 0?o.emissive:0,emissiveIntensity:o.emissiveIntensity!==void 0?o.emissiveIntensity:1});break;case"MeshBasicMaterial":e=new x.MeshBasicMaterial({...t});break;case"MeshPhongMaterial":e=new x.MeshPhongMaterial({...t,shininess:o.shininess!==void 0?o.shininess:30,specular:o.specular!==void 0?o.specular:1118481,emissive:o.emissive!==void 0?o.emissive:0,emissiveIntensity:o.emissiveIntensity!==void 0?o.emissiveIntensity:1});break;default:e=new x.MeshStandardMaterial(t)}return e.uuid=o.uuid,e}class os{constructor(){this.geometries=[],this.materials=[],this.hierarchy=[],this.geometryMap=new Map,this.materialMap=new Map}addChunk(e){e.geometries&&e.geometries.forEach(t=>{const n=this.geometries.length;this.geometries.push(t),this.geometryMap.set(t.uuid,n)}),e.materials&&e.materials.forEach(t=>{const n=this.materials.length;this.materials.push(t),this.materialMap.set(t.uuid,n)}),e.hierarchy&&this.hierarchy.push(...e.hierarchy)}buildCurrent(){const e={geometries:this.geometries,materials:this.materials,hierarchy:this.hierarchy};return Te(e)}finalize(){return this.buildCurrent()}}function as(o){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/gltfParser.worker-D2lwod50.js").href:new URL("assets/gltfParser.worker-D2lwod50.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{name:o==null?void 0:o.name})}function cs(o){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/gltfParserOptimized.worker-BHgPWvd-.js").href:new URL("assets/gltfParserOptimized.worker-BHgPWvd-.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{name:o==null?void 0:o.name})}let F;const pe="/draco/";let W,X,Pe=0;const z=new Map,v=new Map;function ye(o){const e=o.clone(!1);o.userData&&typeof o.userData=="object"?e.userData=JSON.parse(JSON.stringify(o.userData)):e.userData=o.userData;for(const t of o.children){const n=ye(t);e.add(n)}return e}const Ue=(o={})=>{const{debug:e=!1}=o,t=new rt,n=new nt;n.setDecoderPath(pe),t.setDRACOLoader(n);const s={info:(...f)=>e&&console.log(...f),warn:(...f)=>e&&console.warn(...f),error:(...f)=>console.error(...f),time:f=>e&&console.time(f),timeEnd:f=>e&&console.timeEnd(f)};function r(f,p,y,w){return t.load(f,p,y,w)}function i(f,p){return new Promise((y,w)=>{t.load(f,y,p,w)})}async function c(f,p,y,w={}){const _=performance.now();let S=!1;const{maxRetries:M=3,optimizeMaterials:A=!1,simplifyGeometry:D=!1,simplifyRatio:P=.5,simplifyOptions:G={},useMemoryCache:ee=!0}=w;if(ee){const C=v.get(f);if(C&&C.has(p)){const k=C.get(p);s.info(`[ 内存缓存命中 ] ${f} (version: ${p})`),s.time("[ 内存缓存克隆耗时 ]");const K=ye(k);return s.timeEnd("[ 内存缓存克隆耗时 ]"),U.recordHit(performance.now()-_),K}}try{let C=await l(f,p);if(C)s.info(`[ asyncFetch ] ====> IndexedDB 缓存命中: ${f}`),S=!0;else{s.info(`[ asyncFetch ] ====> 缓存未命中: ${f}`),s.time("[ fetchArrayBuffer ] 加载模型耗时"),C=await J.retry(()=>a(f,y),{maxRetries:M,shouldRetry:we=>!!(we.name==="TypeError"||we.message.includes("HTTP error! status: 5"))}),s.timeEnd("[ fetchArrayBuffer ] 加载模型耗时");const N=performance.now();await F.saveModel(f,p,C);const ae=performance.now()-N;U.recordCacheSave(ae),S=!1}s.time("[ 解析模型耗时 ]");let k=await d(C);if(s.timeEnd("[ 解析模型耗时 ]"),s.time("[ 模型优化耗时 ]"),A){s.info("🔧 [ 材质优化 ] 开始合并相同材质...");const{modelOptimizer:N}=await Promise.resolve().then(()=>require("./modelOptimizer-A0Cs6f9e.cjs"));k=N.optimizeMaterials(k)}if(D){s.info(`🔧 [ 几何体简化 ] 开始简化模型 (比例: ${P})...`);const{modelOptimizer:N}=await Promise.resolve().then(()=>require("./modelOptimizer-A0Cs6f9e.cjs")),ae={minFaceCount:100,preserveUVs:!0,...G};k=N.simplifyModel(k,P,ae)}if(s.timeEnd("[ 模型优化耗时 ]"),ee){v.has(f)||v.set(f,new Map);const N=v.get(f);N.has(p)||(s.info(`[ 内存缓存 ] 存储模型 ${f} (version: ${p})`),N.set(p,ye(k)))}const K=performance.now()-_;return S?U.recordHit(K):U.recordMiss(K),k}catch(C){throw s.error(`加载模型 ${f} 失败:`,C),U.recordError(f,C),C.name==="TypeError"&&C.message.includes("fetch")?q.networkError(f,C):C}}async function a(f,p){return new Promise((y,w)=>{fetch(f).then(_=>{if(!_.ok)throw new Error(`HTTP error! status: ${_.status}`);return _}).then(_=>{const S=_.headers.get("content-length"),M=S?parseInt(S,10):0;if(p&&M>0){const A=_.body.getReader();let D=0;const P=[],G=()=>{A.read().then(({done:ee,value:C})=>{if(ee){const k=new Uint8Array(D);let K=0;for(const N of P)k.set(N,K),K+=N.length;y(k.buffer);return}P.push(C),D+=C.length,p(Math.round(D/M*100)),G()}).catch(w)};G()}else return _.arrayBuffer()}).then(_=>y(_)).catch(_=>{w(_)})})}async function l(f,p){return F||(F=new Q),F.getModel(f,p)}async function d(f,p={}){if(!f)return null;const{useOptimizedParser:y=!0,useProgressive:w=!1}=p;if(y){const M=m();if(M)try{s.time("[ 优化解析 ] 使用 Transferable Objects 解析");const A=await g(M,f,w);return s.timeEnd("[ 优化解析 ] 使用 Transferable Objects 解析"),Te(A)}catch(A){s.warn("[ 优化解析 ] 失败,回退到标准解析",A)}}const _=h();if(_)try{const M=await T(_,f);return He(M)}catch(M){s.warn("[ GLTF Worker ] ====> 解析失败,回退到主线程解析",M)}return(await b(f)).scene}const h=()=>{if(typeof window>"u"||typeof Worker>"u")return null;if(!W)try{s.info("[GLTF Worker] 使用 ?worker 工厂函数创建 Worker..."),W=as(),s.info("[GLTF Worker] Worker 创建成功:",W),W.onmessage=f=>{const{id:p,data:y,error:w}=f.data||{};if(!p||!z.has(p))return;const{resolve:_,reject:S}=z.get(p);z.delete(p),w?S(new Error(w)):_(y)},W.onmessageerror=f=>{console.error("[ GLTF Worker ] ====> 消息解析失败",f)},W.onerror=f=>{console.error("[ GLTF Worker ] ====> 运行错误",f)}}catch(f){console.error("[GLTF Worker] 创建 Worker 失败:",f),console.error("[GLTF Worker] 错误堆栈:",f.stack)}return W},m=()=>{if(typeof window>"u"||typeof Worker>"u")return null;if(!X)try{s.info("[Optimized Worker] 使用 ?worker 工厂函数创建 Worker..."),X=cs(),s.info("[Optimized Worker] Worker 创建成功:",X),X.onmessage=f=>{const{id:p,data:y,error:w,type:_}=f.data||{};if(!p||!z.has(p)||_==="progress")return;const{resolve:S,reject:M}=z.get(p);z.delete(p),w?M(new Error(w)):S(y)},X.onmessageerror=f=>{console.error("[ 优化 Worker ] ====> 消息解析失败",f)},X.onerror=f=>{console.error("[ 优化 Worker ] ====> 运行错误",f)}}catch(f){return s.warn("[ 优化 Worker ] ====> 创建失败,可能不支持模块化 Worker",f),null}return X},g=(f,p,y=!1)=>new Promise((w,_)=>{const S=++Pe;z.set(S,{resolve:w,reject:_});const M={id:S,arrayBuffer:p,dracoPath:pe,mode:y?"progressive":"standard"};f.postMessage(M,[p])}),T=(f,p)=>new Promise((y,w)=>{const _=++Pe;z.set(_,{resolve:y,reject:w}),f.postMessage({id:_,arrayBuffer:p,dracoPath:pe})}),b=f=>new Promise((p,y)=>{t.parse(f,"",p,y)});return{load:r,asyncLoad:i,asyncCacheLoad:c,asyncFetch:c,getCacheStats:()=>U.getStats(),getCache:()=>F||(F=new Q),logCacheReport:()=>U.logReport(),resetCacheStats:()=>U.reset(),clearMemoryCache:()=>{let f=0;for(const[p,y]of v.entries())f+=y.size,y.clear();return v.clear(),s.info(`[ 内存缓存 ] 已清空,释放了 ${f} 个模型`),f},getMemoryCacheInfo:()=>{const f=[];let p=0;for(const[y,w]of v.entries()){const _=Array.from(w.keys());p+=_.length,f.push({path:y,versions:_,count:_.length})}return{totalPaths:v.size,totalModels:p,details:f}},deleteMemoryCache:(f,p)=>{const y=v.get(f);if(!y)return!1;if(p){const w=y.delete(p);return y.size===0&&v.delete(f),s.info(`[ 内存缓存 ] 删除模型 ${f} (version: ${p})`),w}else{const w=y.size;return v.delete(f),s.info(`[ 内存缓存 ] 删除模型 ${f} 及其所有版本 (共 ${w} 个)`),w>0}},cleanLegacyCache:async()=>await(F||(F=new Q)).cleanLegacyFormats(),validateCache:async()=>await(F||(F=new Q)).validateAndRepair()}};class je{constructor(e={}){this.options={maxPreloadCount:e.maxPreloadCount||5,preloadDelay:e.preloadDelay||1e3,enableLearning:e.enableLearning!==!1},this.loadHistory=new Map,this.loadSequence=[],this.associations=new Map,this.preloadQueue=new Set,this.isPreloading=!1,this.loader=null,this.getLoader=()=>(this.loader||(this.loader=Ue()),this.loader)}recordLoad(e,t){const n=Date.now(),s=this.loadHistory.get(e)||{count:0,lastLoadTime:0,versions:new Set};s.count++,s.lastLoadTime=n,s.versions.add(t),this.loadHistory.set(e,s),this.loadSequence.push({path:e,timestamp:n}),this.loadSequence.length>100&&this.loadSequence.shift(),this.options.enableLearning&&this.loadSequence.length>=2&&this._learnAssociations(e),this._triggerPredictivePreload(e,t)}_learnAssociations(e){const n=this.loadSequence.length-1;for(let s=Math.max(0,n-10);s<n;s++){const{path:r}=this.loadSequence[s];if(this.loadSequence[n].timestamp-this.loadSequence[s].timestamp<5*60*1e3&&r!==e){this.associations.has(r)||this.associations.set(r,new Map);const c=this.associations.get(r),a=c.get(e)||0;c.set(e,a+1)}}}_triggerPredictivePreload(e,t){setTimeout(()=>{const n=this.predictNext(e);this.preload(n,t)},this.options.preloadDelay)}predictNext(e){const t=new Map,n=this.associations.get(e);n&&n.forEach((c,a)=>{t.set(a,(t.get(a)||0)+c*2)});const s=Array.from(this.loadHistory.values()).reduce((c,a)=>c+a.count,0)/(this.loadHistory.size||1);this.loadHistory.forEach((c,a)=>{if(a!==e){const l=c.count/s;t.set(a,(t.get(a)||0)+l)}});const r=this.loadSequence.slice(-10);return new Set(r.map(c=>c.path)).forEach(c=>{c!==e&&t.set(c,(t.get(c)||0)+.5)}),Array.from(t.entries()).sort((c,a)=>a[1]-c[1]).slice(0,this.options.maxPreloadCount).map(([c])=>c)}async preload(e,t="latest"){if(this.isPreloading)return;this.isPreloading=!0;const{asyncFetch:n}=this.getLoader(),s=e.filter(r=>!this.preloadQueue.has(r)).slice(0,this.options.maxPreloadCount).map(async r=>{this.preloadQueue.add(r);try{console.log(`[ 智能预加载 ] 开始预加载: ${r}`),await n(r,t),console.log(`[ 智能预加载 ] 完成: ${r}`)}catch(i){console.warn(`[ 智能预加载 ] 失败: ${r}`,i)}finally{this.preloadQueue.delete(r)}});await Promise.all(s),this.isPreloading=!1}addAssociation(e,t){this.associations.has(e)||this.associations.set(e,new Map);const n=this.associations.get(e);t.forEach(s=>{const r=n.get(s)||0;n.set(s,r+10)})}getStats(){const e=Array.from(this.loadHistory.entries()).sort((t,n)=>n[1].count-t[1].count).slice(0,10).map(([t,n])=>({path:t,loadCount:n.count,lastLoadTime:new Date(n.lastLoadTime).toLocaleString()}));return{totalModelsLoaded:this.loadHistory.size,totalAssociations:this.associations.size,topModels:e,preloadQueueSize:this.preloadQueue.size}}clearHistory(){this.loadHistory.clear(),this.loadSequence=[],this.associations.clear()}exportAssociations(){const e={};return this.associations.forEach((t,n)=>{e[n]=Array.from(t.entries())}),e}importAssociations(e){Object.entries(e).forEach(([t,n])=>{const s=new Map(n);this.associations.set(t,s)})}}const ls=new je;exports.CSS3DRenderer=Kt;exports.CSS3DSprite=Bt;exports.CacheMonitor=Fe;exports.ErrorType=se;exports.IDBCache=Q;exports.ModelLoadError=q;exports.PredictiveLoader=je;exports.ProgressiveSceneBuilder=os;exports.RetryHelper=J;exports.Stats=$;exports.cacheMonitor=U;exports.createArrowHelper=Qt;exports.createAxesHelper=Zt;exports.createBox3Helper=Xt;exports.createCameraHelper=Vt;exports.createGridHelper=Wt;exports.createMapControls=$t;exports.createOrbitControl=Yt;exports.createRaycaster=qt;exports.createStats=Jt;exports.dataToObject3D=He;exports.dataToObject3DSync=ss;exports.disposeThreeObject=ve;exports.object3DToData=es;exports.object3DToDataSync=ts;exports.predictiveLoader=ls;exports.rebuildScene=Te;exports.useGLTFLoader=Ue;