@streamoji/avatar-widget 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4146,7 +4146,7 @@ void main() {
4146
4146
  vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));
4147
4147
  gl_FragColor = vec4( clampedHdrColor , 1.0 );
4148
4148
  }
4149
- `;class II extends gs{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:t,offsetSdr:n,gainMapMin:i,gainMapMax:o,maxDisplayBoost:l,hdrCapacityMin:h,hdrCapacityMax:d,sdr:p,gainMap:_}){super({name:"GainMapDecoderMaterial",vertexShader:LI,fragmentShader:OI,uniforms:{sdr:{value:p},gainMap:{value:_},gamma:{value:new Z(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:new Z().fromArray(t)},offsetSdr:{value:new Z().fromArray(n)},gainMapMin:{value:new Z().fromArray(i)},gainMapMax:{value:new Z().fromArray(o)},weightFactor:{value:(Math.log2(l)-h)/(d-h)}},blending:Xr,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=l,this._hdrCapacityMin=h,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}class eC extends NI{constructor(e,t){super({renderer:e,createMaterial:n=>new II(n),createQuadRenderer:n=>new CS(n)},t)}async render(e,t,n,i){const{sdrImage:o,gainMapImage:l,needsFlip:h}=await this.processImages(n,i,"flipY"),{gainMap:d,sdr:p}=this.createTextures(o,l,h);this.updateQuadRenderer(e,o,d,p,t),e.render()}}class FI extends eC{load([e,t,n],i,o,l){const h=this.prepareQuadRenderer();let d,p,_;const v=async()=>{if(d&&p&&_){try{await this.render(h,_,d,p)}catch(N){this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(n),typeof l=="function"&&l(N),h.disposeOnDemandRenderer();return}typeof i=="function"&&i(h),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(n),h.disposeOnDemandRenderer()}};let y=!0,x=0,b=0,R=!0,T=0,M=0,w=!0,D=0,U=0;const H=()=>{if(typeof o=="function"){const N=x+T+D,F=b+M+U,W=y&&R&&w;o(new ProgressEvent("progress",{lengthComputable:W,loaded:F,total:N}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(n);const I=new ha(this._internalLoadingManager);I.setResponseType("arraybuffer"),I.setRequestHeader(this.requestHeader),I.setPath(this.path),I.setWithCredentials(this.withCredentials),I.load(e,async N=>{if(typeof N=="string")throw new Error("Invalid sdr buffer");d=N,await v()},N=>{y=N.lengthComputable,b=N.loaded,x=N.total,H()},N=>{this.manager.itemError(e),typeof l=="function"&&l(N)});const z=new ha(this._internalLoadingManager);z.setResponseType("arraybuffer"),z.setRequestHeader(this.requestHeader),z.setPath(this.path),z.setWithCredentials(this.withCredentials),z.load(t,async N=>{if(typeof N=="string")throw new Error("Invalid gainmap buffer");p=N,await v()},N=>{R=N.lengthComputable,M=N.loaded,T=N.total,H()},N=>{this.manager.itemError(t),typeof l=="function"&&l(N)});const k=new ha(this._internalLoadingManager);return k.setRequestHeader(this.requestHeader),k.setPath(this.path),k.setWithCredentials(this.withCredentials),k.load(n,async N=>{if(typeof N!="string")throw new Error("Invalid metadata string");_=JSON.parse(N),await v()},N=>{w=N.lengthComputable,U=N.loaded,D=N.total,H()},N=>{this.manager.itemError(n),typeof l=="function"&&l(N)}),h}}class HI extends eC{load(e,t,n,i){const o=this.prepareQuadRenderer(),l=new ha(this._internalLoadingManager);return l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),this.manager.itemStart(e),l.load(e,async h=>{if(typeof h=="string")throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const d=new Uint8Array(h);let p,_,v;try{const y=await UI(d);p=y.sdr,_=y.gainMap,v=y.metadata}catch(y){if(y instanceof QT||y instanceof ZT)console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),v={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},p=d;else throw y}try{await this.render(o,v,p.buffer,_?.buffer)}catch(y){this.manager.itemError(e),typeof i=="function"&&i(y),o.disposeOnDemandRenderer();return}typeof t=="function"&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},n,h=>{this.manager.itemError(e),typeof i=="function"&&i(h)}),o}}const nm={apartment:"lebombo_1k.hdr",city:"potsdamer_platz_1k.hdr",dawn:"kiara_1_dawn_1k.hdr",forest:"forest_slope_1k.hdr",lobby:"st_fagans_interior_1k.hdr",night:"dikhololo_night_1k.hdr",park:"rooitou_park_1k.hdr",studio:"studio_small_03_1k.hdr",sunset:"venice_sunset_1k.hdr",warehouse:"empty_warehouse_01_1k.hdr"},tC="https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/",Vh=s=>Array.isArray(s),RS=["/px.png","/nx.png","/py.png","/ny.png","/pz.png","/nz.png"];function p_({files:s=RS,path:e="",preset:t=void 0,colorSpace:n=void 0,extensions:i}={}){t&&(wS(t),s=nm[t],e=tC);const o=Vh(s),{extension:l,isCubemap:h}=BS(s),d=DS(l);if(!d)throw new Error("useEnvironment: Unrecognized file extension: "+s);const p=Ih(x=>x.gl);Ce.useLayoutEffect(()=>{if(l!=="webp"&&l!=="jpg"&&l!=="jpeg")return;function x(){Cl.clear(d,o?[s]:s)}p.domElement.addEventListener("webglcontextlost",x,{once:!0})},[s,p.domElement]);const _=Cl(d,o?[s]:s,x=>{(l==="webp"||l==="jpg"||l==="jpeg")&&x.setRenderer(p),x.setPath==null||x.setPath(e),i&&i(x)});let v=o?_[0]:_;if(l==="jpg"||l==="jpeg"||l==="webp"){var y;v=(y=v.renderTarget)==null?void 0:y.texture}return v.mapping=h?Yr:Wf,v.colorSpace=n??(h?"srgb":"srgb-linear"),v}const PI={files:RS,path:"",preset:void 0,extensions:void 0};p_.preload=s=>{const e={...PI,...s};let{files:t,path:n=""}=e;const{preset:i,extensions:o}=e;i&&(wS(i),t=nm[i],n=tC);const{extension:l}=BS(t);if(l==="webp"||l==="jpg"||l==="jpeg")throw new Error("useEnvironment: Preloading gainmaps is not supported");const h=DS(l);if(!h)throw new Error("useEnvironment: Unrecognized file extension: "+t);Cl.preload(h,Vh(t)?[t]:t,d=>{d.setPath==null||d.setPath(n),o&&o(d)})};const GI={files:RS,preset:void 0};p_.clear=s=>{const e={...GI,...s};let{files:t}=e;const{preset:n}=e;n&&(wS(n),t=nm[n]);const{extension:i}=BS(t),o=DS(i);if(!o)throw new Error("useEnvironment: Unrecognized file extension: "+t);Cl.clear(o,Vh(t)?[t]:t)};function wS(s){if(!(s in nm))throw new Error("Preset must be one of: "+Object.keys(nm).join(", "))}function BS(s){var e;const t=Vh(s)&&s.length===6,n=Vh(s)&&s.length===3&&s.some(l=>l.endsWith("json")),i=Vh(s)?s[0]:s;return{extension:t?"cube":n?"webp":i.startsWith("data:application/exr")?"exr":i.startsWith("data:application/hdr")?"hdr":i.startsWith("data:image/jpeg")?"jpg":(e=i.split(".").pop())==null||(e=e.split("?"))==null||(e=e.shift())==null?void 0:e.toLowerCase(),isCubemap:t,isGainmap:n}}function DS(s){return s==="cube"?G1:s==="hdr"?EI:s==="exr"?TI:s==="jpg"||s==="jpeg"?HI:s==="webp"?FI:null}const zI=s=>s.current&&s.current.isScene,VI=s=>zI(s)?s.current:s;function US(s,e,t,n,i={}){var o,l,h,d;i={backgroundBlurriness:0,backgroundIntensity:1,backgroundRotation:[0,0,0],environmentIntensity:1,environmentRotation:[0,0,0],...i};const p=VI(e||t),_=p.background,v=p.environment,y={backgroundBlurriness:p.backgroundBlurriness,backgroundIntensity:p.backgroundIntensity,backgroundRotation:(o=(l=p.backgroundRotation)==null||l.clone==null?void 0:l.clone())!==null&&o!==void 0?o:[0,0,0],environmentIntensity:p.environmentIntensity,environmentRotation:(h=(d=p.environmentRotation)==null||d.clone==null?void 0:d.clone())!==null&&h!==void 0?h:[0,0,0]};return s!=="only"&&(p.environment=n),s&&(p.background=n),Do(p,i),()=>{s!=="only"&&(p.environment=v),s&&(p.background=_),Do(p,y)}}function NS({scene:s,background:e=!1,map:t,...n}){const i=Ih(o=>o.scene);return Ce.useLayoutEffect(()=>{if(t)return US(e,s,i,t,n)}),null}function nC({background:s=!1,scene:e,blur:t,backgroundBlurriness:n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h,...d}){const p=p_(d),_=Ih(v=>v.scene);return Ce.useLayoutEffect(()=>US(s,e,_,p,{backgroundBlurriness:t??n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h})),Ce.useEffect(()=>()=>{p.dispose()},[p]),null}function kI({children:s,near:e=.1,far:t=1e3,resolution:n=256,frames:i=1,map:o,background:l=!1,blur:h,backgroundBlurriness:d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y,scene:x,files:b,path:R,preset:T=void 0,extensions:M}){const w=Ih(k=>k.gl),D=Ih(k=>k.scene),U=Ce.useRef(null),[H]=Ce.useState(()=>new Mp),I=Ce.useMemo(()=>{const k=new J0(n);return k.texture.type=Pi,k},[n]);Ce.useEffect(()=>()=>{I.dispose()},[I]),Ce.useLayoutEffect(()=>{if(i===1){const k=w.autoClear;w.autoClear=!0,U.current.update(w,H),w.autoClear=k}return US(l,x,D,I.texture,{backgroundBlurriness:h??d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y})},[s,H,I.texture,x,D,l,i,w]);let z=1;return _T(()=>{if(i===1/0||z<i){const k=w.autoClear;w.autoClear=!0,U.current.update(w,H),w.autoClear=k,z++}}),Ce.createElement(Ce.Fragment,null,gO(Ce.createElement(Ce.Fragment,null,s,Ce.createElement("cubeCamera",{ref:U,args:[e,t,I]}),b||T?Ce.createElement(nC,{background:!0,files:b,preset:T,path:R,extensions:M}):o?Ce.createElement(NS,{background:!0,map:o,extensions:M}):null),H))}function XI(s){var e,t,n,i;const o=p_(s),l=s.map||o;Ce.useMemo(()=>ST({GroundProjectedEnvImpl:kO}),[]),Ce.useEffect(()=>()=>{o.dispose()},[o]);const h=Ce.useMemo(()=>[l],[l]),d=(e=s.ground)==null?void 0:e.height,p=(t=s.ground)==null?void 0:t.radius,_=(n=(i=s.ground)==null?void 0:i.scale)!==null&&n!==void 0?n:1e3;return Ce.createElement(Ce.Fragment,null,Ce.createElement(NS,dS({},s,{map:l})),Ce.createElement("groundProjectedEnvImpl",{args:h,scale:_,height:d,radius:p}))}function YI(s){return s.ground?Ce.createElement(XI,s):s.map?Ce.createElement(NS,s):s.children?Ce.createElement(kI,s):Ce.createElement(nC,s)}function iC(s,e){if(e===ox)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===bu||e===fp){let t=s.getIndex();if(t===null){const l=[],h=s.getAttribute("position");if(h!==void 0){for(let d=0;d<h.count;d++)l.push(d);s.setIndex(l),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,i=[];if(e===bu)for(let l=1;l<=n;l++)i.push(t.getX(0)),i.push(t.getX(l)),i.push(t.getX(l+1));else for(let l=0;l<n;l++)l%2===0?(i.push(t.getX(l)),i.push(t.getX(l+1)),i.push(t.getX(l+2))):(i.push(t.getX(l+2)),i.push(t.getX(l+1)),i.push(t.getX(l)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class JI extends Ta{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ZI(t)}),this.register(function(t){return new QI(t)}),this.register(function(t){return new oF(t)}),this.register(function(t){return new lF(t)}),this.register(function(t){return new cF(t)}),this.register(function(t){return new eF(t)}),this.register(function(t){return new tF(t)}),this.register(function(t){return new nF(t)}),this.register(function(t){return new iF(t)}),this.register(function(t){return new jI(t)}),this.register(function(t){return new aF(t)}),this.register(function(t){return new $I(t)}),this.register(function(t){return new rF(t)}),this.register(function(t){return new sF(t)}),this.register(function(t){return new KI(t)}),this.register(function(t){return new uF(t)}),this.register(function(t){return new fF(t)})}load(e,t,n,i){const o=this;let l;if(this.resourcePath!=="")l=this.resourcePath;else if(this.path!==""){const p=ir.extractUrlBase(e);l=ir.resolveURL(p,this.path)}else l=ir.extractUrlBase(e);this.manager.itemStart(e);const h=function(p){i?i(p):console.error(p),o.manager.itemError(e),o.manager.itemEnd(e)},d=new ha(this.manager);d.setPath(this.path),d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setWithCredentials(this.withCredentials),d.load(e,function(p){try{o.parse(p,l,function(_){t(_),o.manager.itemEnd(e)},h)}catch(_){h(_)}},n,h)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let o;const l={},h={},d=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(d.decode(new Uint8Array(e,0,4))===aC){try{l[Un.KHR_BINARY_GLTF]=new hF(e)}catch(v){i&&i(v);return}o=JSON.parse(l[Un.KHR_BINARY_GLTF].content)}else o=JSON.parse(d.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const p=new EF(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});p.fileLoader.setRequestHeader(this.requestHeader);for(let _=0;_<this.pluginCallbacks.length;_++){const v=this.pluginCallbacks[_](p);v.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),h[v.name]=v,l[v.name]=!0}if(o.extensionsUsed)for(let _=0;_<o.extensionsUsed.length;++_){const v=o.extensionsUsed[_],y=o.extensionsRequired||[];switch(v){case Un.KHR_MATERIALS_UNLIT:l[v]=new WI;break;case Un.KHR_DRACO_MESH_COMPRESSION:l[v]=new dF(o,this.dracoLoader);break;case Un.KHR_TEXTURE_TRANSFORM:l[v]=new pF;break;case Un.KHR_MESH_QUANTIZATION:l[v]=new mF;break;default:y.indexOf(v)>=0&&h[v]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+v+'".')}}p.setExtensions(l),p.setPlugins(h),p.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,o){n.parse(e,t,i,o)})}}function qI(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Un={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 KI{constructor(e){this.parser=e,this.name=Un.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const o=t.json,d=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let p;const _=new Mt(16777215);d.color!==void 0&&_.setRGB(d.color[0],d.color[1],d.color[2],ta);const v=d.range!==void 0?d.range:0;switch(d.type){case"directional":p=new Gv(_),p.target.position.set(0,0,-1),p.add(p.target);break;case"point":p=new Pv(_),p.distance=v;break;case"spot":p=new Hv(_),p.distance=v,d.spot=d.spot||{},d.spot.innerConeAngle=d.spot.innerConeAngle!==void 0?d.spot.innerConeAngle:0,d.spot.outerConeAngle=d.spot.outerConeAngle!==void 0?d.spot.outerConeAngle:Math.PI/4,p.angle=d.spot.outerConeAngle,p.penumbra=1-d.spot.innerConeAngle/d.spot.outerConeAngle,p.target.position.set(0,0,-1),p.add(p.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+d.type)}return p.position.set(0,0,0),Uo(p,d),d.intensity!==void 0&&(p.intensity=d.intensity),p.name=t.createUniqueName(d.name||"light_"+e),i=Promise.resolve(p),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],h=(o.extensions&&o.extensions[this.name]||{}).light;return h===void 0?null:this._loadLight(h).then(function(d){return n._getNodeRef(t.cache,h,d)})}}class WI{constructor(){this.name=Un.KHR_MATERIALS_UNLIT}getMaterialType(){return fa}extendParams(e,t,n){const i=[];e.color=new Mt(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const l=o.baseColorFactor;e.color.setRGB(l[0],l[1],l[2],ta),e.opacity=l[3]}o.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",o.baseColorTexture,Gi))}return Promise.all(i)}}class jI{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class ZI{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];if(l.clearcoatFactor!==void 0&&(t.clearcoat=l.clearcoatFactor),l.clearcoatTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatMap",l.clearcoatTexture)),l.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=l.clearcoatRoughnessFactor),l.clearcoatRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatRoughnessMap",l.clearcoatRoughnessTexture)),l.clearcoatNormalTexture!==void 0&&(o.push(n.assignTexture(t,"clearcoatNormalMap",l.clearcoatNormalTexture)),l.clearcoatNormalTexture.scale!==void 0)){const h=l.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new et(h,h)}return Promise.all(o)}}class QI{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class $I{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.iridescenceFactor!==void 0&&(t.iridescence=l.iridescenceFactor),l.iridescenceTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceMap",l.iridescenceTexture)),l.iridescenceIor!==void 0&&(t.iridescenceIOR=l.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),l.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=l.iridescenceThicknessMinimum),l.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=l.iridescenceThicknessMaximum),l.iridescenceThicknessTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceThicknessMap",l.iridescenceThicknessTexture)),Promise.all(o)}}class eF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new Mt(0,0,0),t.sheenRoughness=0,t.sheen=1;const l=i.extensions[this.name];if(l.sheenColorFactor!==void 0){const h=l.sheenColorFactor;t.sheenColor.setRGB(h[0],h[1],h[2],ta)}return l.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=l.sheenRoughnessFactor),l.sheenColorTexture!==void 0&&o.push(n.assignTexture(t,"sheenColorMap",l.sheenColorTexture,Gi)),l.sheenRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"sheenRoughnessMap",l.sheenRoughnessTexture)),Promise.all(o)}}class tF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.transmissionFactor!==void 0&&(t.transmission=l.transmissionFactor),l.transmissionTexture!==void 0&&o.push(n.assignTexture(t,"transmissionMap",l.transmissionTexture)),Promise.all(o)}}class nF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.thickness=l.thicknessFactor!==void 0?l.thicknessFactor:0,l.thicknessTexture!==void 0&&o.push(n.assignTexture(t,"thicknessMap",l.thicknessTexture)),t.attenuationDistance=l.attenuationDistance||1/0;const h=l.attenuationColor||[1,1,1];return t.attenuationColor=new Mt().setRGB(h[0],h[1],h[2],ta),Promise.all(o)}}class iF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class aF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.specularIntensity=l.specularFactor!==void 0?l.specularFactor:1,l.specularTexture!==void 0&&o.push(n.assignTexture(t,"specularIntensityMap",l.specularTexture));const h=l.specularColorFactor||[1,1,1];return t.specularColor=new Mt().setRGB(h[0],h[1],h[2],ta),l.specularColorTexture!==void 0&&o.push(n.assignTexture(t,"specularColorMap",l.specularColorTexture,Gi)),Promise.all(o)}}class sF{constructor(e){this.parser=e,this.name=Un.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return t.bumpScale=l.bumpFactor!==void 0?l.bumpFactor:1,l.bumpTexture!==void 0&&o.push(n.assignTexture(t,"bumpMap",l.bumpTexture)),Promise.all(o)}}class rF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.anisotropyStrength!==void 0&&(t.anisotropy=l.anisotropyStrength),l.anisotropyRotation!==void 0&&(t.anisotropyRotation=l.anisotropyRotation),l.anisotropyTexture!==void 0&&o.push(n.assignTexture(t,"anisotropyMap",l.anisotropyTexture)),Promise.all(o)}}class oF{constructor(e){this.parser=e,this.name=Un.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const o=i.extensions[this.name],l=t.options.ktx2Loader;if(!l){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,l)}}class lF{constructor(e){this.parser=e,this.name=Un.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class cF{constructor(e){this.parser=e,this.name=Un.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class uF{constructor(e){this.name=Un.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 i=n.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),l=this.parser.options.meshoptDecoder;if(!l||!l.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(h){const d=i.byteOffset||0,p=i.byteLength||0,_=i.count,v=i.byteStride,y=new Uint8Array(h,d,p);return l.decodeGltfBufferAsync?l.decodeGltfBufferAsync(_,v,y,i.mode,i.filter).then(function(x){return x.buffer}):l.ready.then(function(){const x=new ArrayBuffer(_*v);return l.decodeGltfBuffer(new Uint8Array(x),_,v,y,i.mode,i.filter),x})})}else return null}}class fF{constructor(e){this.name=Un.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const p of i.primitives)if(p.mode!==Mr.TRIANGLES&&p.mode!==Mr.TRIANGLE_STRIP&&p.mode!==Mr.TRIANGLE_FAN&&p.mode!==void 0)return null;const l=n.extensions[this.name].attributes,h=[],d={};for(const p in l)h.push(this.parser.getDependency("accessor",l[p]).then(_=>(d[p]=_,d[p])));return h.length<1?null:(h.push(this.parser.createNodeMesh(e)),Promise.all(h).then(p=>{const _=p.pop(),v=_.isGroup?_.children:[_],y=p[0].count,x=[];for(const b of v){const R=new $t,T=new Z,M=new Ma,w=new Z(1,1,1),D=new iv(b.geometry,b.material,y);for(let U=0;U<y;U++)d.TRANSLATION&&T.fromBufferAttribute(d.TRANSLATION,U),d.ROTATION&&M.fromBufferAttribute(d.ROTATION,U),d.SCALE&&w.fromBufferAttribute(d.SCALE,U),D.setMatrixAt(U,R.compose(T,M,w));for(const U in d)if(U==="_COLOR_0"){const H=d[U];D.instanceColor=new xc(H.array,H.itemSize,H.normalized)}else U!=="TRANSLATION"&&U!=="ROTATION"&&U!=="SCALE"&&b.geometry.setAttribute(U,d[U]);Bn.prototype.copy.call(D,b),this.parser.assignFinalMaterial(D),x.push(D)}return _.isGroup?(_.clear(),_.add(...x),_):x[0]}))}}const aC="glTF",im=12,sC={JSON:1313821514,BIN:5130562};class hF{constructor(e){this.name=Un.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,im),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!==aC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-im,o=new DataView(e,im);let l=0;for(;l<i;){const h=o.getUint32(l,!0);l+=4;const d=o.getUint32(l,!0);if(l+=4,d===sC.JSON){const p=new Uint8Array(e,im+l,h);this.content=n.decode(p)}else if(d===sC.BIN){const p=im+l;this.body=e.slice(p,p+h)}l+=h}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class dF{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Un.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,l=e.extensions[this.name].attributes,h={},d={},p={};for(const _ in l){const v=OS[_]||_.toLowerCase();h[v]=l[_]}for(const _ in e.attributes){const v=OS[_]||_.toLowerCase();if(l[_]!==void 0){const y=n.accessors[e.attributes[_]],x=kh[y.componentType];p[v]=x.name,d[v]=y.normalized===!0}}return t.getDependency("bufferView",o).then(function(_){return new Promise(function(v,y){i.decodeDracoFile(_,function(x){for(const b in x.attributes){const R=x.attributes[b],T=d[b];T!==void 0&&(R.normalized=T)}v(x)},h,p,ta,y)})})}}class pF{constructor(){this.name=Un.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 mF{constructor(){this.name=Un.KHR_MESH_QUANTIZATION}}class rC extends Pu{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let l=0;l!==i;l++)t[l]=n[o+l];return t}interpolate_(e,t,n,i){const o=this.resultBuffer,l=this.sampleValues,h=this.valueSize,d=h*2,p=h*3,_=i-t,v=(n-t)/_,y=v*v,x=y*v,b=e*p,R=b-p,T=-2*x+3*y,M=x-y,w=1-T,D=M-y+v;for(let U=0;U!==h;U++){const H=l[R+U+h],I=l[R+U+d]*_,z=l[b+U+h],k=l[b+U]*_;o[U]=w*H+D*I+T*z+M*k}return o}}const gF=new Ma;class vF extends rC{interpolate_(e,t,n,i){const o=super.interpolate_(e,t,n,i);return gF.fromArray(o).normalize().toArray(o),o}}const Mr={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},kh={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},oC={9728:Ai,9729:bn,9984:tp,9985:yu,9986:lc,9987:Fs},lC={33071:xi,33648:_u,10497:Jr},LS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},OS={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"},Bc={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},_F={CUBICSPLINE:void 0,LINEAR:uc,STEP:Au},IS={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function yF(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new Fu({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:kr})),s.DefaultMaterial}function nf(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Uo(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function xF(s,e,t){let n=!1,i=!1,o=!1;for(let p=0,_=e.length;p<_;p++){const v=e[p];if(v.POSITION!==void 0&&(n=!0),v.NORMAL!==void 0&&(i=!0),v.COLOR_0!==void 0&&(o=!0),n&&i&&o)break}if(!n&&!i&&!o)return Promise.resolve(s);const l=[],h=[],d=[];for(let p=0,_=e.length;p<_;p++){const v=e[p];if(n){const y=v.POSITION!==void 0?t.getDependency("accessor",v.POSITION):s.attributes.position;l.push(y)}if(i){const y=v.NORMAL!==void 0?t.getDependency("accessor",v.NORMAL):s.attributes.normal;h.push(y)}if(o){const y=v.COLOR_0!==void 0?t.getDependency("accessor",v.COLOR_0):s.attributes.color;d.push(y)}}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d)]).then(function(p){const _=p[0],v=p[1],y=p[2];return n&&(s.morphAttributes.position=_),i&&(s.morphAttributes.normal=v),o&&(s.morphAttributes.color=y),s.morphTargetsRelative=!0,s})}function AF(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function SF(s){let e;const t=s.extensions&&s.extensions[Un.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+FS(t.attributes):e=s.indices+":"+FS(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,i=s.targets.length;n<i;n++)e+=":"+FS(s.targets[n]);return e}function FS(s){let e="";const t=Object.keys(s).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+s[t[n]]+";";return e}function HS(s){switch(s){case Int8Array:return .007874015748031496;case Uint8Array:return .00392156862745098;case Int16Array:return 3051850947599719e-20;case Uint16Array:return 15259021896696422e-21;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function MF(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const bF=new $t;class EF{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new qI,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,o=!1,l=-1;if(typeof navigator<"u"){const h=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(h)===!0;const d=h.match(/Version\/(\d+)/);i=n&&d?parseInt(d[1],10):-1,o=h.indexOf("Firefox")>-1,l=o?h.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||o&&l<98?this.textureLoader=new uA(this.options.manager):this.textureLoader=new mA(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ha(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(l){return l._markDefs&&l._markDefs()}),Promise.all(this._invokeAll(function(l){return l.beforeRoot&&l.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(l){const h={scene:l[0][i.scene||0],scenes:l[0],animations:l[1],cameras:l[2],asset:i.asset,parser:n,userData:{}};return nf(o,h,i),Uo(h,i),Promise.all(n._invokeAll(function(d){return d.afterRoot&&d.afterRoot(h)})).then(function(){for(const d of h.scenes)d.updateMatrixWorld();e(h)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,o=t.length;i<o;i++){const l=t[i].joints;for(let h=0,d=l.length;h<d;h++)e[l[h]].isBone=!0}for(let i=0,o=e.length;i<o;i++){const l=e[i];l.mesh!==void 0&&(this._addNodeRef(this.meshCache,l.mesh),l.skin!==void 0&&(n[l.mesh].isSkinnedMesh=!0)),l.camera!==void 0&&this._addNodeRef(this.cameraCache,l.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),o=(l,h)=>{const d=this.associations.get(l);d!=null&&this.associations.set(h,d);for(const[p,_]of l.children.entries())o(_,h.children[p])};return o(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const o=e(t[i]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,l){return n.getDependency(e,l)})),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[Un.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(o,l){n.load(ir.resolveURL(t.uri,i.path),o,void 0,function(){l(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const l=LS[i.type],h=kh[i.componentType],d=i.normalized===!0,p=new h(i.count*l);return Promise.resolve(new On(p,l,d))}const o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(l){const h=l[0],d=LS[i.type],p=kh[i.componentType],_=p.BYTES_PER_ELEMENT,v=_*d,y=i.byteOffset||0,x=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,b=i.normalized===!0;let R,T;if(x&&x!==v){const M=Math.floor(y/x),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+M+":"+i.count;let D=t.cache.get(w);D||(R=new p(h,M*x,i.count*x/_),D=new yh(R,x/_),t.cache.add(w,D)),T=new Al(D,d,y%x/_,b)}else h===null?R=new p(i.count*d):R=new p(h,y,i.count*d),T=new On(R,d,b);if(i.sparse!==void 0){const M=LS.SCALAR,w=kh[i.sparse.indices.componentType],D=i.sparse.indices.byteOffset||0,U=i.sparse.values.byteOffset||0,H=new w(l[1],D,i.sparse.count*M),I=new p(l[2],U,i.sparse.count*d);h!==null&&(T=new On(T.array.slice(),T.itemSize,T.normalized)),T.normalized=!1;for(let z=0,k=H.length;z<k;z++){const N=H[z];if(T.setX(N,I[z*d]),d>=2&&T.setY(N,I[z*d+1]),d>=3&&T.setZ(N,I[z*d+2]),d>=4&&T.setW(N,I[z*d+3]),d>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}T.normalized=b}return T})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,l=t.images[o];let h=this.textureLoader;if(l.uri){const d=n.manager.getHandler(l.uri);d!==null&&(h=d)}return this.loadTextureImage(e,o,h)}loadTextureImage(e,t,n){const i=this,o=this.json,l=o.textures[e],h=o.images[t],d=(h.uri||h.bufferView)+":"+l.sampler;if(this.textureCache[d])return this.textureCache[d];const p=this.loadImageSource(t,n).then(function(_){_.flipY=!1,_.name=l.name||h.name||"",_.name===""&&typeof h.uri=="string"&&h.uri.startsWith("data:image/")===!1&&(_.name=h.uri);const y=(o.samplers||{})[l.sampler]||{};return _.magFilter=oC[y.magFilter]||bn,_.minFilter=oC[y.minFilter]||Fs,_.wrapS=lC[y.wrapS]||Jr,_.wrapT=lC[y.wrapT]||Jr,_.generateMipmaps=!_.isCompressedTexture&&_.minFilter!==Ai&&_.minFilter!==bn,i.associations.set(_,{textures:e}),_}).catch(function(){return null});return this.textureCache[d]=p,p}loadImageSource(e,t){const n=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(v=>v.clone());const l=i.images[e],h=self.URL||self.webkitURL;let d=l.uri||"",p=!1;if(l.bufferView!==void 0)d=n.getDependency("bufferView",l.bufferView).then(function(v){p=!0;const y=new Blob([v],{type:l.mimeType});return d=h.createObjectURL(y),d});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const _=Promise.resolve(d).then(function(v){return new Promise(function(y,x){let b=y;t.isImageBitmapLoader===!0&&(b=function(R){const T=new Kn(R);T.needsUpdate=!0,y(T)}),t.load(ir.resolveURL(v,o.path),b,void 0,x)})}).then(function(v){return p===!0&&h.revokeObjectURL(d),Uo(v,l),v.userData.mimeType=l.mimeType||MF(l.uri),v}).catch(function(v){throw console.error("THREE.GLTFLoader: Couldn't load texture",d),v});return this.sourceCache[e]=_,_}assignTexture(e,t,n,i){const o=this;return this.getDependency("texture",n.index).then(function(l){if(!l)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(l=l.clone(),l.channel=n.texCoord),o.extensions[Un.KHR_TEXTURE_TRANSFORM]){const h=n.extensions!==void 0?n.extensions[Un.KHR_TEXTURE_TRANSFORM]:void 0;if(h){const d=o.associations.get(l);l=o.extensions[Un.KHR_TEXTURE_TRANSFORM].extendTexture(l,h),o.associations.set(l,d)}}return i!==void 0&&(l.colorSpace=i),e[t]=l,l})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,l=t.attributes.normal===void 0;if(e.isPoints){const h="PointsMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Up,zi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,d.sizeAttenuation=!1,this.cache.add(h,d)),n=d}else if(e.isLine){const h="LineBasicMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Ga,zi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,this.cache.add(h,d)),n=d}if(i||o||l){let h="ClonedMaterial:"+n.uuid+":";i&&(h+="derivative-tangents:"),o&&(h+="vertex-colors:"),l&&(h+="flat-shading:");let d=this.cache.get(h);d||(d=n.clone(),o&&(d.vertexColors=!0),l&&(d.flatShading=!0),i&&(d.normalScale&&(d.normalScale.y*=-1),d.clearcoatNormalScale&&(d.clearcoatNormalScale.y*=-1)),this.cache.add(h,d),this.associations.set(d,this.associations.get(n))),n=d}e.material=n}getMaterialType(){return Fu}loadMaterial(e){const t=this,n=this.json,i=this.extensions,o=n.materials[e];let l;const h={},d=o.extensions||{},p=[];if(d[Un.KHR_MATERIALS_UNLIT]){const v=i[Un.KHR_MATERIALS_UNLIT];l=v.getMaterialType(),p.push(v.extendParams(h,o,t))}else{const v=o.pbrMetallicRoughness||{};if(h.color=new Mt(1,1,1),h.opacity=1,Array.isArray(v.baseColorFactor)){const y=v.baseColorFactor;h.color.setRGB(y[0],y[1],y[2],ta),h.opacity=y[3]}v.baseColorTexture!==void 0&&p.push(t.assignTexture(h,"map",v.baseColorTexture,Gi)),h.metalness=v.metallicFactor!==void 0?v.metallicFactor:1,h.roughness=v.roughnessFactor!==void 0?v.roughnessFactor:1,v.metallicRoughnessTexture!==void 0&&(p.push(t.assignTexture(h,"metalnessMap",v.metallicRoughnessTexture)),p.push(t.assignTexture(h,"roughnessMap",v.metallicRoughnessTexture))),l=this._invokeOne(function(y){return y.getMaterialType&&y.getMaterialType(e)}),p.push(Promise.all(this._invokeAll(function(y){return y.extendMaterialParams&&y.extendMaterialParams(e,h)})))}o.doubleSided===!0&&(h.side=js);const _=o.alphaMode||IS.OPAQUE;if(_===IS.BLEND?(h.transparent=!0,h.depthWrite=!1):(h.transparent=!1,_===IS.MASK&&(h.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&l!==fa&&(p.push(t.assignTexture(h,"normalMap",o.normalTexture)),h.normalScale=new et(1,1),o.normalTexture.scale!==void 0)){const v=o.normalTexture.scale;h.normalScale.set(v,v)}if(o.occlusionTexture!==void 0&&l!==fa&&(p.push(t.assignTexture(h,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(h.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&l!==fa){const v=o.emissiveFactor;h.emissive=new Mt().setRGB(v[0],v[1],v[2],ta)}return o.emissiveTexture!==void 0&&l!==fa&&p.push(t.assignTexture(h,"emissiveMap",o.emissiveTexture,Gi)),Promise.all(p).then(function(){const v=new l(h);return o.name&&(v.name=o.name),Uo(v,o),t.associations.set(v,{materials:e}),o.extensions&&nf(i,v,o),v})}createUniqueName(e){const t=Pn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function o(h){return n[Un.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(h,t).then(function(d){return cC(d,h,t)})}const l=[];for(let h=0,d=e.length;h<d;h++){const p=e[h],_=SF(p),v=i[_];if(v)l.push(v.promise);else{let y;p.extensions&&p.extensions[Un.KHR_DRACO_MESH_COMPRESSION]?y=o(p):y=cC(new cn,p,t),i[_]={primitive:p,promise:y},l.push(y)}}return Promise.all(l)}loadMesh(e){const t=this,n=this.json,i=this.extensions,o=n.meshes[e],l=o.primitives,h=[];for(let d=0,p=l.length;d<p;d++){const _=l[d].material===void 0?yF(this.cache):this.getDependency("material",l[d].material);h.push(_)}return h.push(t.loadGeometries(l)),Promise.all(h).then(function(d){const p=d.slice(0,d.length-1),_=d[d.length-1],v=[];for(let x=0,b=_.length;x<b;x++){const R=_[x],T=l[x];let M;const w=p[x];if(T.mode===Mr.TRIANGLES||T.mode===Mr.TRIANGLE_STRIP||T.mode===Mr.TRIANGLE_FAN||T.mode===void 0)M=o.isSkinnedMesh===!0?new tv(R,w):new mi(R,w),M.isSkinnedMesh===!0&&M.normalizeSkinWeights(),T.mode===Mr.TRIANGLE_STRIP?M.geometry=iC(M.geometry,fp):T.mode===Mr.TRIANGLE_FAN&&(M.geometry=iC(M.geometry,bu));else if(T.mode===Mr.LINES)M=new yr(R,w);else if(T.mode===Mr.LINE_STRIP)M=new Ro(R,w);else if(T.mode===Mr.LINE_LOOP)M=new hv(R,w);else if(T.mode===Mr.POINTS)M=new mv(R,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+T.mode);Object.keys(M.geometry.morphAttributes).length>0&&AF(M,o),M.name=t.createUniqueName(o.name||"mesh_"+e),Uo(M,o),T.extensions&&nf(i,M,T),t.assignFinalMaterial(M),v.push(M)}for(let x=0,b=v.length;x<b;x++)t.associations.set(v[x],{meshes:e,primitives:x});if(v.length===1)return o.extensions&&nf(i,v[0],o),v[0];const y=new vr;o.extensions&&nf(i,y,o),t.associations.set(y,{meshes:e});for(let x=0,b=v.length;x<b;x++)y.add(v[x]);return y})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new ia(T0.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new Tl(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Uo(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,o=t.joints.length;i<o;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const o=i.pop(),l=i,h=[],d=[];for(let p=0,_=l.length;p<_;p++){const v=l[p];if(v){h.push(v);const y=new $t;o!==null&&y.fromArray(o.array,p*16),d.push(y)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[p])}return new bh(h,d)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,l=[],h=[],d=[],p=[],_=[];for(let v=0,y=i.channels.length;v<y;v++){const x=i.channels[v],b=i.samplers[x.sampler],R=x.target,T=R.node,M=i.parameters!==void 0?i.parameters[b.input]:b.input,w=i.parameters!==void 0?i.parameters[b.output]:b.output;R.node!==void 0&&(l.push(this.getDependency("node",T)),h.push(this.getDependency("accessor",M)),d.push(this.getDependency("accessor",w)),p.push(b),_.push(R))}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d),Promise.all(p),Promise.all(_)]).then(function(v){const y=v[0],x=v[1],b=v[2],R=v[3],T=v[4],M=[];for(let D=0,U=y.length;D<U;D++){const H=y[D],I=x[D],z=b[D],k=R[D],N=T[D];if(H===void 0)continue;H.updateMatrix&&H.updateMatrix();const F=n._createAnimationTracks(H,I,z,k,N);if(F)for(let W=0;W<F.length;W++)M.push(F[W])}const w=new Vu(o,void 0,M);return Uo(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(o){const l=n._getNodeRef(n.meshCache,i.mesh,o);return i.weights!==void 0&&l.traverse(function(h){if(h.isMesh)for(let d=0,p=i.weights.length;d<p;d++)h.morphTargetInfluences[d]=i.weights[d]}),l})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],o=n._loadNodeShallow(e),l=[],h=i.children||[];for(let p=0,_=h.length;p<_;p++)l.push(n.getDependency("node",h[p]));const d=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([o,Promise.all(l),d]).then(function(p){const _=p[0],v=p[1],y=p[2];y!==null&&_.traverse(function(x){x.isSkinnedMesh&&x.bind(y,bF)});for(let x=0,b=v.length;x<b;x++)_.add(v[x]);return _})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],l=o.name?i.createUniqueName(o.name):"",h=[],d=i._invokeOne(function(p){return p.createNodeMesh&&p.createNodeMesh(e)});return d&&h.push(d),o.camera!==void 0&&h.push(i.getDependency("camera",o.camera).then(function(p){return i._getNodeRef(i.cameraCache,o.camera,p)})),i._invokeAll(function(p){return p.createNodeAttachment&&p.createNodeAttachment(e)}).forEach(function(p){h.push(p)}),this.nodeCache[e]=Promise.all(h).then(function(p){let _;if(o.isBone===!0?_=new Cp:p.length>1?_=new vr:p.length===1?_=p[0]:_=new Bn,_!==p[0])for(let v=0,y=p.length;v<y;v++)_.add(p[v]);if(o.name&&(_.userData.name=o.name,_.name=l),Uo(_,o),o.extensions&&nf(n,_,o),o.matrix!==void 0){const v=new $t;v.fromArray(o.matrix),_.applyMatrix4(v)}else o.translation!==void 0&&_.position.fromArray(o.translation),o.rotation!==void 0&&_.quaternion.fromArray(o.rotation),o.scale!==void 0&&_.scale.fromArray(o.scale);if(!i.associations.has(_))i.associations.set(_,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){const v=i.associations.get(_);i.associations.set(_,{...v})}return i.associations.get(_).nodes=e,_}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,o=new vr;n.name&&(o.name=i.createUniqueName(n.name)),Uo(o,n),n.extensions&&nf(t,o,n);const l=n.nodes||[],h=[];for(let d=0,p=l.length;d<p;d++)h.push(i.getDependency("node",l[d]));return Promise.all(h).then(function(d){for(let _=0,v=d.length;_<v;_++)o.add(d[_]);const p=_=>{const v=new Map;for(const[y,x]of i.associations)(y instanceof zi||y instanceof Kn)&&v.set(y,x);return _.traverse(y=>{const x=i.associations.get(y);x!=null&&v.set(y,x)}),v};return i.associations=p(o),o})}_createAnimationTracks(e,t,n,i,o){const l=[],h=e.name?e.name:e.uuid,d=[];Bc[o.path]===Bc.weights?e.traverse(function(y){y.morphTargetInfluences&&d.push(y.name?y.name:y.uuid)}):d.push(h);let p;switch(Bc[o.path]){case Bc.weights:p=Sl;break;case Bc.rotation:p=Ml;break;case Bc.translation:case Bc.scale:p=bl;break;default:n.itemSize===1?p=Sl:p=bl;break}const _=i.interpolation!==void 0?_F[i.interpolation]:uc,v=this._getArrayFromAccessor(n);for(let y=0,x=d.length;y<x;y++){const b=new p(d[y]+"."+Bc[o.path],t.array,v,_);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),l.push(b)}return l}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=HS(t.constructor),i=new Float32Array(t.length);for(let o=0,l=t.length;o<l;o++)i[o]=t[o]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof Ml?vF:rC;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function TF(s,e,t){const n=e.attributes,i=new ba;if(n.POSITION!==void 0){const h=t.json.accessors[n.POSITION],d=h.min,p=h.max;if(d!==void 0&&p!==void 0){if(i.set(new Z(d[0],d[1],d[2]),new Z(p[0],p[1],p[2])),h.normalized){const _=HS(kh[h.componentType]);i.min.multiplyScalar(_),i.max.multiplyScalar(_)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const h=new Z,d=new Z;for(let p=0,_=o.length;p<_;p++){const v=o[p];if(v.POSITION!==void 0){const y=t.json.accessors[v.POSITION],x=y.min,b=y.max;if(x!==void 0&&b!==void 0){if(d.setX(Math.max(Math.abs(x[0]),Math.abs(b[0]))),d.setY(Math.max(Math.abs(x[1]),Math.abs(b[1]))),d.setZ(Math.max(Math.abs(x[2]),Math.abs(b[2]))),y.normalized){const R=HS(kh[y.componentType]);d.multiplyScalar(R)}h.max(d)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(h)}s.boundingBox=i;const l=new ua;i.getCenter(l.center),l.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=l}function cC(s,e,t){const n=e.attributes,i=[];function o(l,h){return t.getDependency("accessor",l).then(function(d){s.setAttribute(h,d)})}for(const l in n){const h=OS[l]||l.toLowerCase();h in s.attributes||i.push(o(n[l],h))}if(e.indices!==void 0&&!s.index){const l=t.getDependency("accessor",e.indices).then(function(h){s.setIndex(h)});i.push(l)}return Cn.workingColorSpace!==ta&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Cn.workingColorSpace}" not supported.`),Uo(s,e),TF(s,e,t),Promise.all(i).then(function(){return e.targets!==void 0?xF(s,e.targets,t):s})}const $a=(...s)=>{},CF=(...s)=>{},uC=({analyser:s})=>{const e=Ce.useRef(null),t=Ce.useRef(null);return Ce.useEffect(()=>{const n=e.current;if(!n)return;const i=n.getContext("2d",{alpha:!0});if(!i)return;let o,l=null;s&&(s.fftSize=128,l=new Uint8Array(s.frequencyBinCount));const h=()=>{o=requestAnimationFrame(h),(n.width!==n.offsetWidth||n.height!==n.offsetHeight)&&(n.width=n.offsetWidth,n.height=n.offsetHeight);const d=n.width,p=n.height;if(d===0||p===0)return;const _=p/2;i.clearRect(0,0,d,p),i.fillStyle="#1e293b";const v=2,x=v+2,b=d*.95,R=Math.floor(b/x);(!t.current||t.current.length!==R)&&(t.current=new Float32Array(R).fill(2));const T=R*x,M=(d-T)/2;s&&l&&s.getByteFrequencyData(l);const w=l?l.length:0,U=Math.floor(w*.7)/R,H=new Float32Array(R);for(let I=0;I<R;I++){let z=0;if(l&&U>0){const F=Math.floor(I*U),W=Math.floor((I+1)*U);for(let ae=F;ae<W;ae++){const ie=l[ae]||0;ie>z&&(z=ie)}}z<10&&(z=0);const k=z/255,N=z>0?Math.max(2,Math.pow(k,1.4)*p*.25):2;H[I]=N}for(let I=0;I<R;I++){const z=R-1-I,k=Math.max(H[I],H[z]),N=t.current[I]+(k-t.current[I])*.3;t.current[I]=N;const F=M+I*x,W=_-N/2;i.beginPath(),i.roundRect?i.roundRect(F,W,v,N,4):i.fillRect(F,W,v,N),i.fill()}};return h(),()=>{cancelAnimationFrame(o)}},[s]),Vt.jsx("canvas",{ref:e,style:{width:"100%",height:"100%",display:"block"}})},fC="https://ai.streamoji.com",RF="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev";async function wF(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}function BF(s){const[e,t]=Ce.useState(null);return Ce.useEffect(()=>{if(!s){t(null);return}let n=!1;return wF(s).then(i=>{if(n)return;const o=`${RF}/${i}.glb`;fetch(o,{method:"HEAD"}).then(l=>{n||t(l.ok?o:null)}).catch(()=>{n||t(null)})}),()=>{n=!0}},[s]),e}const DF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],UF=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],NF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"],LF={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},OF=[-.45,1.9,.1],IF={browInnerUp:.2},PS=.18,FF=1,m_={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},HF=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],PF={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]};function GF(s){if(!s)return[{v:"sil",w:1}];const e=s.toLowerCase();return PF[e]??[{v:"sil",w:1}]}function zF({target:s}){const{camera:e}=Ih();return Ce.useEffect(()=>{e.lookAt(...s)},[e,s]),null}function zs(s,e,t){if(!s||!s.morphTargetDictionary)return;const n=s,i=n.morphTargetDictionary,o=n.morphTargetInfluences;if(o)for(const l in i)l.toLowerCase()===e.toLowerCase()&&(o[i[l]]=t)}function hC(s,e=.97){if(!s)return;const t=s;if(t.morphTargetInfluences)for(let n=0;n<t.morphTargetInfluences.length;n++)t.morphTargetInfluences[n]*=e}const VF=Ce.memo(({avatarUrl:s,isPlayingRef:e,visemeQueueRef:t,audioContextRef:n,responseAudioStartTimeRef:i,adjustments:o,mood:l,expression:h,agentResponse:d,isSpeaking:p,nextStartTimeRef:_,stopPlayback:v,setIsSpeaking:y,expressionUrl:x,onExpressionFinished:b})=>{const{scene:R}=zh(s),T=zh(DF),M=Ce.useMemo(()=>T.flatMap(Q=>Q.animations),[T]),w=zh(NF),D=Ce.useMemo(()=>w.flatMap(Q=>Q.animations),[w]),U=Ce.useRef(null),H=Ce.useRef(null),I=Ce.useRef(null),z=Ce.useRef([]),[k]=Ce.useState(()=>new aE(R)),N=Ce.useRef({}),F=Ce.useRef(null),W=Ce.useRef(0),ae=Ce.useRef(!1),ie=Ce.useRef(0),re=Ce.useRef(null);Ce.useEffect(()=>{if(!(!M||!R)){if(M.forEach((Q,ce)=>{const se=`idle_${ce}`;if(!N.current[se]){const X=k.clipAction(Q,R);X.name=se,X.setLoop(cp,1),X.clampWhenFinished=!0,N.current[se]=X}}),D.forEach((Q,ce)=>{const se=`talk_${ce}`;if(!N.current[se]){const X=k.clipAction(Q,R);X.name=se,X.setLoop(cp,1),X.clampWhenFinished=!0,N.current[se]=X}}),M.length>0){const Q=N.current.idle_0,ce=F.current&&k.existingAction(F.current.getClip());Q&&!ce&&(Q.reset().fadeIn(.5).play(),F.current=Q)}return()=>{k.stopAllAction(),N.current={},F.current=null}}},[M,D,R,k]);const _e=Ce.useRef("");Ce.useEffect(()=>{if(!x||!R||x===_e.current)return;_e.current=x,re.current=x,new JI().load(x,ce=>{if(ce.animations&&ce.animations.length>0){const se=ce.animations[0],X=k.clipAction(se,R);if(X.name=`EXPR_${x}`,X.setLoop(cp,1),X.clampWhenFinished=!0,N.current[`EXPR_${x}`]=X,p&&re.current===x){const ne=F.current;X.reset().fadeIn(.3).play(),ne&&ne!==X&&ne.crossFadeTo(X,.3,!0),F.current=X,re.current=null}}},void 0,ce=>{console.error(`[ANIMATION] Failed to load ${x}`,ce)})},[x,R,k,p]),Ce.useEffect(()=>{const Q=ce=>{const se=ce.action,X=se.name||"";if(X.startsWith("idle_")){const ye=(parseInt(X.split("_")[1])+1)%M.length,Ee=N.current[`idle_${ye}`];Ee&&(Ee.reset().fadeIn(.5).play(),se.crossFadeTo(Ee,.5,!0),F.current=Ee)}else if(X.startsWith("EXPR_")){if(p){const ne=N.current.talk_0;ne&&(ne.reset().fadeIn(.5).play(),se.crossFadeTo(ne,.5,!0),F.current=ne)}else{const ne=N.current.idle_0;ne&&(ne.reset().fadeIn(.5).play(),se.crossFadeTo(ne,.5,!0),F.current=ne)}b&&b()}else if(X.startsWith("talk_"))if(p){const ye=(parseInt(X.split("_")[1])+1)%D.length,Ee=N.current[`talk_${ye}`];Ee&&(Ee.reset().fadeIn(.3).play(),se.crossFadeTo(Ee,.3,!0),F.current=Ee)}else{const ne=N.current.idle_0;ne&&(ne.reset().fadeIn(.5).play(),se.crossFadeTo(ne,.5,!0),F.current=ne)}};return k.addEventListener("finished",Q),()=>k.removeEventListener("finished",Q)},[k,M,D,p,b]),Ce.useEffect(()=>{if(p&&R){const Q=F.current,ce=Q?.name||"";if(ce.startsWith("idle_")||ce.startsWith("talk_")||ce===""){const se=re.current;if(se){const X=N.current[`EXPR_${se}`];if(X){X.reset().fadeIn(.3).play(),Q&&Q!==X&&Q.crossFadeTo(X,.3,!0),F.current=X,re.current=null;return}}if(ce.startsWith("idle_")||ce===""){const X=N.current.talk_0;X&&(X.reset().fadeIn(.5).play(),Q&&Q.crossFadeTo(X,.5,!0),F.current=X)}}}else if(!p&&R){const Q=F.current,ce=Q?.name||"";if(ce.startsWith("talk_")||ce.startsWith("EXPR_")){const se=N.current.idle_0;se&&(se.reset().fadeIn(.5).play(),Q&&Q.crossFadeTo(se,.5,!0),F.current=se)}}},[p,R,x]),Ce.useEffect(()=>{if(!R)return;R.traverse(se=>{if(se.isMesh&&se.morphTargetDictionary){const X=se.name.toLowerCase();(X.includes("head")||X.includes("avatar"))&&(H.current=se,$a(`[ANIMATION] Found head mesh: ${se.name}`)),X.includes("teeth")&&(I.current=se,$a(`[ANIMATION] Found teeth mesh: ${se.name}`))}});const Q=H.current?.morphTargetDictionary;Q&&Object.keys(Q).filter(se=>se.toLowerCase().includes("brow"));const ce=[];R.traverse(se=>{if(se.isMesh){const ne=se.morphTargetDictionary;ne&&Object.keys(ne).some(ye=>ye.toLowerCase().includes("brow"))&&ce.push(se)}}),z.current=ce,ce.length>0&&$a("[ANIMATION] Meshes with brow morphs:",ce.length)},[R]);const P=(Q,ce=1)=>{const se=`viseme_${Q}`.toLowerCase(),X=HF.find(ne=>ne.key.toLowerCase()===se);if(X)for(const ne in X.mix){const ye=X.mix[ne]*ce;zs(H.current,ne,ye),zs(I.current,ne,ye)}},K=Q=>{const ce=m_[Q]??m_.neutral;for(const se in ce)zs(H.current,se,ce[se]),zs(I.current,se,ce[se])};return _T((Q,ce)=>{const se=Math.pow(.88,60*ce);hC(H.current,se),hC(I.current,se),K(l);const X=Q.clock.elapsedTime;let ne=0;if(Math.floor(X)%5===0&&Math.floor((X-ce)%5)!==0){let Pe=null;R.traverse($=>{$.name.toLowerCase().includes("hips")&&(Pe=$)});const ht=Pe?`Hips Y: ${Pe.position.y.toFixed(4)}`:"Hips not found";$a(`[ANIMATION] Mixer Time: ${k.time.toFixed(2)}, ${ht}`)}if(k.update(ce),X>W.current&&!ae.current&&(ae.current=!0,ie.current=X),ae.current){const ht=(X-ie.current)/.3;if(ht>=1)ae.current=!1,W.current=X+2+Math.random()*5;else{const $=ht<.5?ht*2:(1-ht)*2;zs(H.current,"eyeBlinkLeft",$),zs(H.current,"eyeBlinkRight",$),zs(I.current,"eyeBlinkLeft",$),zs(I.current,"eyeBlinkRight",$),ne=$*IF.browInnerUp}}const ye=m_[l]??m_.neutral,Ee=ye.browInnerUp??0,it=ye.browOuterUpLeft??0,ve=ye.browOuterUpRight??0,Be=X*FF,at=PS*Math.sin(Be),bt=PS*.7*Math.sin(Be+.7),Tt=PS*.7*Math.sin(Be+1.3),en=Pe=>Math.max(0,Math.min(1,Pe)),fn=en(Ee+at),Xt=en(it+bt),Fe=en(ve+Tt),$e=en(fn+ne);if(zs(H.current,"browInnerUp",$e),zs(I.current,"browInnerUp",$e),zs(H.current,"browOuterUpLeft",Xt),zs(I.current,"browOuterUpLeft",Xt),zs(H.current,"browOuterUpRight",Fe),zs(I.current,"browOuterUpRight",Fe),U.current){const Pe=e.current?0:o.rotation[1];U.current.rotation.y=T0.lerp(U.current.rotation.y,Pe,.1),U.current.position.set(...o.position),U.current.scale.setScalar(o.scale),U.current.rotation.x=o.rotation[0],U.current.rotation.z=o.rotation[2]}if(e.current&&n.current){const Pe=n.current.currentTime,Bt=(Pe-i.current)*1e3- -150;for(let ft=0;ft<t.current.length;ft++){const Dt=t.current[ft];Bt>=Dt.vtime&&Bt<Dt.vtime+Dt.vduration&&P(Dt.viseme,Dt.weight??1)}Pe>_.current+.5&&(v(),y(!1))}}),Vt.jsx("group",{ref:U,children:Vt.jsx("primitive",{object:R})})});function kF(s){return s?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():""}const XF=({token:s,agentToken:e,onNavigationRequested:t}={})=>{const n=s??e??"",i=BF(n||void 0),[o,l]=Ce.useState(""),[h,d]=Ce.useState(""),[p,_]=Ce.useState("Ready"),[v,y]=Ce.useState(!1),[x,b]=Ce.useState(!1),R=Ce.useRef(!1),T=Ce.useRef([]),M=Ce.useRef(0),w=Ce.useRef(!1),D=Ce.useRef([]),U=Ce.useRef(null),H=Ce.useRef([]);Ce.useRef([]);const I=Ce.useRef([]),z=Ce.useRef(0),k=Ce.useRef(0),N=Ce.useRef(0),F=Ce.useRef(0),[W,ae]=Ce.useState(null),ie=Ce.useRef(null),[re,_e]=Ce.useState("neutral"),[P,K]=Ce.useState(""),[Q,ce]=Ce.useState(""),[se,X]=Ce.useState("Chat with us"),[ne,ye]=Ce.useState(null),[Ee,it]=Ce.useState("hidden"),[ve,Be]=Ce.useState(""),at=Ce.useRef(null),bt=Ce.useRef(Ee);bt.current=Ee;const[Tt,en]=Ce.useState(null),fn=Ce.useRef(null),Xt=Ce.useRef(null),[Fe,$e]=Ce.useState("hidden"),[Pe,ht]=Ce.useState(""),$=Ce.useRef(Fe);$.current=Fe;const Bt=Ce.useRef(""),ft=Ce.useRef(!1),Dt=Ce.useRef(""),dt=Ce.useMemo(()=>p==="Thinking..."||p==="Processing Voice..."?p:ne!=null&&ne!==""&&ne!=="none"&&ne!=="<none>"?`Enter ${kF(ne)}`:null,[p,ne]),j=dt!=null&&dt!=="";Ce.useEffect(()=>{const rt=bt.current;if(!(rt==="exiting"||rt==="entering")){if(rt==="hidden"){j&&(Be(dt??""),it("entering"));return}rt==="visible"&&(!j||dt!==ve)&&(at.current=j?dt:null,it("exiting"))}},[j,dt,Ee,ve]);const G=Ce.useCallback(()=>{const rt=bt.current;if(rt==="exiting"){it("hidden");const pt=at.current;at.current=null,pt!=null&&pt!==""&&(Be(pt),it("entering"))}else rt==="entering"&&it("visible")},[]),pe=rt=>{if(!rt)return;if(rt.mood!=null){const ee=String(rt.mood).toLowerCase();_e(ee)}if(rt.expression!=null){const ee=String(rt.expression).trim();K(ee);const ge=UF.find(Me=>Me.name.toLowerCase()===ee.toLowerCase());$a(`[STREAM] Animation match for "${ee}": ${ge?ge.name:"NONE"}`),ce(ge?.url??"")}if(rt.navigation!=null){const ee=String(rt.navigation).trim();ee!==""&&(t?t(ee):window.location.href=ee)}const pt=rt.ask_for||rt.lead_capture?.ask_for,O=pt?String(pt).trim().toLowerCase():"",Y=O==="none"||O==="<none>";if(pt&&!Y){const ee=O;ye(ee||null),X(ee==="email"?"Enter your email":ee==="name"?"Enter your name":ee==="phone"?"Enter your phone number":"Chat with us")}else(Y||rt.ask_for===null||rt.lead_capture&&rt.lead_capture.ask_for===null||rt.ask_for==="none")&&(ye(null),se!=="Chat with us"&&X("Chat with us"));rt.collected,rt.valid},Oe=rt=>{const pt=rt.trim();if(!pt)return null;if(pt.startsWith("{"))try{return JSON.parse(pt)}catch{return null}if(pt.includes(":")){const O=pt.split(":"),Y=O[0].trim().toLowerCase(),ee=O.slice(1).join(":").trim();return{[Y]:ee}}return null},Ye=Ce.useCallback(()=>{},[]),Le=rt=>{if(ft.current)rt==="§"?ft.current=!1:(Dt.current+=rt,d(pt=>pt+rt));else if(rt==="§"){ft.current=!0;return}else for(Bt.current+=rt;Bt.current.includes(`
4149
+ `;class II extends gs{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:t,offsetSdr:n,gainMapMin:i,gainMapMax:o,maxDisplayBoost:l,hdrCapacityMin:h,hdrCapacityMax:d,sdr:p,gainMap:_}){super({name:"GainMapDecoderMaterial",vertexShader:LI,fragmentShader:OI,uniforms:{sdr:{value:p},gainMap:{value:_},gamma:{value:new Z(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:new Z().fromArray(t)},offsetSdr:{value:new Z().fromArray(n)},gainMapMin:{value:new Z().fromArray(i)},gainMapMax:{value:new Z().fromArray(o)},weightFactor:{value:(Math.log2(l)-h)/(d-h)}},blending:Xr,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=l,this._hdrCapacityMin=h,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}class eC extends NI{constructor(e,t){super({renderer:e,createMaterial:n=>new II(n),createQuadRenderer:n=>new CS(n)},t)}async render(e,t,n,i){const{sdrImage:o,gainMapImage:l,needsFlip:h}=await this.processImages(n,i,"flipY"),{gainMap:d,sdr:p}=this.createTextures(o,l,h);this.updateQuadRenderer(e,o,d,p,t),e.render()}}class FI extends eC{load([e,t,n],i,o,l){const h=this.prepareQuadRenderer();let d,p,_;const v=async()=>{if(d&&p&&_){try{await this.render(h,_,d,p)}catch(N){this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(n),typeof l=="function"&&l(N),h.disposeOnDemandRenderer();return}typeof i=="function"&&i(h),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(n),h.disposeOnDemandRenderer()}};let y=!0,x=0,b=0,R=!0,T=0,M=0,w=!0,D=0,U=0;const H=()=>{if(typeof o=="function"){const N=x+T+D,F=b+M+U,W=y&&R&&w;o(new ProgressEvent("progress",{lengthComputable:W,loaded:F,total:N}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(n);const I=new ha(this._internalLoadingManager);I.setResponseType("arraybuffer"),I.setRequestHeader(this.requestHeader),I.setPath(this.path),I.setWithCredentials(this.withCredentials),I.load(e,async N=>{if(typeof N=="string")throw new Error("Invalid sdr buffer");d=N,await v()},N=>{y=N.lengthComputable,b=N.loaded,x=N.total,H()},N=>{this.manager.itemError(e),typeof l=="function"&&l(N)});const z=new ha(this._internalLoadingManager);z.setResponseType("arraybuffer"),z.setRequestHeader(this.requestHeader),z.setPath(this.path),z.setWithCredentials(this.withCredentials),z.load(t,async N=>{if(typeof N=="string")throw new Error("Invalid gainmap buffer");p=N,await v()},N=>{R=N.lengthComputable,M=N.loaded,T=N.total,H()},N=>{this.manager.itemError(t),typeof l=="function"&&l(N)});const k=new ha(this._internalLoadingManager);return k.setRequestHeader(this.requestHeader),k.setPath(this.path),k.setWithCredentials(this.withCredentials),k.load(n,async N=>{if(typeof N!="string")throw new Error("Invalid metadata string");_=JSON.parse(N),await v()},N=>{w=N.lengthComputable,U=N.loaded,D=N.total,H()},N=>{this.manager.itemError(n),typeof l=="function"&&l(N)}),h}}class HI extends eC{load(e,t,n,i){const o=this.prepareQuadRenderer(),l=new ha(this._internalLoadingManager);return l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),this.manager.itemStart(e),l.load(e,async h=>{if(typeof h=="string")throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const d=new Uint8Array(h);let p,_,v;try{const y=await UI(d);p=y.sdr,_=y.gainMap,v=y.metadata}catch(y){if(y instanceof QT||y instanceof ZT)console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),v={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},p=d;else throw y}try{await this.render(o,v,p.buffer,_?.buffer)}catch(y){this.manager.itemError(e),typeof i=="function"&&i(y),o.disposeOnDemandRenderer();return}typeof t=="function"&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},n,h=>{this.manager.itemError(e),typeof i=="function"&&i(h)}),o}}const nm={apartment:"lebombo_1k.hdr",city:"potsdamer_platz_1k.hdr",dawn:"kiara_1_dawn_1k.hdr",forest:"forest_slope_1k.hdr",lobby:"st_fagans_interior_1k.hdr",night:"dikhololo_night_1k.hdr",park:"rooitou_park_1k.hdr",studio:"studio_small_03_1k.hdr",sunset:"venice_sunset_1k.hdr",warehouse:"empty_warehouse_01_1k.hdr"},tC="https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/",Vh=s=>Array.isArray(s),RS=["/px.png","/nx.png","/py.png","/ny.png","/pz.png","/nz.png"];function p_({files:s=RS,path:e="",preset:t=void 0,colorSpace:n=void 0,extensions:i}={}){t&&(wS(t),s=nm[t],e=tC);const o=Vh(s),{extension:l,isCubemap:h}=BS(s),d=DS(l);if(!d)throw new Error("useEnvironment: Unrecognized file extension: "+s);const p=Ih(x=>x.gl);Ce.useLayoutEffect(()=>{if(l!=="webp"&&l!=="jpg"&&l!=="jpeg")return;function x(){Cl.clear(d,o?[s]:s)}p.domElement.addEventListener("webglcontextlost",x,{once:!0})},[s,p.domElement]);const _=Cl(d,o?[s]:s,x=>{(l==="webp"||l==="jpg"||l==="jpeg")&&x.setRenderer(p),x.setPath==null||x.setPath(e),i&&i(x)});let v=o?_[0]:_;if(l==="jpg"||l==="jpeg"||l==="webp"){var y;v=(y=v.renderTarget)==null?void 0:y.texture}return v.mapping=h?Yr:Wf,v.colorSpace=n??(h?"srgb":"srgb-linear"),v}const PI={files:RS,path:"",preset:void 0,extensions:void 0};p_.preload=s=>{const e={...PI,...s};let{files:t,path:n=""}=e;const{preset:i,extensions:o}=e;i&&(wS(i),t=nm[i],n=tC);const{extension:l}=BS(t);if(l==="webp"||l==="jpg"||l==="jpeg")throw new Error("useEnvironment: Preloading gainmaps is not supported");const h=DS(l);if(!h)throw new Error("useEnvironment: Unrecognized file extension: "+t);Cl.preload(h,Vh(t)?[t]:t,d=>{d.setPath==null||d.setPath(n),o&&o(d)})};const GI={files:RS,preset:void 0};p_.clear=s=>{const e={...GI,...s};let{files:t}=e;const{preset:n}=e;n&&(wS(n),t=nm[n]);const{extension:i}=BS(t),o=DS(i);if(!o)throw new Error("useEnvironment: Unrecognized file extension: "+t);Cl.clear(o,Vh(t)?[t]:t)};function wS(s){if(!(s in nm))throw new Error("Preset must be one of: "+Object.keys(nm).join(", "))}function BS(s){var e;const t=Vh(s)&&s.length===6,n=Vh(s)&&s.length===3&&s.some(l=>l.endsWith("json")),i=Vh(s)?s[0]:s;return{extension:t?"cube":n?"webp":i.startsWith("data:application/exr")?"exr":i.startsWith("data:application/hdr")?"hdr":i.startsWith("data:image/jpeg")?"jpg":(e=i.split(".").pop())==null||(e=e.split("?"))==null||(e=e.shift())==null?void 0:e.toLowerCase(),isCubemap:t,isGainmap:n}}function DS(s){return s==="cube"?G1:s==="hdr"?EI:s==="exr"?TI:s==="jpg"||s==="jpeg"?HI:s==="webp"?FI:null}const zI=s=>s.current&&s.current.isScene,VI=s=>zI(s)?s.current:s;function US(s,e,t,n,i={}){var o,l,h,d;i={backgroundBlurriness:0,backgroundIntensity:1,backgroundRotation:[0,0,0],environmentIntensity:1,environmentRotation:[0,0,0],...i};const p=VI(e||t),_=p.background,v=p.environment,y={backgroundBlurriness:p.backgroundBlurriness,backgroundIntensity:p.backgroundIntensity,backgroundRotation:(o=(l=p.backgroundRotation)==null||l.clone==null?void 0:l.clone())!==null&&o!==void 0?o:[0,0,0],environmentIntensity:p.environmentIntensity,environmentRotation:(h=(d=p.environmentRotation)==null||d.clone==null?void 0:d.clone())!==null&&h!==void 0?h:[0,0,0]};return s!=="only"&&(p.environment=n),s&&(p.background=n),Do(p,i),()=>{s!=="only"&&(p.environment=v),s&&(p.background=_),Do(p,y)}}function NS({scene:s,background:e=!1,map:t,...n}){const i=Ih(o=>o.scene);return Ce.useLayoutEffect(()=>{if(t)return US(e,s,i,t,n)}),null}function nC({background:s=!1,scene:e,blur:t,backgroundBlurriness:n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h,...d}){const p=p_(d),_=Ih(v=>v.scene);return Ce.useLayoutEffect(()=>US(s,e,_,p,{backgroundBlurriness:t??n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h})),Ce.useEffect(()=>()=>{p.dispose()},[p]),null}function kI({children:s,near:e=.1,far:t=1e3,resolution:n=256,frames:i=1,map:o,background:l=!1,blur:h,backgroundBlurriness:d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y,scene:x,files:b,path:R,preset:T=void 0,extensions:M}){const w=Ih(k=>k.gl),D=Ih(k=>k.scene),U=Ce.useRef(null),[H]=Ce.useState(()=>new Mp),I=Ce.useMemo(()=>{const k=new J0(n);return k.texture.type=Pi,k},[n]);Ce.useEffect(()=>()=>{I.dispose()},[I]),Ce.useLayoutEffect(()=>{if(i===1){const k=w.autoClear;w.autoClear=!0,U.current.update(w,H),w.autoClear=k}return US(l,x,D,I.texture,{backgroundBlurriness:h??d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y})},[s,H,I.texture,x,D,l,i,w]);let z=1;return _T(()=>{if(i===1/0||z<i){const k=w.autoClear;w.autoClear=!0,U.current.update(w,H),w.autoClear=k,z++}}),Ce.createElement(Ce.Fragment,null,gO(Ce.createElement(Ce.Fragment,null,s,Ce.createElement("cubeCamera",{ref:U,args:[e,t,I]}),b||T?Ce.createElement(nC,{background:!0,files:b,preset:T,path:R,extensions:M}):o?Ce.createElement(NS,{background:!0,map:o,extensions:M}):null),H))}function XI(s){var e,t,n,i;const o=p_(s),l=s.map||o;Ce.useMemo(()=>ST({GroundProjectedEnvImpl:kO}),[]),Ce.useEffect(()=>()=>{o.dispose()},[o]);const h=Ce.useMemo(()=>[l],[l]),d=(e=s.ground)==null?void 0:e.height,p=(t=s.ground)==null?void 0:t.radius,_=(n=(i=s.ground)==null?void 0:i.scale)!==null&&n!==void 0?n:1e3;return Ce.createElement(Ce.Fragment,null,Ce.createElement(NS,dS({},s,{map:l})),Ce.createElement("groundProjectedEnvImpl",{args:h,scale:_,height:d,radius:p}))}function YI(s){return s.ground?Ce.createElement(XI,s):s.map?Ce.createElement(NS,s):s.children?Ce.createElement(kI,s):Ce.createElement(nC,s)}function iC(s,e){if(e===ox)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===bu||e===fp){let t=s.getIndex();if(t===null){const l=[],h=s.getAttribute("position");if(h!==void 0){for(let d=0;d<h.count;d++)l.push(d);s.setIndex(l),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,i=[];if(e===bu)for(let l=1;l<=n;l++)i.push(t.getX(0)),i.push(t.getX(l)),i.push(t.getX(l+1));else for(let l=0;l<n;l++)l%2===0?(i.push(t.getX(l)),i.push(t.getX(l+1)),i.push(t.getX(l+2))):(i.push(t.getX(l+2)),i.push(t.getX(l+1)),i.push(t.getX(l)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class JI extends Ta{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ZI(t)}),this.register(function(t){return new QI(t)}),this.register(function(t){return new oF(t)}),this.register(function(t){return new lF(t)}),this.register(function(t){return new cF(t)}),this.register(function(t){return new eF(t)}),this.register(function(t){return new tF(t)}),this.register(function(t){return new nF(t)}),this.register(function(t){return new iF(t)}),this.register(function(t){return new jI(t)}),this.register(function(t){return new aF(t)}),this.register(function(t){return new $I(t)}),this.register(function(t){return new rF(t)}),this.register(function(t){return new sF(t)}),this.register(function(t){return new KI(t)}),this.register(function(t){return new uF(t)}),this.register(function(t){return new fF(t)})}load(e,t,n,i){const o=this;let l;if(this.resourcePath!=="")l=this.resourcePath;else if(this.path!==""){const p=ir.extractUrlBase(e);l=ir.resolveURL(p,this.path)}else l=ir.extractUrlBase(e);this.manager.itemStart(e);const h=function(p){i?i(p):console.error(p),o.manager.itemError(e),o.manager.itemEnd(e)},d=new ha(this.manager);d.setPath(this.path),d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setWithCredentials(this.withCredentials),d.load(e,function(p){try{o.parse(p,l,function(_){t(_),o.manager.itemEnd(e)},h)}catch(_){h(_)}},n,h)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let o;const l={},h={},d=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(d.decode(new Uint8Array(e,0,4))===aC){try{l[Un.KHR_BINARY_GLTF]=new hF(e)}catch(v){i&&i(v);return}o=JSON.parse(l[Un.KHR_BINARY_GLTF].content)}else o=JSON.parse(d.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const p=new EF(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});p.fileLoader.setRequestHeader(this.requestHeader);for(let _=0;_<this.pluginCallbacks.length;_++){const v=this.pluginCallbacks[_](p);v.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),h[v.name]=v,l[v.name]=!0}if(o.extensionsUsed)for(let _=0;_<o.extensionsUsed.length;++_){const v=o.extensionsUsed[_],y=o.extensionsRequired||[];switch(v){case Un.KHR_MATERIALS_UNLIT:l[v]=new WI;break;case Un.KHR_DRACO_MESH_COMPRESSION:l[v]=new dF(o,this.dracoLoader);break;case Un.KHR_TEXTURE_TRANSFORM:l[v]=new pF;break;case Un.KHR_MESH_QUANTIZATION:l[v]=new mF;break;default:y.indexOf(v)>=0&&h[v]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+v+'".')}}p.setExtensions(l),p.setPlugins(h),p.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,o){n.parse(e,t,i,o)})}}function qI(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Un={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 KI{constructor(e){this.parser=e,this.name=Un.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const o=t.json,d=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let p;const _=new Mt(16777215);d.color!==void 0&&_.setRGB(d.color[0],d.color[1],d.color[2],ta);const v=d.range!==void 0?d.range:0;switch(d.type){case"directional":p=new Gv(_),p.target.position.set(0,0,-1),p.add(p.target);break;case"point":p=new Pv(_),p.distance=v;break;case"spot":p=new Hv(_),p.distance=v,d.spot=d.spot||{},d.spot.innerConeAngle=d.spot.innerConeAngle!==void 0?d.spot.innerConeAngle:0,d.spot.outerConeAngle=d.spot.outerConeAngle!==void 0?d.spot.outerConeAngle:Math.PI/4,p.angle=d.spot.outerConeAngle,p.penumbra=1-d.spot.innerConeAngle/d.spot.outerConeAngle,p.target.position.set(0,0,-1),p.add(p.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+d.type)}return p.position.set(0,0,0),Uo(p,d),d.intensity!==void 0&&(p.intensity=d.intensity),p.name=t.createUniqueName(d.name||"light_"+e),i=Promise.resolve(p),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],h=(o.extensions&&o.extensions[this.name]||{}).light;return h===void 0?null:this._loadLight(h).then(function(d){return n._getNodeRef(t.cache,h,d)})}}class WI{constructor(){this.name=Un.KHR_MATERIALS_UNLIT}getMaterialType(){return fa}extendParams(e,t,n){const i=[];e.color=new Mt(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const l=o.baseColorFactor;e.color.setRGB(l[0],l[1],l[2],ta),e.opacity=l[3]}o.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",o.baseColorTexture,Gi))}return Promise.all(i)}}class jI{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class ZI{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];if(l.clearcoatFactor!==void 0&&(t.clearcoat=l.clearcoatFactor),l.clearcoatTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatMap",l.clearcoatTexture)),l.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=l.clearcoatRoughnessFactor),l.clearcoatRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatRoughnessMap",l.clearcoatRoughnessTexture)),l.clearcoatNormalTexture!==void 0&&(o.push(n.assignTexture(t,"clearcoatNormalMap",l.clearcoatNormalTexture)),l.clearcoatNormalTexture.scale!==void 0)){const h=l.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new et(h,h)}return Promise.all(o)}}class QI{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class $I{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.iridescenceFactor!==void 0&&(t.iridescence=l.iridescenceFactor),l.iridescenceTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceMap",l.iridescenceTexture)),l.iridescenceIor!==void 0&&(t.iridescenceIOR=l.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),l.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=l.iridescenceThicknessMinimum),l.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=l.iridescenceThicknessMaximum),l.iridescenceThicknessTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceThicknessMap",l.iridescenceThicknessTexture)),Promise.all(o)}}class eF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new Mt(0,0,0),t.sheenRoughness=0,t.sheen=1;const l=i.extensions[this.name];if(l.sheenColorFactor!==void 0){const h=l.sheenColorFactor;t.sheenColor.setRGB(h[0],h[1],h[2],ta)}return l.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=l.sheenRoughnessFactor),l.sheenColorTexture!==void 0&&o.push(n.assignTexture(t,"sheenColorMap",l.sheenColorTexture,Gi)),l.sheenRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"sheenRoughnessMap",l.sheenRoughnessTexture)),Promise.all(o)}}class tF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.transmissionFactor!==void 0&&(t.transmission=l.transmissionFactor),l.transmissionTexture!==void 0&&o.push(n.assignTexture(t,"transmissionMap",l.transmissionTexture)),Promise.all(o)}}class nF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.thickness=l.thicknessFactor!==void 0?l.thicknessFactor:0,l.thicknessTexture!==void 0&&o.push(n.assignTexture(t,"thicknessMap",l.thicknessTexture)),t.attenuationDistance=l.attenuationDistance||1/0;const h=l.attenuationColor||[1,1,1];return t.attenuationColor=new Mt().setRGB(h[0],h[1],h[2],ta),Promise.all(o)}}class iF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class aF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.specularIntensity=l.specularFactor!==void 0?l.specularFactor:1,l.specularTexture!==void 0&&o.push(n.assignTexture(t,"specularIntensityMap",l.specularTexture));const h=l.specularColorFactor||[1,1,1];return t.specularColor=new Mt().setRGB(h[0],h[1],h[2],ta),l.specularColorTexture!==void 0&&o.push(n.assignTexture(t,"specularColorMap",l.specularColorTexture,Gi)),Promise.all(o)}}class sF{constructor(e){this.parser=e,this.name=Un.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return t.bumpScale=l.bumpFactor!==void 0?l.bumpFactor:1,l.bumpTexture!==void 0&&o.push(n.assignTexture(t,"bumpMap",l.bumpTexture)),Promise.all(o)}}class rF{constructor(e){this.parser=e,this.name=Un.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Vi}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.anisotropyStrength!==void 0&&(t.anisotropy=l.anisotropyStrength),l.anisotropyRotation!==void 0&&(t.anisotropyRotation=l.anisotropyRotation),l.anisotropyTexture!==void 0&&o.push(n.assignTexture(t,"anisotropyMap",l.anisotropyTexture)),Promise.all(o)}}class oF{constructor(e){this.parser=e,this.name=Un.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const o=i.extensions[this.name],l=t.options.ktx2Loader;if(!l){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,l)}}class lF{constructor(e){this.parser=e,this.name=Un.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class cF{constructor(e){this.parser=e,this.name=Un.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class uF{constructor(e){this.name=Un.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 i=n.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),l=this.parser.options.meshoptDecoder;if(!l||!l.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(h){const d=i.byteOffset||0,p=i.byteLength||0,_=i.count,v=i.byteStride,y=new Uint8Array(h,d,p);return l.decodeGltfBufferAsync?l.decodeGltfBufferAsync(_,v,y,i.mode,i.filter).then(function(x){return x.buffer}):l.ready.then(function(){const x=new ArrayBuffer(_*v);return l.decodeGltfBuffer(new Uint8Array(x),_,v,y,i.mode,i.filter),x})})}else return null}}class fF{constructor(e){this.name=Un.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const p of i.primitives)if(p.mode!==Mr.TRIANGLES&&p.mode!==Mr.TRIANGLE_STRIP&&p.mode!==Mr.TRIANGLE_FAN&&p.mode!==void 0)return null;const l=n.extensions[this.name].attributes,h=[],d={};for(const p in l)h.push(this.parser.getDependency("accessor",l[p]).then(_=>(d[p]=_,d[p])));return h.length<1?null:(h.push(this.parser.createNodeMesh(e)),Promise.all(h).then(p=>{const _=p.pop(),v=_.isGroup?_.children:[_],y=p[0].count,x=[];for(const b of v){const R=new $t,T=new Z,M=new Ma,w=new Z(1,1,1),D=new iv(b.geometry,b.material,y);for(let U=0;U<y;U++)d.TRANSLATION&&T.fromBufferAttribute(d.TRANSLATION,U),d.ROTATION&&M.fromBufferAttribute(d.ROTATION,U),d.SCALE&&w.fromBufferAttribute(d.SCALE,U),D.setMatrixAt(U,R.compose(T,M,w));for(const U in d)if(U==="_COLOR_0"){const H=d[U];D.instanceColor=new xc(H.array,H.itemSize,H.normalized)}else U!=="TRANSLATION"&&U!=="ROTATION"&&U!=="SCALE"&&b.geometry.setAttribute(U,d[U]);Bn.prototype.copy.call(D,b),this.parser.assignFinalMaterial(D),x.push(D)}return _.isGroup?(_.clear(),_.add(...x),_):x[0]}))}}const aC="glTF",im=12,sC={JSON:1313821514,BIN:5130562};class hF{constructor(e){this.name=Un.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,im),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!==aC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-im,o=new DataView(e,im);let l=0;for(;l<i;){const h=o.getUint32(l,!0);l+=4;const d=o.getUint32(l,!0);if(l+=4,d===sC.JSON){const p=new Uint8Array(e,im+l,h);this.content=n.decode(p)}else if(d===sC.BIN){const p=im+l;this.body=e.slice(p,p+h)}l+=h}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class dF{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Un.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,l=e.extensions[this.name].attributes,h={},d={},p={};for(const _ in l){const v=OS[_]||_.toLowerCase();h[v]=l[_]}for(const _ in e.attributes){const v=OS[_]||_.toLowerCase();if(l[_]!==void 0){const y=n.accessors[e.attributes[_]],x=kh[y.componentType];p[v]=x.name,d[v]=y.normalized===!0}}return t.getDependency("bufferView",o).then(function(_){return new Promise(function(v,y){i.decodeDracoFile(_,function(x){for(const b in x.attributes){const R=x.attributes[b],T=d[b];T!==void 0&&(R.normalized=T)}v(x)},h,p,ta,y)})})}}class pF{constructor(){this.name=Un.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 mF{constructor(){this.name=Un.KHR_MESH_QUANTIZATION}}class rC extends Pu{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let l=0;l!==i;l++)t[l]=n[o+l];return t}interpolate_(e,t,n,i){const o=this.resultBuffer,l=this.sampleValues,h=this.valueSize,d=h*2,p=h*3,_=i-t,v=(n-t)/_,y=v*v,x=y*v,b=e*p,R=b-p,T=-2*x+3*y,M=x-y,w=1-T,D=M-y+v;for(let U=0;U!==h;U++){const H=l[R+U+h],I=l[R+U+d]*_,z=l[b+U+h],k=l[b+U]*_;o[U]=w*H+D*I+T*z+M*k}return o}}const gF=new Ma;class vF extends rC{interpolate_(e,t,n,i){const o=super.interpolate_(e,t,n,i);return gF.fromArray(o).normalize().toArray(o),o}}const Mr={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},kh={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},oC={9728:Ai,9729:bn,9984:tp,9985:yu,9986:lc,9987:Fs},lC={33071:xi,33648:_u,10497:Jr},LS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},OS={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"},Bc={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},_F={CUBICSPLINE:void 0,LINEAR:uc,STEP:Au},IS={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function yF(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new Fu({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:kr})),s.DefaultMaterial}function nf(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Uo(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function xF(s,e,t){let n=!1,i=!1,o=!1;for(let p=0,_=e.length;p<_;p++){const v=e[p];if(v.POSITION!==void 0&&(n=!0),v.NORMAL!==void 0&&(i=!0),v.COLOR_0!==void 0&&(o=!0),n&&i&&o)break}if(!n&&!i&&!o)return Promise.resolve(s);const l=[],h=[],d=[];for(let p=0,_=e.length;p<_;p++){const v=e[p];if(n){const y=v.POSITION!==void 0?t.getDependency("accessor",v.POSITION):s.attributes.position;l.push(y)}if(i){const y=v.NORMAL!==void 0?t.getDependency("accessor",v.NORMAL):s.attributes.normal;h.push(y)}if(o){const y=v.COLOR_0!==void 0?t.getDependency("accessor",v.COLOR_0):s.attributes.color;d.push(y)}}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d)]).then(function(p){const _=p[0],v=p[1],y=p[2];return n&&(s.morphAttributes.position=_),i&&(s.morphAttributes.normal=v),o&&(s.morphAttributes.color=y),s.morphTargetsRelative=!0,s})}function AF(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function SF(s){let e;const t=s.extensions&&s.extensions[Un.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+FS(t.attributes):e=s.indices+":"+FS(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,i=s.targets.length;n<i;n++)e+=":"+FS(s.targets[n]);return e}function FS(s){let e="";const t=Object.keys(s).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+s[t[n]]+";";return e}function HS(s){switch(s){case Int8Array:return .007874015748031496;case Uint8Array:return .00392156862745098;case Int16Array:return 3051850947599719e-20;case Uint16Array:return 15259021896696422e-21;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function MF(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const bF=new $t;class EF{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new qI,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,o=!1,l=-1;if(typeof navigator<"u"){const h=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(h)===!0;const d=h.match(/Version\/(\d+)/);i=n&&d?parseInt(d[1],10):-1,o=h.indexOf("Firefox")>-1,l=o?h.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||o&&l<98?this.textureLoader=new uA(this.options.manager):this.textureLoader=new mA(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ha(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(l){return l._markDefs&&l._markDefs()}),Promise.all(this._invokeAll(function(l){return l.beforeRoot&&l.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(l){const h={scene:l[0][i.scene||0],scenes:l[0],animations:l[1],cameras:l[2],asset:i.asset,parser:n,userData:{}};return nf(o,h,i),Uo(h,i),Promise.all(n._invokeAll(function(d){return d.afterRoot&&d.afterRoot(h)})).then(function(){for(const d of h.scenes)d.updateMatrixWorld();e(h)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,o=t.length;i<o;i++){const l=t[i].joints;for(let h=0,d=l.length;h<d;h++)e[l[h]].isBone=!0}for(let i=0,o=e.length;i<o;i++){const l=e[i];l.mesh!==void 0&&(this._addNodeRef(this.meshCache,l.mesh),l.skin!==void 0&&(n[l.mesh].isSkinnedMesh=!0)),l.camera!==void 0&&this._addNodeRef(this.cameraCache,l.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),o=(l,h)=>{const d=this.associations.get(l);d!=null&&this.associations.set(h,d);for(const[p,_]of l.children.entries())o(_,h.children[p])};return o(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const o=e(t[i]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,l){return n.getDependency(e,l)})),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[Un.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(o,l){n.load(ir.resolveURL(t.uri,i.path),o,void 0,function(){l(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const l=LS[i.type],h=kh[i.componentType],d=i.normalized===!0,p=new h(i.count*l);return Promise.resolve(new On(p,l,d))}const o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(l){const h=l[0],d=LS[i.type],p=kh[i.componentType],_=p.BYTES_PER_ELEMENT,v=_*d,y=i.byteOffset||0,x=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,b=i.normalized===!0;let R,T;if(x&&x!==v){const M=Math.floor(y/x),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+M+":"+i.count;let D=t.cache.get(w);D||(R=new p(h,M*x,i.count*x/_),D=new yh(R,x/_),t.cache.add(w,D)),T=new Al(D,d,y%x/_,b)}else h===null?R=new p(i.count*d):R=new p(h,y,i.count*d),T=new On(R,d,b);if(i.sparse!==void 0){const M=LS.SCALAR,w=kh[i.sparse.indices.componentType],D=i.sparse.indices.byteOffset||0,U=i.sparse.values.byteOffset||0,H=new w(l[1],D,i.sparse.count*M),I=new p(l[2],U,i.sparse.count*d);h!==null&&(T=new On(T.array.slice(),T.itemSize,T.normalized)),T.normalized=!1;for(let z=0,k=H.length;z<k;z++){const N=H[z];if(T.setX(N,I[z*d]),d>=2&&T.setY(N,I[z*d+1]),d>=3&&T.setZ(N,I[z*d+2]),d>=4&&T.setW(N,I[z*d+3]),d>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}T.normalized=b}return T})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,l=t.images[o];let h=this.textureLoader;if(l.uri){const d=n.manager.getHandler(l.uri);d!==null&&(h=d)}return this.loadTextureImage(e,o,h)}loadTextureImage(e,t,n){const i=this,o=this.json,l=o.textures[e],h=o.images[t],d=(h.uri||h.bufferView)+":"+l.sampler;if(this.textureCache[d])return this.textureCache[d];const p=this.loadImageSource(t,n).then(function(_){_.flipY=!1,_.name=l.name||h.name||"",_.name===""&&typeof h.uri=="string"&&h.uri.startsWith("data:image/")===!1&&(_.name=h.uri);const y=(o.samplers||{})[l.sampler]||{};return _.magFilter=oC[y.magFilter]||bn,_.minFilter=oC[y.minFilter]||Fs,_.wrapS=lC[y.wrapS]||Jr,_.wrapT=lC[y.wrapT]||Jr,_.generateMipmaps=!_.isCompressedTexture&&_.minFilter!==Ai&&_.minFilter!==bn,i.associations.set(_,{textures:e}),_}).catch(function(){return null});return this.textureCache[d]=p,p}loadImageSource(e,t){const n=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(v=>v.clone());const l=i.images[e],h=self.URL||self.webkitURL;let d=l.uri||"",p=!1;if(l.bufferView!==void 0)d=n.getDependency("bufferView",l.bufferView).then(function(v){p=!0;const y=new Blob([v],{type:l.mimeType});return d=h.createObjectURL(y),d});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const _=Promise.resolve(d).then(function(v){return new Promise(function(y,x){let b=y;t.isImageBitmapLoader===!0&&(b=function(R){const T=new Kn(R);T.needsUpdate=!0,y(T)}),t.load(ir.resolveURL(v,o.path),b,void 0,x)})}).then(function(v){return p===!0&&h.revokeObjectURL(d),Uo(v,l),v.userData.mimeType=l.mimeType||MF(l.uri),v}).catch(function(v){throw console.error("THREE.GLTFLoader: Couldn't load texture",d),v});return this.sourceCache[e]=_,_}assignTexture(e,t,n,i){const o=this;return this.getDependency("texture",n.index).then(function(l){if(!l)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(l=l.clone(),l.channel=n.texCoord),o.extensions[Un.KHR_TEXTURE_TRANSFORM]){const h=n.extensions!==void 0?n.extensions[Un.KHR_TEXTURE_TRANSFORM]:void 0;if(h){const d=o.associations.get(l);l=o.extensions[Un.KHR_TEXTURE_TRANSFORM].extendTexture(l,h),o.associations.set(l,d)}}return i!==void 0&&(l.colorSpace=i),e[t]=l,l})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,l=t.attributes.normal===void 0;if(e.isPoints){const h="PointsMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Up,zi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,d.sizeAttenuation=!1,this.cache.add(h,d)),n=d}else if(e.isLine){const h="LineBasicMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Ga,zi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,this.cache.add(h,d)),n=d}if(i||o||l){let h="ClonedMaterial:"+n.uuid+":";i&&(h+="derivative-tangents:"),o&&(h+="vertex-colors:"),l&&(h+="flat-shading:");let d=this.cache.get(h);d||(d=n.clone(),o&&(d.vertexColors=!0),l&&(d.flatShading=!0),i&&(d.normalScale&&(d.normalScale.y*=-1),d.clearcoatNormalScale&&(d.clearcoatNormalScale.y*=-1)),this.cache.add(h,d),this.associations.set(d,this.associations.get(n))),n=d}e.material=n}getMaterialType(){return Fu}loadMaterial(e){const t=this,n=this.json,i=this.extensions,o=n.materials[e];let l;const h={},d=o.extensions||{},p=[];if(d[Un.KHR_MATERIALS_UNLIT]){const v=i[Un.KHR_MATERIALS_UNLIT];l=v.getMaterialType(),p.push(v.extendParams(h,o,t))}else{const v=o.pbrMetallicRoughness||{};if(h.color=new Mt(1,1,1),h.opacity=1,Array.isArray(v.baseColorFactor)){const y=v.baseColorFactor;h.color.setRGB(y[0],y[1],y[2],ta),h.opacity=y[3]}v.baseColorTexture!==void 0&&p.push(t.assignTexture(h,"map",v.baseColorTexture,Gi)),h.metalness=v.metallicFactor!==void 0?v.metallicFactor:1,h.roughness=v.roughnessFactor!==void 0?v.roughnessFactor:1,v.metallicRoughnessTexture!==void 0&&(p.push(t.assignTexture(h,"metalnessMap",v.metallicRoughnessTexture)),p.push(t.assignTexture(h,"roughnessMap",v.metallicRoughnessTexture))),l=this._invokeOne(function(y){return y.getMaterialType&&y.getMaterialType(e)}),p.push(Promise.all(this._invokeAll(function(y){return y.extendMaterialParams&&y.extendMaterialParams(e,h)})))}o.doubleSided===!0&&(h.side=js);const _=o.alphaMode||IS.OPAQUE;if(_===IS.BLEND?(h.transparent=!0,h.depthWrite=!1):(h.transparent=!1,_===IS.MASK&&(h.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&l!==fa&&(p.push(t.assignTexture(h,"normalMap",o.normalTexture)),h.normalScale=new et(1,1),o.normalTexture.scale!==void 0)){const v=o.normalTexture.scale;h.normalScale.set(v,v)}if(o.occlusionTexture!==void 0&&l!==fa&&(p.push(t.assignTexture(h,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(h.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&l!==fa){const v=o.emissiveFactor;h.emissive=new Mt().setRGB(v[0],v[1],v[2],ta)}return o.emissiveTexture!==void 0&&l!==fa&&p.push(t.assignTexture(h,"emissiveMap",o.emissiveTexture,Gi)),Promise.all(p).then(function(){const v=new l(h);return o.name&&(v.name=o.name),Uo(v,o),t.associations.set(v,{materials:e}),o.extensions&&nf(i,v,o),v})}createUniqueName(e){const t=Pn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function o(h){return n[Un.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(h,t).then(function(d){return cC(d,h,t)})}const l=[];for(let h=0,d=e.length;h<d;h++){const p=e[h],_=SF(p),v=i[_];if(v)l.push(v.promise);else{let y;p.extensions&&p.extensions[Un.KHR_DRACO_MESH_COMPRESSION]?y=o(p):y=cC(new cn,p,t),i[_]={primitive:p,promise:y},l.push(y)}}return Promise.all(l)}loadMesh(e){const t=this,n=this.json,i=this.extensions,o=n.meshes[e],l=o.primitives,h=[];for(let d=0,p=l.length;d<p;d++){const _=l[d].material===void 0?yF(this.cache):this.getDependency("material",l[d].material);h.push(_)}return h.push(t.loadGeometries(l)),Promise.all(h).then(function(d){const p=d.slice(0,d.length-1),_=d[d.length-1],v=[];for(let x=0,b=_.length;x<b;x++){const R=_[x],T=l[x];let M;const w=p[x];if(T.mode===Mr.TRIANGLES||T.mode===Mr.TRIANGLE_STRIP||T.mode===Mr.TRIANGLE_FAN||T.mode===void 0)M=o.isSkinnedMesh===!0?new tv(R,w):new mi(R,w),M.isSkinnedMesh===!0&&M.normalizeSkinWeights(),T.mode===Mr.TRIANGLE_STRIP?M.geometry=iC(M.geometry,fp):T.mode===Mr.TRIANGLE_FAN&&(M.geometry=iC(M.geometry,bu));else if(T.mode===Mr.LINES)M=new yr(R,w);else if(T.mode===Mr.LINE_STRIP)M=new Ro(R,w);else if(T.mode===Mr.LINE_LOOP)M=new hv(R,w);else if(T.mode===Mr.POINTS)M=new mv(R,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+T.mode);Object.keys(M.geometry.morphAttributes).length>0&&AF(M,o),M.name=t.createUniqueName(o.name||"mesh_"+e),Uo(M,o),T.extensions&&nf(i,M,T),t.assignFinalMaterial(M),v.push(M)}for(let x=0,b=v.length;x<b;x++)t.associations.set(v[x],{meshes:e,primitives:x});if(v.length===1)return o.extensions&&nf(i,v[0],o),v[0];const y=new vr;o.extensions&&nf(i,y,o),t.associations.set(y,{meshes:e});for(let x=0,b=v.length;x<b;x++)y.add(v[x]);return y})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new ia(T0.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new Tl(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Uo(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,o=t.joints.length;i<o;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const o=i.pop(),l=i,h=[],d=[];for(let p=0,_=l.length;p<_;p++){const v=l[p];if(v){h.push(v);const y=new $t;o!==null&&y.fromArray(o.array,p*16),d.push(y)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[p])}return new bh(h,d)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,l=[],h=[],d=[],p=[],_=[];for(let v=0,y=i.channels.length;v<y;v++){const x=i.channels[v],b=i.samplers[x.sampler],R=x.target,T=R.node,M=i.parameters!==void 0?i.parameters[b.input]:b.input,w=i.parameters!==void 0?i.parameters[b.output]:b.output;R.node!==void 0&&(l.push(this.getDependency("node",T)),h.push(this.getDependency("accessor",M)),d.push(this.getDependency("accessor",w)),p.push(b),_.push(R))}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d),Promise.all(p),Promise.all(_)]).then(function(v){const y=v[0],x=v[1],b=v[2],R=v[3],T=v[4],M=[];for(let D=0,U=y.length;D<U;D++){const H=y[D],I=x[D],z=b[D],k=R[D],N=T[D];if(H===void 0)continue;H.updateMatrix&&H.updateMatrix();const F=n._createAnimationTracks(H,I,z,k,N);if(F)for(let W=0;W<F.length;W++)M.push(F[W])}const w=new Vu(o,void 0,M);return Uo(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(o){const l=n._getNodeRef(n.meshCache,i.mesh,o);return i.weights!==void 0&&l.traverse(function(h){if(h.isMesh)for(let d=0,p=i.weights.length;d<p;d++)h.morphTargetInfluences[d]=i.weights[d]}),l})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],o=n._loadNodeShallow(e),l=[],h=i.children||[];for(let p=0,_=h.length;p<_;p++)l.push(n.getDependency("node",h[p]));const d=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([o,Promise.all(l),d]).then(function(p){const _=p[0],v=p[1],y=p[2];y!==null&&_.traverse(function(x){x.isSkinnedMesh&&x.bind(y,bF)});for(let x=0,b=v.length;x<b;x++)_.add(v[x]);return _})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],l=o.name?i.createUniqueName(o.name):"",h=[],d=i._invokeOne(function(p){return p.createNodeMesh&&p.createNodeMesh(e)});return d&&h.push(d),o.camera!==void 0&&h.push(i.getDependency("camera",o.camera).then(function(p){return i._getNodeRef(i.cameraCache,o.camera,p)})),i._invokeAll(function(p){return p.createNodeAttachment&&p.createNodeAttachment(e)}).forEach(function(p){h.push(p)}),this.nodeCache[e]=Promise.all(h).then(function(p){let _;if(o.isBone===!0?_=new Cp:p.length>1?_=new vr:p.length===1?_=p[0]:_=new Bn,_!==p[0])for(let v=0,y=p.length;v<y;v++)_.add(p[v]);if(o.name&&(_.userData.name=o.name,_.name=l),Uo(_,o),o.extensions&&nf(n,_,o),o.matrix!==void 0){const v=new $t;v.fromArray(o.matrix),_.applyMatrix4(v)}else o.translation!==void 0&&_.position.fromArray(o.translation),o.rotation!==void 0&&_.quaternion.fromArray(o.rotation),o.scale!==void 0&&_.scale.fromArray(o.scale);if(!i.associations.has(_))i.associations.set(_,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){const v=i.associations.get(_);i.associations.set(_,{...v})}return i.associations.get(_).nodes=e,_}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,o=new vr;n.name&&(o.name=i.createUniqueName(n.name)),Uo(o,n),n.extensions&&nf(t,o,n);const l=n.nodes||[],h=[];for(let d=0,p=l.length;d<p;d++)h.push(i.getDependency("node",l[d]));return Promise.all(h).then(function(d){for(let _=0,v=d.length;_<v;_++)o.add(d[_]);const p=_=>{const v=new Map;for(const[y,x]of i.associations)(y instanceof zi||y instanceof Kn)&&v.set(y,x);return _.traverse(y=>{const x=i.associations.get(y);x!=null&&v.set(y,x)}),v};return i.associations=p(o),o})}_createAnimationTracks(e,t,n,i,o){const l=[],h=e.name?e.name:e.uuid,d=[];Bc[o.path]===Bc.weights?e.traverse(function(y){y.morphTargetInfluences&&d.push(y.name?y.name:y.uuid)}):d.push(h);let p;switch(Bc[o.path]){case Bc.weights:p=Sl;break;case Bc.rotation:p=Ml;break;case Bc.translation:case Bc.scale:p=bl;break;default:n.itemSize===1?p=Sl:p=bl;break}const _=i.interpolation!==void 0?_F[i.interpolation]:uc,v=this._getArrayFromAccessor(n);for(let y=0,x=d.length;y<x;y++){const b=new p(d[y]+"."+Bc[o.path],t.array,v,_);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),l.push(b)}return l}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=HS(t.constructor),i=new Float32Array(t.length);for(let o=0,l=t.length;o<l;o++)i[o]=t[o]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof Ml?vF:rC;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function TF(s,e,t){const n=e.attributes,i=new ba;if(n.POSITION!==void 0){const h=t.json.accessors[n.POSITION],d=h.min,p=h.max;if(d!==void 0&&p!==void 0){if(i.set(new Z(d[0],d[1],d[2]),new Z(p[0],p[1],p[2])),h.normalized){const _=HS(kh[h.componentType]);i.min.multiplyScalar(_),i.max.multiplyScalar(_)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const h=new Z,d=new Z;for(let p=0,_=o.length;p<_;p++){const v=o[p];if(v.POSITION!==void 0){const y=t.json.accessors[v.POSITION],x=y.min,b=y.max;if(x!==void 0&&b!==void 0){if(d.setX(Math.max(Math.abs(x[0]),Math.abs(b[0]))),d.setY(Math.max(Math.abs(x[1]),Math.abs(b[1]))),d.setZ(Math.max(Math.abs(x[2]),Math.abs(b[2]))),y.normalized){const R=HS(kh[y.componentType]);d.multiplyScalar(R)}h.max(d)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(h)}s.boundingBox=i;const l=new ua;i.getCenter(l.center),l.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=l}function cC(s,e,t){const n=e.attributes,i=[];function o(l,h){return t.getDependency("accessor",l).then(function(d){s.setAttribute(h,d)})}for(const l in n){const h=OS[l]||l.toLowerCase();h in s.attributes||i.push(o(n[l],h))}if(e.indices!==void 0&&!s.index){const l=t.getDependency("accessor",e.indices).then(function(h){s.setIndex(h)});i.push(l)}return Cn.workingColorSpace!==ta&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Cn.workingColorSpace}" not supported.`),Uo(s,e),TF(s,e,t),Promise.all(i).then(function(){return e.targets!==void 0?xF(s,e.targets,t):s})}const $a=(...s)=>{},CF=(...s)=>{},uC=({analyser:s})=>{const e=Ce.useRef(null),t=Ce.useRef(null);return Ce.useEffect(()=>{const n=e.current;if(!n)return;const i=n.getContext("2d",{alpha:!0});if(!i)return;let o,l=null;s&&(s.fftSize=128,l=new Uint8Array(s.frequencyBinCount));const h=()=>{o=requestAnimationFrame(h),(n.width!==n.offsetWidth||n.height!==n.offsetHeight)&&(n.width=n.offsetWidth,n.height=n.offsetHeight);const d=n.width,p=n.height;if(d===0||p===0)return;const _=p/2;i.clearRect(0,0,d,p),i.fillStyle="#1e293b";const v=2,x=v+2,b=d*.95,R=Math.floor(b/x);(!t.current||t.current.length!==R)&&(t.current=new Float32Array(R).fill(2));const T=R*x,M=(d-T)/2;s&&l&&s.getByteFrequencyData(l);const w=l?l.length:0,U=Math.floor(w*.7)/R,H=new Float32Array(R);for(let I=0;I<R;I++){let z=0;if(l&&U>0){const F=Math.floor(I*U),W=Math.floor((I+1)*U);for(let ae=F;ae<W;ae++){const ie=l[ae]||0;ie>z&&(z=ie)}}z<10&&(z=0);const k=z/255,N=z>0?Math.max(2,Math.pow(k,1.4)*p*.25):2;H[I]=N}for(let I=0;I<R;I++){const z=R-1-I,k=Math.max(H[I],H[z]),N=t.current[I]+(k-t.current[I])*.3;t.current[I]=N;const F=M+I*x,W=_-N/2;i.beginPath(),i.roundRect?i.roundRect(F,W,v,N,4):i.fillRect(F,W,v,N),i.fill()}};return h(),()=>{cancelAnimationFrame(o)}},[s]),Vt.jsx("canvas",{ref:e,style:{width:"100%",height:"100%",display:"block"}})},fC="https://ai.streamoji.com",RF="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev";async function wF(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}function BF(s){const[e,t]=Ce.useState(null);return Ce.useEffect(()=>{if(!s){t(null);return}let n=!1;return wF(s).then(i=>{if(n)return;const o=`${RF}/${i}.glb`;fetch(o,{method:"HEAD"}).then(l=>{n||t(l.ok?o:null)}).catch(()=>{n||t(null)})}),()=>{n=!0}},[s]),e}const DF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],UF=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],NF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"],LF={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},OF=[-.45,1.9,.1],IF={browInnerUp:.2},PS=.18,FF=1,m_={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},HF=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],PF={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]};function GF(s){if(!s)return[{v:"sil",w:1}];const e=s.toLowerCase();return PF[e]??[{v:"sil",w:1}]}function zF({target:s}){const{camera:e}=Ih();return Ce.useEffect(()=>{e.lookAt(...s)},[e,s]),null}function zs(s,e,t){if(!s||!s.morphTargetDictionary)return;const n=s,i=n.morphTargetDictionary,o=n.morphTargetInfluences;if(o)for(const l in i)l.toLowerCase()===e.toLowerCase()&&(o[i[l]]=t)}function hC(s,e=.97){if(!s)return;const t=s;if(t.morphTargetInfluences)for(let n=0;n<t.morphTargetInfluences.length;n++)t.morphTargetInfluences[n]*=e}const VF=Ce.memo(({avatarUrl:s,isPlayingRef:e,visemeQueueRef:t,audioContextRef:n,responseAudioStartTimeRef:i,adjustments:o,mood:l,expression:h,agentResponse:d,isSpeaking:p,nextStartTimeRef:_,stopPlayback:v,setIsSpeaking:y,expressionUrl:x,onExpressionFinished:b})=>{const{scene:R}=zh(s),T=zh(DF),M=Ce.useMemo(()=>T.flatMap(Q=>Q.animations),[T]),w=zh(NF),D=Ce.useMemo(()=>w.flatMap(Q=>Q.animations),[w]),U=Ce.useRef(null),H=Ce.useRef(null),I=Ce.useRef(null),z=Ce.useRef([]),[k]=Ce.useState(()=>new aE(R)),N=Ce.useRef({}),F=Ce.useRef(null),W=Ce.useRef(0),ae=Ce.useRef(!1),ie=Ce.useRef(0),re=Ce.useRef(null);Ce.useEffect(()=>{if(!(!M||!R)){if(M.forEach((Q,ce)=>{const se=`idle_${ce}`;if(!N.current[se]){const X=k.clipAction(Q,R);X.name=se,X.setLoop(cp,1),X.clampWhenFinished=!0,N.current[se]=X}}),D.forEach((Q,ce)=>{const se=`talk_${ce}`;if(!N.current[se]){const X=k.clipAction(Q,R);X.name=se,X.setLoop(cp,1),X.clampWhenFinished=!0,N.current[se]=X}}),M.length>0){const Q=N.current.idle_0,ce=F.current&&k.existingAction(F.current.getClip());Q&&!ce&&(Q.reset().fadeIn(.5).play(),F.current=Q)}return()=>{k.stopAllAction(),N.current={},F.current=null}}},[M,D,R,k]);const _e=Ce.useRef("");Ce.useEffect(()=>{if(!x||!R||x===_e.current)return;_e.current=x,re.current=x,new JI().load(x,ce=>{if(ce.animations&&ce.animations.length>0){const se=ce.animations[0],X=k.clipAction(se,R);if(X.name=`EXPR_${x}`,X.setLoop(cp,1),X.clampWhenFinished=!0,N.current[`EXPR_${x}`]=X,p&&re.current===x){const ne=F.current;X.reset().fadeIn(.3).play(),ne&&ne!==X&&ne.crossFadeTo(X,.3,!0),F.current=X,re.current=null}}},void 0,ce=>{console.error(`[ANIMATION] Failed to load ${x}`,ce)})},[x,R,k,p]),Ce.useEffect(()=>{const Q=ce=>{const se=ce.action,X=se.name||"";if(X.startsWith("idle_")){const ye=(parseInt(X.split("_")[1])+1)%M.length,Ee=N.current[`idle_${ye}`];Ee&&(Ee.reset().fadeIn(.5).play(),se.crossFadeTo(Ee,.5,!0),F.current=Ee)}else if(X.startsWith("EXPR_")){if(p){const ne=N.current.talk_0;ne&&(ne.reset().fadeIn(.5).play(),se.crossFadeTo(ne,.5,!0),F.current=ne)}else{const ne=N.current.idle_0;ne&&(ne.reset().fadeIn(.5).play(),se.crossFadeTo(ne,.5,!0),F.current=ne)}b&&b()}else if(X.startsWith("talk_"))if(p){const ye=(parseInt(X.split("_")[1])+1)%D.length,Ee=N.current[`talk_${ye}`];Ee&&(Ee.reset().fadeIn(.3).play(),se.crossFadeTo(Ee,.3,!0),F.current=Ee)}else{const ne=N.current.idle_0;ne&&(ne.reset().fadeIn(.5).play(),se.crossFadeTo(ne,.5,!0),F.current=ne)}};return k.addEventListener("finished",Q),()=>k.removeEventListener("finished",Q)},[k,M,D,p,b]),Ce.useEffect(()=>{if(p&&R){const Q=F.current,ce=Q?.name||"";if(ce.startsWith("idle_")||ce.startsWith("talk_")||ce===""){const se=re.current;if(se){const X=N.current[`EXPR_${se}`];if(X){X.reset().fadeIn(.3).play(),Q&&Q!==X&&Q.crossFadeTo(X,.3,!0),F.current=X,re.current=null;return}}if(ce.startsWith("idle_")||ce===""){const X=N.current.talk_0;X&&(X.reset().fadeIn(.5).play(),Q&&Q.crossFadeTo(X,.5,!0),F.current=X)}}}else if(!p&&R){const Q=F.current,ce=Q?.name||"";if(ce.startsWith("talk_")||ce.startsWith("EXPR_")){const se=N.current.idle_0;se&&(se.reset().fadeIn(.5).play(),Q&&Q.crossFadeTo(se,.5,!0),F.current=se)}}},[p,R,x]),Ce.useEffect(()=>{if(!R)return;R.traverse(se=>{if(se.isMesh&&se.morphTargetDictionary){const X=se.name.toLowerCase();(X.includes("head")||X.includes("avatar"))&&(H.current=se,$a(`[ANIMATION] Found head mesh: ${se.name}`)),X.includes("teeth")&&(I.current=se,$a(`[ANIMATION] Found teeth mesh: ${se.name}`))}});const Q=H.current?.morphTargetDictionary;Q&&Object.keys(Q).filter(se=>se.toLowerCase().includes("brow"));const ce=[];R.traverse(se=>{if(se.isMesh){const ne=se.morphTargetDictionary;ne&&Object.keys(ne).some(ye=>ye.toLowerCase().includes("brow"))&&ce.push(se)}}),z.current=ce,ce.length>0&&$a("[ANIMATION] Meshes with brow morphs:",ce.length)},[R]);const P=(Q,ce=1)=>{const se=`viseme_${Q}`.toLowerCase(),X=HF.find(ne=>ne.key.toLowerCase()===se);if(X)for(const ne in X.mix){const ye=X.mix[ne]*ce;zs(H.current,ne,ye),zs(I.current,ne,ye)}},K=Q=>{const ce=m_[Q]??m_.neutral;for(const se in ce)zs(H.current,se,ce[se]),zs(I.current,se,ce[se])};return _T((Q,ce)=>{const se=Math.pow(.88,60*ce);hC(H.current,se),hC(I.current,se),K(l);const X=Q.clock.elapsedTime;let ne=0;if(Math.floor(X)%5===0&&Math.floor((X-ce)%5)!==0){let Pe=null;R.traverse($=>{$.name.toLowerCase().includes("hips")&&(Pe=$)});const ht=Pe?`Hips Y: ${Pe.position.y.toFixed(4)}`:"Hips not found";$a(`[ANIMATION] Mixer Time: ${k.time.toFixed(2)}, ${ht}`)}if(k.update(ce),X>W.current&&!ae.current&&(ae.current=!0,ie.current=X),ae.current){const ht=(X-ie.current)/.3;if(ht>=1)ae.current=!1,W.current=X+2+Math.random()*5;else{const $=ht<.5?ht*2:(1-ht)*2;zs(H.current,"eyeBlinkLeft",$),zs(H.current,"eyeBlinkRight",$),zs(I.current,"eyeBlinkLeft",$),zs(I.current,"eyeBlinkRight",$),ne=$*IF.browInnerUp}}const ye=m_[l]??m_.neutral,Ee=ye.browInnerUp??0,it=ye.browOuterUpLeft??0,ve=ye.browOuterUpRight??0,Be=X*FF,at=PS*Math.sin(Be),bt=PS*.7*Math.sin(Be+.7),Tt=PS*.7*Math.sin(Be+1.3),en=Pe=>Math.max(0,Math.min(1,Pe)),fn=en(Ee+at),Xt=en(it+bt),Fe=en(ve+Tt),$e=en(fn+ne);if(zs(H.current,"browInnerUp",$e),zs(I.current,"browInnerUp",$e),zs(H.current,"browOuterUpLeft",Xt),zs(I.current,"browOuterUpLeft",Xt),zs(H.current,"browOuterUpRight",Fe),zs(I.current,"browOuterUpRight",Fe),U.current){const Pe=e.current?0:o.rotation[1];U.current.rotation.y=T0.lerp(U.current.rotation.y,Pe,.1),U.current.position.set(...o.position),U.current.scale.setScalar(o.scale),U.current.rotation.x=o.rotation[0],U.current.rotation.z=o.rotation[2]}if(e.current&&n.current){const Pe=n.current.currentTime,Bt=(Pe-i.current)*1e3- -150;for(let ft=0;ft<t.current.length;ft++){const Dt=t.current[ft];Bt>=Dt.vtime&&Bt<Dt.vtime+Dt.vduration&&P(Dt.viseme,Dt.weight??1)}Pe>_.current+.5&&(v(),y(!1))}}),Vt.jsx("group",{ref:U,children:Vt.jsx("primitive",{object:R})})});function kF(s){return s?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():""}const XF=({token:s,agentToken:e,onNavigationRequested:t}={})=>{const n=s??e??"",i=BF(n||void 0),[o,l]=Ce.useState(""),[h,d]=Ce.useState(""),[p,_]=Ce.useState("Ready"),[v,y]=Ce.useState(!1),[x,b]=Ce.useState(!1),R=Ce.useRef(!1),T=Ce.useRef([]),M=Ce.useRef(0),w=Ce.useRef(!1),D=Ce.useRef([]),U=Ce.useRef(null),H=Ce.useRef([]);Ce.useRef([]);const I=Ce.useRef([]),z=Ce.useRef(0),k=Ce.useRef(0),N=Ce.useRef(0),F=Ce.useRef(0),[W,ae]=Ce.useState(null),ie=Ce.useRef(null),[re,_e]=Ce.useState("neutral"),[P,K]=Ce.useState(""),[Q,ce]=Ce.useState(""),[se,X]=Ce.useState("Chat with us"),[ne,ye]=Ce.useState(null),[Ee,it]=Ce.useState("hidden"),[ve,Be]=Ce.useState(""),at=Ce.useRef(null),bt=Ce.useRef(Ee);bt.current=Ee;const[Tt,en]=Ce.useState(null),fn=Ce.useRef(null),Xt=Ce.useRef(null),[Fe,$e]=Ce.useState("hidden"),[Pe,ht]=Ce.useState(""),$=Ce.useRef(Fe);$.current=Fe;const Bt=Ce.useRef(""),ft=Ce.useRef(!1),Dt=Ce.useRef(""),dt=Ce.useMemo(()=>p==="Thinking..."||p==="Processing Voice..."?p:ne!=null&&ne!==""&&ne!=="none"&&ne!=="<none>"?`Enter ${kF(ne)}`:null,[p,ne]),j=dt!=null&&dt!=="";Ce.useEffect(()=>{const rt=bt.current;if(!(rt==="exiting"||rt==="entering")){if(rt==="hidden"){j&&(Be(dt??""),it("entering"));return}rt==="visible"&&(!j||dt!==ve)&&(at.current=j?dt:null,it("exiting"))}},[j,dt,Ee,ve]);const G=Ce.useCallback(()=>{const rt=bt.current;if(rt==="exiting"){it("hidden");const pt=at.current;at.current=null,pt!=null&&pt!==""&&(Be(pt),it("entering"))}else rt==="entering"&&it("visible")},[]),pe=rt=>{if(!rt)return;if(rt.mood!=null){const ee=String(rt.mood).toLowerCase();_e(ee)}if(rt.expression!=null){const ee=String(rt.expression).trim();K(ee);const ge=UF.find(Me=>Me.name.toLowerCase()===ee.toLowerCase());$a(`[STREAM] Animation match for "${ee}": ${ge?ge.name:"NONE"}`),ce(ge?.url??"")}if(rt.navigation!=null){const ee=String(rt.navigation).trim();ee!==""&&(t?t(ee):window.open(ee,"_blank"))}const pt=rt.ask_for||rt.lead_capture?.ask_for,O=pt?String(pt).trim().toLowerCase():"",Y=O==="none"||O==="<none>";if(pt&&!Y){const ee=O;ye(ee||null),X(ee==="email"?"Enter your email":ee==="name"?"Enter your name":ee==="phone"?"Enter your phone number":"Chat with us")}else(Y||rt.ask_for===null||rt.lead_capture&&rt.lead_capture.ask_for===null||rt.ask_for==="none")&&(ye(null),se!=="Chat with us"&&X("Chat with us"));rt.collected,rt.valid},Oe=rt=>{const pt=rt.trim();if(!pt)return null;if(pt.startsWith("{"))try{return JSON.parse(pt)}catch{return null}if(pt.includes(":")){const O=pt.split(":"),Y=O[0].trim().toLowerCase(),ee=O.slice(1).join(":").trim();return{[Y]:ee}}return null},Ye=Ce.useCallback(()=>{},[]),Le=rt=>{if(ft.current)rt==="§"?ft.current=!1:(Dt.current+=rt,d(pt=>pt+rt));else if(rt==="§"){ft.current=!0;return}else for(Bt.current+=rt;Bt.current.includes(`
4150
4150
  `);){const pt=Bt.current.indexOf(`
4151
4151
  `),O=Bt.current.slice(0,pt).trim();Bt.current=Bt.current.slice(pt+1);const Y=Oe(O);Y&&pe(Y)}};Ce.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const O="secret",Y=Math.floor(Date.now()/1e3).toString();try{const ee=new TextEncoder,ge=await crypto.subtle.importKey("raw",ee.encode(O),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),Me=await crypto.subtle.sign("HMAC",ge,ee.encode(Y)),Ze=Array.from(new Uint8Array(Me)).map(He=>He.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",Ze),$a("[SESSION] New HMAC UID generated and saved:",Ze)}catch(ee){console.error("[SESSION] HMAC generation failed:",ee);const ge=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",ge)}}sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[]);const Lt=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},xt=rt=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(rt))},[Ot,kt]=Ce.useState(!1),[Je,qe]=Ce.useState(0),_t=Ce.useRef(null),At=Ce.useRef([]),ot=Ce.useRef(0),[Ht,me]=Ce.useState(null),[Ue,st]=Ce.useState(null),St=Ce.useRef(null),je=Ce.useRef(null),ke=Ce.useCallback(()=>{D.current=[],w.current=!1,b(!1),z.current=0,k.current=0,N.current=0,H.current.forEach(rt=>{try{rt.stop()}catch{}}),fn.current&&(clearTimeout(fn.current),fn.current=null),en(null),ce(""),H.current=[]},[]),mt=async()=>{try{const rt=await navigator.mediaDevices.getUserMedia({audio:!0}),pt=window.AudioContext||window.webkitAudioContext,O=new pt,Y=O.createMediaStreamSource(rt),ee=O.createAnalyser();ee.fftSize=64,Y.connect(ee),St.current=O,je.current=Y,st(ee);const ge=new MediaRecorder(rt);_t.current=ge,At.current=[],ge.ondataavailable=Me=>{Me.data.size>0&&At.current.push(Me.data)},ge.onstop=async()=>{const Me=Date.now()-ot.current;if(st(null),je.current&&(je.current.disconnect(),je.current=null),St.current&&St.current.state!=="closed"&&(St.current.close(),St.current=null),Me<1e3){_("Recording too short. Hold or click longer."),y(!1);return}const be=new Blob(At.current,{type:"audio/wav"});await Ca(be)},ot.current=Date.now(),ge.start(100),kt(!0),_("Listening...")}catch(rt){console.error("Error accessing microphone:",rt),_("Mic Access Error")}},tn=()=>{_t.current&&_t.current.state!=="inactive"&&(_t.current.stop(),_t.current.stream.getTracks().forEach(rt=>rt.stop()),kt(!1))},Tn=()=>{_t.current&&_t.current.state!=="inactive"&&(_t.current.onstop=null,_t.current.stop(),_t.current.stream.getTracks().forEach(rt=>rt.stop()),st(null),je.current&&(je.current.disconnect(),je.current=null),St.current&&St.current.state!=="closed"&&(St.current.close(),St.current=null),kt(!1),At.current=[],_("Ready"))};Ce.useEffect(()=>{if(!x)return;const rt=()=>{const pt=N.current;if(pt<=0)return;const O=U.current,Y=z.current;if(!O)return;const ee=O.currentTime-Y,ge=Math.min(Math.max(0,ee),pt),Me=h.trim().length;if(Me<=0)return;const be=Math.min(Math.round(ge/pt*Me),Me);ae(be)};return clearInterval(ie.current??void 0),ie.current=setInterval(rt,90),()=>clearInterval(ie.current??void 0)},[x,h,N.current]),Ce.useEffect(()=>{let rt;return Ot?(qe(0),rt=window.setInterval(()=>{qe(pt=>pt+1)},1e3)):qe(0),()=>clearInterval(rt)},[Ot]);const yn=rt=>{const pt=rt.numberOfChannels,O=rt.length*pt*2+44,Y=new ArrayBuffer(O),ee=new DataView(Y);let ge=0;const Me=Ve=>{ee.setUint16(ge,Ve,!0),ge+=2},be=Ve=>{ee.setUint32(ge,Ve,!0),ge+=4};be(1179011410),be(O-8),be(1163280727),be(544501094),be(16),Me(1),Me(pt),be(rt.sampleRate),be(rt.sampleRate*2*pt),Me(pt*2),Me(16),be(1635017060),be(O-ge-4);const Ze=[];for(let Ve=0;Ve<pt;Ve++)Ze.push(rt.getChannelData(Ve));let He=0;for(;ge<O;){for(let Ve=0;Ve<pt;Ve++){let Ge=Math.max(-1,Math.min(1,Ze[Ve][He]));Ge=Ge<0?Ge*32768:Ge*32767,ee.setInt16(ge,Ge,!0),ge+=2}He++}return new Blob([Y],{type:"audio/wav"})},vi=async(rt,pt,O=!1)=>{if(R.current){T.current.push({audio:rt,visemes:pt,isNewSegment:O});return}R.current=!0;try{const Y=window.AudioContext||window.webkitAudioContext,ee=U.current??new Y;ee.state==="suspended"&&await ee.resume(),U.current=ee;const ge=window.atob(rt),Me=new Uint8Array(ge.length);for(let V=0;V<ge.length;V++)Me[V]=ge.charCodeAt(V);const be=await ee.decodeAudioData(Me.buffer.slice(0));N.current+=be.duration;const Ze=ee.currentTime;let He=k.current;const Ve=!w.current;He<Ze&&(He=Ze+.1),k.current=He+be.duration;const Ge=ee.createBufferSource();Ge.buffer=be;let tt=Ht;if((!tt||tt.context!==ee)&&(tt=ee.createAnalyser(),tt.fftSize=64,tt.connect(ee.destination),me(tt)),Ge.connect(tt),H.current.push(Ge),Ve){w.current=!0,b(!0),$a(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${He.toFixed(3)}`),z.current=He;const V=(He-Ze)*1e3;M.current=performance.now()+V,$a(`[AUDIO] Response started. Initial startTime: ${He.toFixed(3)}, CT: ${Ze.toFixed(3)}`)}Ge.start(He);const nt=(He-z.current)*1e3;O&&(F.current=nt,$a(`[AUDIO] New segment detected at +${nt.toFixed(0)}ms. Resetting segment offset.`)),pt.forEach((V,te)=>{const ue=V.symbol??"";if(ue){const he=GF(ue),fe=Math.round(V.start*1e3),We=Math.round((V.duration??0)*1e3),lt=F.current+fe;te<3&&$a(`[AUDIO] Viseme "${ue}": segment_relative=${fe}ms, segment_offset=${F.current.toFixed(0)}ms => vtime=${lt}ms`),he.forEach(ct=>{D.current.push({viseme:ct.v,weight:ct.w,vtime:lt,vduration:We})})}}),_("Speaking...")}finally{if(R.current=!1,T.current.length>0){const Y=T.current.shift();Y&&vi(Y.audio,Y.visemes,Y.isNewSegment)}}},Ca=async rt=>{try{y(!0),Dt.current="",d(""),_("Processing Voice...");const pt=await rt.arrayBuffer(),Y=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(pt),ee=yn(Y),ge=new FileReader;ge.readAsDataURL(ee),ge.onloadend=async()=>{const Me=ge.result.split(",")[1];ke(),l(""),Bt.current="",ft.current=!1;const be=`${fC}/stt?token=${encodeURIComponent(n)}`,Ze=await fetch(be,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:Me,audio_format:"wav"})});if(!Ze.ok){const te=await Ze.text();let ue="STT Failed";try{ue=JSON.parse(te).error||ue}catch{te&&(ue=te.slice(0,200))}throw new Error(ue)}const He=Ze.body;if($a("this is body"+He),!He){_("STT Failed"),y(!1);return}const Ve=He.getReader(),Ge=new TextDecoder;let tt="",nt=!1;const V=async(te,ue)=>{switch(te){case"transcript":ue.transcript!=null&&l(String(ue.transcript));break;case"text":{const he=ue.delta??ue.text??"";he&&Le(he);break}case"audio":{const he=ue.chunk,fe=ue.visemes??[],We=!!ue.is_new_segment;he&&await vi(he,fe,We);break}case"done":{nt=!0,_("Ready"),y(!1);break}case"error":{nt=!0,_("STT Failed"),y(!1);break}default:break}};for(;;){const{done:te,value:ue}=await Ve.read();ue&&(tt+=Ge.decode(ue,{stream:!0}));const he=tt.split(`
4152
4152